From bf819d7c752770d965fa1a03e588196344e583c5 Mon Sep 17 00:00:00 2001 From: Ravishankar Chavare Date: 2023εΉ΄8月27ζ—₯ 19:36:51 +0530 Subject: [PATCH 1/2] w34 added --- doc/newsletters/2023/WEEK_34.md | 230 ++++++++++++++++++++++++++++++++ doc/newsletters/index.2023.rst | 1 + 2 files changed, 231 insertions(+) create mode 100644 doc/newsletters/2023/WEEK_34.md diff --git a/doc/newsletters/2023/WEEK_34.md b/doc/newsletters/2023/WEEK_34.md new file mode 100644 index 0000000..48dce53 --- /dev/null +++ b/doc/newsletters/2023/WEEK_34.md @@ -0,0 +1,230 @@ + +# Week 34 - Augest 2023 + + +## 1. πŸ“° The 'Title()' Method and Its Nuances(Limitations) + +The `title()` method is a versatile tool for enhancing text formatting. However, it's essential to recognize its limitations. The title() method isn't just about capitalizing; it also handles special characters and maintains proper casing rules. + + + Let's explore some insights: + +πŸ” **Use Case 1: Letters Only** +```python +text = "pycon 2023" +formatted_text = text.title() +print(formatted_text) # Output: Pycon 2023 +``` + +πŸ“‹ **Use Case 2: Alphanumeric Exploration** +```python +text = "python3.10_release" +formatted_text = text.title() +print(formatted_text) # Output: Python3.10_Release +``` + +πŸ“„ **Use Case 3: Punctuation Perspective** +```python +text = "don't STOP believin'!" +formatted_text = text.title() +print(formatted_text) # Output: Don'T Stop Believin'! +``` + + +## 2. πŸ“š Run A Python Module Directly With `__main__.py` + +The `__main__.py` file empowers you to seamlessly convert your Python module into an executable script, enhancing usability and efficiency. + +Have you ever wished to run a Python module directly as if it were a script? The `__main__.py` file holds the key! Let's explore a captivating use case that showcases its remarkable potential: + +πŸ” **Use Case: Transforming Modules into Scripts** +``` +my_module/ +|-- __main__.py +|-- helper_functions.py +``` + +```python +# file : helper_functions.py + +def some_function(): + return "Python World" +``` + +Imagine you have a module named `my_module` containing useful functions. By adding the following code to `__main__.py`, you can make your module directly executable: +```python +from helper_functions import * + +if __name__ == "__main__": + # Your script logic goes here + result = some_function() + print("Result:", result) +``` + +Now, executing `python my_module` directly from the command line runs the script within the `__main__.py` file, providing instant access to your module's functionality without additional steps. + + +## 3. πŸ” Unraveling Dictionary Literals and Constructors + +Dictionaries are fundamental for storing and accessing key-value data, and Python's versatility in creating them caters to various scenarios. + +Dictionaries are essential data structures in Python, and the methods to create them are fascinating. Let's explore these methods along with some captivating use cases: + +πŸ” **Use Case 1: Dictionary Literals** +```python +employee = {'name': 'Alice', 'age': 30, 'department': 'HR'} +``` +Dictionary literals allow you to create dictionaries directly by listing key-value pairs enclosed in curly braces. Perfect for concise and readable code. + +πŸ“‹ **Use Case 2: Dictionary Constructor** +```python +colors = dict(red='#FF0000', green='#00FF00', blue='#0000FF') +``` +The dictionary constructor lets you create dictionaries using the built-in `dict()` function. Ideal for dynamically constructing dictionaries from various sources. + +πŸ“„ **Use Case 3: Merging Dictionaries** +```python +defaults = {'theme': 'light', 'font_size': 12} +user_preferences = {'font_size': 14, 'language': 'en'} +merged_preferences = {**defaults, **user_preferences} +``` +Combine dictionaries effortlessly by unpacking them into a new dictionary. A powerful technique for overriding default values. + +πŸ”— **Use Case 4: Creating Dynamic Dictionaries** +```python +keys = ['a', 'b', 'c'] +values = [1, 2, 3] +dynamic_dict = dict(zip(keys, values)) +``` +Construct dictionaries dynamically by using the `zip()` function to combine lists of keys and values. + + +**πŸš€ In a Nutshell:** + +Choose dictionary literals for straightforward dictionary creation, and opt for the dictionary constructor when you need more flexibility, such as when dynamically constructing dictionaries or merging multiple dictionaries. + + +## 4. 🧹 Discovering isort: The Art of Import Arrangement + +Import statements – a gateway to the world of functionality. But arranging them can be a challenge. Enter `isort`, the Python package that effortlessly arranges your imports for clarity and readability. Behold how easily you can get started: + +1. **Installation of isort** via pip: + + ``` + pip install isort + ``` + +2. **Running isort** on your Python file: + + ``` + isort your_file.py + ``` + + 🌟 Witness the transformation as your imports fall into a harmonious order! + +🌐 **A Symphony of Imports: Prioritize with Precision** + +Picture this: system packages, third-party modules, and local imports, all in symphonic order. `isort` brings this vision to life: + +```python +# Before isort +from flask import Flask, render_template +import os, sys +from datetime import datetime, timedelta +from my_local_module import my_function + +# After isort +import os +import sys +from datetime import datetime, timedelta + +from flask import Flask, render_template + +from my_local_module import my_function +``` + +🧩 **Custom Choreography: Tailoring isort to Your Tunes** + +`isort` is not just a one-size-fits-all solution; it dances to your rhythm. Craft your own dance steps with configuration options in `pyproject.toml`: + +```toml +# pyproject.toml +[tool.isort] +profile = "black" +line_length = 88 +known_third_party = ["flask", "requests"] +``` + +πŸ” **isort in Your Workflow Ensemble: Effortless Integration** + +Seamlessly blend `isort` into your development routine. Set it as a pre-commit hook using tools like `pre-commit`. Feel the magic as your imports gracefully align with every commit. + + + +## 5. πŸ•°οΈ Master Time with Python's Scheduler! + +In the chaotic world of programming, managing tasks at specific intervals is a breeze with Python's built-in `sched` module. Let's jump into a simple example to showcase its power: + +```python +import sched +import time + +def greet(name): + print(f"Hello, {name}! It's time to shine.") + +# Create a scheduler instance +scheduler = sched.scheduler(time.time, time.sleep) + +# Schedule the greeting +scheduler.enter(5, 1, greet, ("Python-world",)) + +# Run the scheduler +scheduler.run() +``` + +πŸš€ **Automation at Your Fingertips: Scheduled Tasks** + +Python's scheduler isn't limited to just delaying functions. You can schedule tasks at specific times, automate backups, and more. Here's a snippet to illustrate scheduling a task every hour: + +```python +import sched +import time + +def hourly_task(): + print("Performing hourly task!") + +scheduler = sched.scheduler(time.time, time.sleep) + +# Schedule the task every hour +interval = 3600 # 1 hour in seconds +while True: + scheduler.enter(interval, 1, hourly_task, ()) + scheduler.run() +``` + +⏳ **Cron-like Scheduling: `schedule` Library** + +For more advanced scheduling, the `schedule` library offers a cron-like syntax. Check out how easy it is to schedule tasks with this powerful tool: + +```python +import schedule +import time + +def daily_task(): + print("Daily task is due!") + +# Schedule a task to run daily at 3:30 PM +schedule.every().day.at("15:30").do(daily_task) + +while True: + schedule.run_pending() + time.sleep(1) +``` + +πŸ” **Tailoring to Your Time Needs: Versatility of Scheduling** + +Whether it's running regular maintenance scripts, sending automated emails, or managing data backups, Python's scheduler empowers you to automate tasks according to your precise timing needs. + +🌐 **Unlock the Potential of Python's Scheduler!** + +Say goodbye to manual task management and hello to efficient automation with Python's scheduler. From simple delays to intricate cron-like scheduling, Python has your back when it comes to managing time and tasks. \ No newline at end of file diff --git a/doc/newsletters/index.2023.rst b/doc/newsletters/index.2023.rst index 1a7edd9..7a55fad 100644 --- a/doc/newsletters/index.2023.rst +++ b/doc/newsletters/index.2023.rst @@ -3,6 +3,7 @@ .. toctree:: :maxdepth: 4 + Augest - Week 34 <2023/week_34.md> Augest - Week 33 <2023/week_33.md> Augest - Week 32 <2023/week_32.md> Augest - Week 31 <2023/week_31.md> From 0c007b66bf196033fe6dec65b3f89408453310ba Mon Sep 17 00:00:00 2001 From: Ravishankar Chavare Date: Sun, 3 Sep 2023 21:28:32 +0530 Subject: [PATCH 2/2] W35 added --- doc/newsletters/2023/WEEK_35.md | 261 ++++++++++++++++++++++++++++++++ doc/newsletters/index.2023.rst | 1 + 2 files changed, 262 insertions(+) create mode 100644 doc/newsletters/2023/WEEK_35.md diff --git a/doc/newsletters/2023/WEEK_35.md b/doc/newsletters/2023/WEEK_35.md new file mode 100644 index 0000000..ad1fd1c --- /dev/null +++ b/doc/newsletters/2023/WEEK_35.md @@ -0,0 +1,261 @@ + +# Week 35 - Septmember 2023 + + +## 1. πŸ“¦ Unveiling Descriptors: The Hidden Gems of Python + + +Descriptors are a fascinating, albeit less-explored aspect of Python. They allow you to customize attribute access on classes, providing a level of control and abstraction that can significantly enhance your code. + +A descriptor is a class that implements the special methods `__get__()`, `__set__()`, or `__delete__()` and is assigned to a class attribute. This magic trio opens the door to attribute management, validation, and computation. + +Descriptors and property decorators are not merely advanced Python features; they are powerful tools for crafting clean, maintainable, and robust code. Whether you're building a complex framework, a user-friendly API, or simply want to add some magic to your classes, these tools are worth mastering. + + +Let's dive deeper: + +```python +class DescriptorExample: + def __get__(self, instance, owner): + # Custom attribute retrieval logic + return instance._value + + def __set__(self, instance, value): + # Custom attribute assignment logic + instance._value = value + 10 # Add 10 + +class MyClass: + descriptor_attr = DescriptorExample() + +# Usage +obj = MyClass() +obj.descriptor_attr = 42 +print(obj.descriptor_attr) # 52 +``` + +**Elevating Control with Property Decorators πŸš€** + +Property decorators, often seen as the friendlier face of descriptors, provide an elegant way to manage class attributes without exposing the underlying descriptor machinery. + +By decorating a method with `@property`, you can define a computed attribute that appears as a regular attribute but allows you to add custom logic to its access. Similarly, `@property_name.setter` and `@property_name.deleter` decorators enable control over assignment and deletion. + +```python +class MyClass: + def __init__(self): + self._value = None + + @property + def value(self): + # Custom attribute retrieval logic + return self._value + + @value.setter + def value(self, new_value): + # Custom attribute assignment logic + self._value = new_value + +# Usage +obj = MyClass() +obj.value = 42 +print(obj.value) # 42 +``` + +**Practical Applications πŸ› οΈ** + +Understanding descriptors and property decorators opens doors to a plethora of practical applications, including: + +- **Data Validation**: Ensure attribute values meet specific criteria or constraints. +- **Computed Properties**: Create attributes with dynamic values calculated on the fly. +- **Access Control**: Implement read-only or write-only attributes. +- **Legacy Code Integration**: Retrofit descriptor behavior into existing codebases. + + + + +## 2. πŸ§™β€β™‚οΈ Dynamic Code Generation: Crafting Code on the Fly + +Dynamic code generation is the art of creating and manipulating Python code at runtime. This opens up a world of possibilities, enabling you to generate classes, functions, and code structures dynamically to solve complex problems and automate repetitive tasks. + +Imagine building a code generator that tailors Python scripts based on user input or generating data models from configuration files. With dynamic code generation, the possibilities are limitless. + +```python +# Dynamic function creation +def generate_multiply_function(factor): + def multiply(x): + return x * factor + return multiply + +# Usage +double = generate_multiply_function(2) +print(double(5)) # Output: 10 +``` + +**Metaprogramming: Code that Writes Code πŸ–‹οΈ** + +Metaprogramming takes dynamic code generation to the next level. It's about writing code that writes or manipulates other code. This powerful technique is often used in frameworks, libraries, and code generators to simplify complex tasks. + +Metaclasses, decorators, and class factories are common tools in the metaprogrammer's toolbox. They allow you to control class creation, customize attribute access, and modify the behavior of functions and methods. + +```python +# Metaclass example +class MyMeta(type): + def __new__(cls, name, bases, dct): + # Customize class creation + dct['custom_attribute'] = 42 + return super().__new__(cls, name, bases, dct) + +class MyClass(metaclass=MyMeta): + pass + +# Usage +obj = MyClass() +print(obj.custom_attribute) # Output: 42 +``` + +**Practical Applications: Where the Magic Happens 🌟** + +Dynamic code generation and metaprogramming aren't just theoretical concepts; they have practical applications across various domains: + +- **Code Generators**: Automate code generation for repetitive tasks and template-based code. + +- **Configuration-driven Development**: Create dynamic configurations that generate code based on user-defined parameters. + +- **Domain-Specific Languages (DSLs)**: Build custom languages tailored to specific tasks or industries. + +- **Framework and Library Development**: Simplify complex APIs and extend framework functionality. + + + +## 3. 🐍 Avoid These 5 Common Mistakes When Writing Python Programs + + +Python is a fantastic language for its simplicity and readability, but that doesn't mean it's immune to errors. By avoiding these common mistakes and adopting best practices, you'll become a more proficient Python programmer and create more reliable and maintainable software. + +**Mistake 1: Neglecting Indentation 🧐** + +Python's use of indentation for code blocks is one of its distinctive features. However, it's also a common source of errors. Failing to maintain consistent and correct indentation levels can lead to syntax errors and unexpected program behavior. + +**Tip:** Use a reliable code editor or IDE that automatically handles indentation, and be consistent with your style. + +**Mistake 2: Ignoring Error Handling 🚨** + +Errors and exceptions are a natural part of software development. Neglecting to handle exceptions or using overly broad `try...except` blocks can make it challenging to diagnose and fix issues in your code. + +**Tip:** Always include proper error handling in your code to gracefully handle exceptions and provide meaningful error messages. + +**Mistake 3: Not Using Virtual Environments 🌐** + +Failing to use virtual environments for your Python projects can lead to version conflicts and dependencies issues. Mixing packages from different projects can result in headaches when trying to maintain or distribute your code. + +**Tip:** Create and use virtual environments for each Python project to isolate dependencies and ensure a clean environment. + +**Mistake 4: Poor Documentation πŸ“–** + +Insufficient or outdated documentation can make your code difficult for others (and even yourself) to understand. Neglecting docstrings, inline comments, and clear variable/function names can hinder collaboration and future maintenance. + +**Tip:** Practice good documentation habits by adding docstrings to your functions, documenting your code's purpose, and maintaining up-to-date README files. + +**Mistake 5: Not Testing Code πŸ§ͺ** + +Failure to test your code thoroughly can lead to undiscovered bugs and regressions. Relying solely on manual testing or skipping testing altogether can result in unreliable software. + +**Tip:** Implement automated testing using tools like `unittest`, `pytest`, or `doctest` to ensure your code behaves as expected and remains stable as it evolves. + + +## 4. πŸ›‘οΈ Test Cases: Your Safety Net in Code Development + +Test cases are the safety net that ensures your Python code works as intended. They help you catch bugs early in the development process, provide documentation for your code's behavior, and facilitate collaboration among developers. + +Writing effective test cases is not just a practice; it's an investment in the quality and reliability of your Python software. By following these tips and incorporating testing into your development workflow, you'll catch issues early, save time, and build more robust applications. + + +Writing effective test cases is a skill every Python programmer should master. Let's explore some best practices: + +**Tip 1: Be Clear on What You Want to Test 🎯** + +Before writing a test case, have a clear understanding of the specific functionality or behavior you want to test. Define your test's scope, inputs, and expected outputs. + +```python +def test_addition(): + result = add(3, 5) + assert result == 8 +``` + +**Tip 2: Cover Edge Cases and Boundaries πŸŒ‰** + +Don't just test for typical scenarios. Ensure your test suite includes edge cases, boundary conditions, and scenarios where unexpected inputs might be provided. + +```python +def test_division_by_zero(): + with pytest.raises(ZeroDivisionError): + divide(10, 0) +``` + +**Tip 3: Keep Your Tests Isolated 🧩** + +Tests should be independent of each other. Avoid test cases that rely on the state or results of previous tests. Isolation ensures that each test provides clear and unambiguous results. + +```python +def test_multiply(): + result = multiply(4, 5) + assert result == 20 +``` + +**Tip 4: Use Descriptive Test Names πŸ“** + +Choose descriptive names for your test functions so that failures are easy to understand. A clear test name should indicate the purpose and context of the test. + +```python +def test_user_registration_valid_data(): + # ... +``` + +**Tip 5: Automate Your Tests πŸ€–** + +Automate the execution of your test suite. Tools like `unittest`, `pytest` make running tests and reporting results straightforward. + +```bash +$ pytest test_my_module.py +``` + + +## 5. πŸ”„ How to Check if a Generator is Empty + + +Generators are a valuable tool in Python, but knowing how to manage them effectively is equally important. With these techniques to check if a generator is empty, you can write more robust and efficient code while working with iterators. + +Generators in Python are a versatile way to create iterators without the need to build an entire class. They allow you to generate values on-the-fly, making them particularly useful for dealing with large data sets or when you don't want to store all values in memory. + +Let's explore the methods to check if a generator is empty: + +**Method 1: Iterate and Check 🚢** + +One common approach to check if a generator is empty is to attempt to iterate over it and catch the `StopIteration` exception that occurs when the generator is exhausted. + +```python +def is_generator_empty(generator): + try: + next(generator) + return False # Generator is not empty + except StopIteration: + return True # Generator is empty +``` + +**Method 2: Use `itertools.tee()` 🍐** + +The `itertools` module provides a helpful `tee()` function that can create multiple independent iterators from a single iterable, including generators. By using `tee()` to create a second iterator, you can check if the first one is empty without consuming its values. + +```python +from itertools import tee + +def is_generator_empty(generator): + # Create two independent iterators + gen1, gen2 = tee(generator) + + try: + next(gen2) # Attempt to advance the second iterator + return False # Generator is not empty + except StopIteration: + return True # Generator is empty +``` +**Note**: element will be exausted from generator, so please use it carefully. \ No newline at end of file diff --git a/doc/newsletters/index.2023.rst b/doc/newsletters/index.2023.rst index 7a55fad..61cd707 100644 --- a/doc/newsletters/index.2023.rst +++ b/doc/newsletters/index.2023.rst @@ -3,6 +3,7 @@ .. toctree:: :maxdepth: 4 + September - Week 35 <2023/week_35.md> Augest - Week 34 <2023/week_34.md> Augest - Week 33 <2023/week_33.md> Augest - Week 32 <2023/week_32.md>

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /