<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: AHTESHAM ZAIDI</title>
    <description>The latest articles on DEV Community by AHTESHAM ZAIDI (@ahtesham007).</description>
    <link>https://dev.to/ahtesham007</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F950229%2F2792e3c8-e43c-4b0c-9116-bb1a2dd1ce9f.jpeg</url>
      <title>DEV Community: AHTESHAM ZAIDI</title>
      <link>https://dev.to/ahtesham007</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ahtesham007"/>
    <language>en</language>
    <item>
      <title>Context Managers: Simplify Resource Management in Python</title>
      <dc:creator>AHTESHAM ZAIDI</dc:creator>
      <pubDate>Fri, 21 Apr 2023 13:03:36 +0000</pubDate>
      <link>https://dev.to/ahtesham007/context-managers-simplify-resource-management-in-python-4bao</link>
      <guid>https://dev.to/ahtesham007/context-managers-simplify-resource-management-in-python-4bao</guid>
      <description>&lt;p&gt;Context managers in Python are a powerful tool for managing resources, like files or network connections, that need to be acquired and released in a specific way. In Python, context managers are defined using the "with" statement, which provides a clean and simple syntax for acquiring and releasing resources.&lt;/p&gt;

&lt;p&gt;The with statement is used in conjunction with a context manager object, which defines how the resource should be acquired and released. The context manager object is responsible for defining two methods: &lt;strong&gt;enter&lt;/strong&gt;() and &lt;strong&gt;exit&lt;/strong&gt;(). The &lt;strong&gt;enter&lt;/strong&gt;() method is called when the with statement is executed, and it returns the resource that will be used in the subsequent block of code. The &lt;strong&gt;exit&lt;/strong&gt;() method is called when the block of code is finished, and it is responsible for releasing the resource.&lt;/p&gt;

&lt;p&gt;Context managers provide a number of benefits over manually acquiring and releasing resources. First, they ensure that resources are always released, even in the case of an error or exception. Second, they provide a clean and simple syntax for acquiring and releasing resources, which makes code easier to read and understand.&lt;/p&gt;

&lt;p&gt;Here's an example of using a context manager to work with a file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('example.txt', 'w') as f:
    f.write('Hello, world!')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the open() function returns a file object, which is used to write the string "Hello, world!" to a file named "example.txt". The with statement ensures that the file is automatically closed when the block of code is finished.&lt;/p&gt;

&lt;p&gt;Here's another example of using context managers with a custom class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MyContext:
    def __enter__(self):
        print('Entering context...')
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('Exiting context...')
        if exc_type:
            print(f'Exception: {exc_type}, {exc_value}')

with MyContext():
    print('Inside the context...')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Entering context...
Inside the context...
Exiting context...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have defined a custom class called MyContext that defines its own &lt;strong&gt;enter&lt;/strong&gt; and &lt;strong&gt;exit&lt;/strong&gt; methods. When the with statement is executed, the &lt;strong&gt;enter&lt;/strong&gt; method is called, which prints 'Entering context...' and returns the context manager object. The code inside the with statement is executed, which prints 'Inside the context...'. Once the code completes execution, the &lt;strong&gt;exit&lt;/strong&gt; method is called, which prints 'Exiting context...'.&lt;/p&gt;

&lt;p&gt;Context managers can also be used for managing multiple resources, locking and unlocking threads, and database transactions, among other things.&lt;/p&gt;

&lt;p&gt;Context managers are a powerful tool for managing resources in Python, and they are used extensively throughout the standard library. If you are working with resources that need to be acquired and released in a specific way, you should consider using a context manager to simplify your code and ensure that your resources are always released properly.&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>contextmanagers</category>
      <category>backend</category>
    </item>
    <item>
      <title>Mastering Python Generators: Unleashing the Power of Lazy Evaluation</title>
      <dc:creator>AHTESHAM ZAIDI</dc:creator>
      <pubDate>Mon, 17 Apr 2023 07:10:15 +0000</pubDate>
      <link>https://dev.to/ahtesham007/mastering-python-generators-unleashing-the-power-of-lazy-evaluation-1kb3</link>
      <guid>https://dev.to/ahtesham007/mastering-python-generators-unleashing-the-power-of-lazy-evaluation-1kb3</guid>
      <description>&lt;p&gt;Are you ready to unlock the full potential of Python generators? 🐍 Generators are a powerful feature in Python that allow for lazy evaluation, enabling efficient processing of large datasets, stream processing, and more. In this post, we will dive deep into the world of generators and explore advanced techniques to level up your Python programming skills.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are Generators?
&lt;/h2&gt;

&lt;p&gt;Generators in Python are special functions that produce a sequence of values on-the-fly, one at a time, using the yield statement. Unlike lists or other sequences, generators don't generate all the values at once and store them in memory. Instead, they produce values on-demand, making them efficient for working with large datasets or when you don't need to generate all the values at once.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advanced Techniques with Generators
&lt;/h2&gt;

&lt;p&gt;In this post, we will explore some advanced techniques with Python generators, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creating infinite generators&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This example shows how to create a generator that generates numbers up to a specified maximum value. It uses a while loop with a yield statement inside, allowing the generator to produce values on the fly without generating all the values upfront. The generator continues to yield values until the maximum value is reached.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def count_up_to(max):
    count = 1
    while True:
        yield count
        count += 1
        if count &amp;gt; max:
            break

# Example usage:
counter = count_up_to(5)
for num in counter:
    print(num)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1
2
3
4
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Using send() and throw() methods:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This example demonstrates how to use the send() and throw() methods with generators. The send() method allows communication between the caller and the generator, where the generator can receive a value sent by the caller. The throw() method allows the caller to raise an exception inside the generator, which can be caught and handled within the generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def coroutine_example():
    while True:
        received = yield
        print("Received:", received)

coroutine = coroutine_example()
next(coroutine)
coroutine.send("Hello")
coroutine.send("World")
coroutine.throw(ValueError, "An error occurred")

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Received: Hello
Received: World
ValueError: An error occurred
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Combining multiple generators with yield from:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This example shows how to use the yield from statement to combine the output of multiple generators into a single generator. It allows for more concise and efficient code when combining multiple generators with overlapping functionality. The combined generator yields values from each individual generator sequentially, providing a unified stream of values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def even_numbers():
    yield 0
    yield 2
    yield 4
    yield 6
    yield 8

def odd_numbers():
    yield 1
    yield 3
    yield 5
    yield 7
    yield 9

def all_numbers():
    yield from even_numbers()
    yield from odd_numbers()

# Example usage:
for num in all_numbers():
    print(num)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0
2
4
6
8
1
3
5
7
9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Implementing coroutine-like behavior with asyncio:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This example demonstrates how to use the asyncio library to implement coroutine-like behavior in Python. It uses the async and await keywords to define asynchronous coroutines that can be scheduled and executed concurrently using the asyncio event loop. This allows for asynchronous I/O operations and concurrent execution of tasks, making it suitable for network programming, I/O-bound tasks, and other asynchronous operations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import asyncio

async def coroutine_example():
    while True:
        received = await asyncio.sleep(1)
        print("Received:", received)

async def main():
    task = asyncio.create_task(coroutine_example())
    await asyncio.gather(task)

# Example usage:
asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Received: None
Received: None
Received: None
Received: None
Received: None
....
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why Use Generators?
&lt;/h2&gt;

&lt;p&gt;Generators offer several advantages over other approaches, such as lists or other sequences:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Memory-efficient: Generators produce values on-demand, making them suitable for processing large datasets or streams of data without loading everything into memory at once.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Faster processing: Generators allow for lazy evaluation, enabling faster processing and improved performance in certain use cases.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Code reusability: Generators can be easily reused in different parts of your codebase, making them a versatile tool for writing modular and maintainable code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Simplified logic: Generators allow for more concise and readable code, especially when dealing with complex data processing tasks.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Generators are a powerful feature in Python that can greatly enhance your coding skills and improve the performance of your applications. In this post, we covered some advanced techniques with Python generators, including infinite generators, using send() and throw() methods, combining multiple generators with yield from, and implementing coroutine-like behavior with asyncio. I hope this post has inspired you to explore the full potential of Python generators and incorporate them into your coding toolbox!&lt;/p&gt;

&lt;p&gt;Disclaimer: “Some parts of this article were created with the help of AI”&lt;/p&gt;

</description>
      <category>python</category>
      <category>generators</category>
      <category>programming</category>
      <category>backend</category>
    </item>
    <item>
      <title>Demystifying Decorators in Python: A Powerful Tool for Function Manipulation</title>
      <dc:creator>AHTESHAM ZAIDI</dc:creator>
      <pubDate>Sun, 16 Apr 2023 10:13:54 +0000</pubDate>
      <link>https://dev.to/ahtesham007/demystifying-decorators-in-python-a-powerful-tool-for-function-manipulation-5o1</link>
      <guid>https://dev.to/ahtesham007/demystifying-decorators-in-python-a-powerful-tool-for-function-manipulation-5o1</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Decorators are a powerful feature in Python that allow you to modify the behavior of functions at runtime. They are widely used in Python programming, but can be a bit confusing for newcomers. In this post, we'll dive into the world of decorators, demystifying their concept and exploring how they can be used to manipulate functions in Python.&lt;/p&gt;
&lt;h2&gt;
  
  
  1. Understanding Decorators:
&lt;/h2&gt;

&lt;p&gt;Decorators in Python are functions that can be used to modify the behavior of other functions. They are applied to functions using the "@" symbol followed by the name of the decorator. Let's take a look at a simple example of a decorator that adds logging functionality to a function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def logger(func):
    def wrapper(*args, **kwargs):
        print(f"Logging: Calling {func.__name__} with args {args} and kwargs {kwargs}")
        return func(*args, **kwargs)
    return wrapper

@logger
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Logging: Calling greet with args ('Alice',) and kwargs {}
Hello, Alice!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Decorator Examples:
&lt;/h2&gt;

&lt;p&gt;Decorators can be used for various purposes, such as logging, timing, authentication, and caching. Here's an example of a timing decorator that measures the execution time of a function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import time

def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Timing: function {func.__name__} took {end_time - start_time:.6f} seconds to execute")
        return result
    return wrapper

@timing_decorator
def fib(n):
    if n &amp;lt;= 2:
        return 1

    a,b = 1,1
    for i in range(2,n):
        c = a + b
        a,b = b,c

    return c

print(fib(9))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Timing: function fib took 0.000000 seconds to execute
34
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Creating Your Own Decorators:
&lt;/h2&gt;

&lt;p&gt;You can also create your own decorators in Python. Here's an example of a custom decorator that adds authorization functionality to a function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def authorization_decorator(func):
    def wrapper(*args, **kwargs):
        if is_user_authorized():
            return func(*args, **kwargs)
        else:
            print("Authorization failed. Access denied.")
    return wrapper

@authorization_decorator
def sensitive_operation():
    print("Performing sensitive operation...")

sensitive_operation()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Advanced Decorator Techniques:
&lt;/h2&gt;

&lt;p&gt;There are advanced techniques you can use with decorators, such as using class-based decorators, applying decorators to classes and methods, and chaining multiple decorators together. Here's an example of using a class-based decorator to measure the execution time of methods in a class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import time

class TimingDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        start_time = time.time()
        result = self.func(self, *args, **kwargs)
        end_time = time.time()
        print(f"Timing: {self.func.__name__} took {end_time - start_time:.2f} seconds to execute")
        return result

class MyClass:
    @TimingDecorator
    def my_method(self):
        print("Performing my_method...")

obj = MyClass()
obj.my_method()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Performing my_method...
Timing: my_method took 0.00 seconds to execute
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;br&gt;
Decorators are a powerful tool in Python that allow you to modify the behavior of functions. They can be used for various purposes and can be easily created and applied to functions or methods. By understanding the concept of decorators and their advanced techniques, you can enhance the functionality of your functions and make your code more modular and reusable.&lt;/p&gt;

&lt;p&gt;Have you used decorators in your Python projects? Share your experiences and thoughts in the comments below! If you have any questions or feedback, feel free to ask. Happy coding!&lt;/p&gt;

&lt;p&gt;Disclaimer: “Some parts of this article were created with the help of AI”&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>decorators</category>
      <category>backend</category>
    </item>
  </channel>
</rss>
