<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prabakaran Santhanam on Medium]]></title>
        <description><![CDATA[Stories by Prabakaran Santhanam on Medium]]></description>
        <link>https://medium.com/@praba230890?source=rss-2bf590491572------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p7MScJcmMDIVtgtKRzu4Rg.png</url>
            <title>Stories by Prabakaran Santhanam on Medium</title>
            <link>https://medium.com/@praba230890?source=rss-2bf590491572------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:28:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@praba230890/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Python’s Iterator Protocol: Iterables, Iterators, and Generators]]></title>
            <link>https://medium.com/@praba230890/understanding-pythons-iterator-protocol-iterables-iterators-and-generators-b51ff7a8700c?source=rss-2bf590491572------2</link>
            <guid isPermaLink="false">https://medium.com/p/b51ff7a8700c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Prabakaran Santhanam]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 09:12:23 GMT</pubDate>
            <atom:updated>2025-09-14T06:25:27.665Z</atom:updated>
            <content:encoded><![CDATA[<p>Python’s iterator protocol is a powerful feature that many developers use daily without fully understanding the mechanics behind it. In this article, we’ll dive deep into iterables, iterators, and generators — the building blocks that make Python’s for loops and comprehensions possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iDKs_4zctDQIV_2V-d3Uwg.png" /></figure><h3>Basic Iteration in Python</h3><p>Let’s start with a simple example:</p><pre>a = [1, 2, 3, 4, 5]<br>for i in a:<br>    print(i)</pre><p>This outputs each number on a separate line. But what’s happening behind the scenes? Python’s for loop is actually using the iterator protocol to traverse the list.</p><p>We can also use list comprehensions for more concise operations:</p><pre># Filter even numbers<br>print([x for x in a if x % 2 == 0])  # Output: [2, 4]<br># Filter elements that exist in another list<br>b = [4, 5]<br>print([x for x in a if x in b])  # Output: [4, 5]</pre><h3>Lazy Iteration with Generators</h3><p>While list comprehensions evaluate immediately, generator expressions provide lazy evaluation:</p><pre>data = (i for i in a if i % 2 == 0)<br>print(next(data))  # Output: 2<br>print(next(data))  # Output: 4</pre><p>The generator expression doesn’t compute all values at once — it produces them on demand with each next() call.</p><h3>Creating Custom Iterables</h3><p>Let’s create a custom class that implements the iterator protocol:</p><pre>class Family:<br>    def __init__(self, members):<br>        self.members = members<br>    <br>    def __iter__(self):<br>        for member in self.members:<br>            yield member<br><br>family = Family([<br>    {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 30},<br>    {&#39;name&#39;: &#39;Bob&#39;, &#39;age&#39;: 25},<br>    {&#39;name&#39;: &#39;Charlie&#39;, &#39;age&#39;: 35}<br>])<br>for member in family:<br>    print(member[&#39;name&#39;])</pre><p>The __iter__ method makes our class iterable, and by using yield, we&#39;ve created a generator function.</p><h3>Iterables vs Iterators: What’s the Difference?</h3><p>To understand the difference, let’s look at how we can manually implement the iteration process:</p><pre>try:<br>    _family = iter(family)<br>    while True:<br>        member = next(_family)<br>        print(member[&#39;name&#39;])<br>except StopIteration:<br>    pass</pre><p>This code does the same thing as our for loop above. We call iter() to get an iterator, then call next() repeatedly until a StopIteration exception is raised.</p><p>A key insight: <strong>iterables</strong> have an __iter__ method that returns an <strong>iterator</strong>, and <strong>iterators</strong> have a __next__ method that returns the next value or raises StopIteration.</p><h3>Generators: Special Iterators</h3><p>Generators are a special type of iterator created using functions with the yield keyword:</p><pre>def just_gen():<br>    for i in range(10):<br>        yield i<br><br>for i in just_gen():<br>    print(i)</pre><p>When we call just_gen(), we get a generator object. This object is both an iterable (it has an __iter__ method) and an iterator (it has a __next__ method).</p><h3>The Iterator Protocol Under the Hood</h3><p>Let’s examine how Python’s for loop works by using the dis module to disassemble a function:</p><pre>import dis <br><br>def just_iter():<br>    for i in [1, 23]:<br>        print(i)<br>print(dis.dis(just_iter))</pre><p>The disassembly shows that Python’s for loop is actually syntactic sugar for the iterator protocol we saw earlier—getting an iterator and repeatedly calling next().</p><pre>  2           0 LOAD_CONST               1 ((1, 23))<br>              2 GET_ITER<br>        &gt;&gt;    4 FOR_ITER                 6 (to 18)<br>              6 STORE_FAST               0 (i)<br><br>  3           8 LOAD_GLOBAL              0 (print)<br>             10 LOAD_FAST                0 (i)<br>             12 CALL_FUNCTION            1<br>             14 POP_TOP<br>             16 JUMP_ABSOLUTE            2 (to 4)<br><br>  2     &gt;&gt;   18 LOAD_CONST               0 (None)<br>             20 RETURN_VALUE</pre><h3>StopIteration: The Signal to Stop</h3><p>The StopIteration exception signals the end of iteration. The for loop handles this exception internally, so we normally don&#39;t see it:</p><pre>try:<br>    for i in range(10):<br>        print(i)<br>except StopIteration:<br>    print(&quot;StopIteration caught&quot;)  # This won&#39;t execute</pre><p>But if we raise StopIteration inside a generator, something interesting happens:</p><pre>def just_gen():<br>    yield 1<br>    raise StopIteration()<br><br>try:<br>    for i in just_gen():<br>        print(i)<br>except StopIteration:<br>    print(&quot;StopIteration caught&quot;)  # This will execute</pre><p>In Python 3, raising StopIteration inside a generator is considered an error (see <a href="https://peps.python.org/pep-0479/">PEP 479</a>), but the exception propagates out of the for loop instead of being caught by it.</p><p>If we use the iterator directly, we see the exception:</p><pre>jg = just_gen()<br>print(next(jg))  # Output: 1<br>print(next(jg))  # Raises StopIteration</pre><h3>The Hierarchy of Iteration</h3><p>Here’s a helpful way to think about these concepts:</p><ul><li><strong>Iterable</strong>: An object that implements __iter__ to return an iterator</li><li><strong>Iterator</strong>: An object that implements __next__ to return values and __iter__ to return itself</li><li><strong>Generator</strong>: A special kind of iterator created by generator functions or expressions</li></ul><p>Let’s confirm this by creating a class that implements only __next__:</p><pre>class JustIter:<br>    def __init__(self, data):<br>        self.data = data<br>        self.index = 0<br>    <br>    def __next__(self):<br>        if self.index &gt;= len(self.data):<br>            raise StopIteration()<br>        value = self.data[self.index]<br>        self.index += 1<br>        return value<br>    <br>just_iter = JustIter([1, 2, 3, 4, 5])<br># for i in just_iter:  # This doesn&#39;t work<br>#     print(i)    <br>print(next(just_iter))  # But this works</pre><p>The class above is not fully compliant with the iterator protocol because it lacks an __iter__ method, so it can&#39;t be used in a for loop.</p><p>To make it work, we need to add __iter__ that returns self:</p><pre>class Iterable:<br>    def __init__(self, data):<br>        self.data = data<br>        self.index = 0<br>    <br>    def __iter__(self):<br>        return self<br>    <br>    def __next__(self):<br>        if self.index &lt; len(self.data):<br>            value = self.data[self.index]<br>            self.index += 1<br>            return value<br>        else:<br>            raise StopIteration</pre><h3>Unpacking with Iterators</h3><p>The iterator protocol also enables Python’s powerful unpacking syntax:</p><pre>def unpack_vals(arr):<br>    a, *b, c = arr<br>    print(a, b, c)<br><br>unpack_vals([1, 2, 3, 4, 5])  # Output: 1 [2, 3, 4] 5</pre><p>This works with any iterable:</p><pre>iterable = Iterable([1, 2, 3, 4, 5])<br>a, *b = iterable<br>print(a, b)  # Output: 1 [2, 3, 4, 5]<br>a, *b = &quot;hello&quot;<br>print(a, b)  # Output: h [&#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;]</pre><h3>Practical Applications: Managing Collections</h3><p>Let’s look at a more practical example — a class that manages a collection of people:</p><pre>class Person:<br>    def __init__(self, persons):<br>        self._persons = persons<br>        self.index = 0<br>    def __iter__(self):<br>        return self<br>    def __next__(self):<br>        if self.index &lt; len(self._persons):<br>            person = self._persons[self.index]<br>            self.index += 1<br>            return person<br>        else:<br>            raise StopIteration <br>persons = Person([<br>    {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30},<br>    {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 25},<br>    {&quot;name&quot;: &quot;Charlie&quot;, &quot;age&quot;: 35}<br>])</pre><p>Once our class implements the iterator protocol, we can use it with Python’s built-in functions that work with iterables:</p><pre># Unpacking<br>one, *rest = persons<br>print(one, rest)  # Output: {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 30} [{&#39;name&#39;: &#39;Bob&#39;, &#39;age&#39;: 25}, {&#39;name&#39;: &#39;Charlie&#39;, &#39;age&#39;: 35}]<br><br># Sorting<br>sorted_persons = sorted(persons, key=lambda x: x[&quot;age&quot;])<br>print(sorted_persons)  # Output: [{&#39;name&#39;: &#39;Bob&#39;, &#39;age&#39;: 25}, {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 30}, {&#39;name&#39;: &#39;Charlie&#39;, &#39;age&#39;: 35}]</pre><h3>Conclusion</h3><p>Understanding Python’s iterator protocol unlocks a deeper comprehension of how Python works internally. By mastering iterables, iterators, and generators, you can write more elegant and efficient code.</p><p>The iterator protocol is what enables:</p><ul><li>For loops</li><li>List/dictionary/set comprehensions</li><li>Generator expressions</li><li>Unpacking syntax</li><li>Many built-in functions like sorted(), map(), filter()</li></ul><p>Next time you write a for loop, remember the magic happening behind the scenes!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b51ff7a8700c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Generator Concept That Every Developer Should Know With Some Code Samples]]></title>
            <link>https://medium.com/@praba230890/python-generator-concept-that-every-developer-should-know-with-some-code-samples-6f133d44894f?source=rss-2bf590491572------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f133d44894f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Prabakaran Santhanam]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 21:52:38 GMT</pubDate>
            <atom:updated>2022-11-21T21:54:06.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EZxvjxKJqXJyWAldES7MA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tama66?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Peter Herrmann</a> on <a href="https://unsplash.com/s/photos/generator?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Generators</h3><p>Generators are a way of doing things lazily in Python. As the name suggests, the generators enable us to retrieve/evaluate things (or generate a sequence output) step by step using functions with control over them.</p><p>Let’s say, we have a vast list, and we have to evaluate something for each item in the list but not sure if we are required to evaluate the entire list in one go. In this scenario, we can use generators to lazily calculate each result item when required and don’t have to store the whole result in memory.</p><h3>Problems that Generators Solve:</h3><ul><li>persisting the state of a function and controlling the function execution over a period of time/application execution instead of executing the entire function block in a go and destroying the function block scope after exiting the function.</li><li>generate and/or process/work on an indefinite output and/or input respectively</li><li>turn a recursion implementation into a more controllable &amp; easy to read code</li></ul><h3>Looking into a generator execution:</h3><pre>&gt;&gt;&gt; def gen():<br>...     lv = 5<br>...     for i in range(3):<br>...         print(locals())<br>...         lv = lv+1<br>...         yield i<br>&gt;&gt;&gt; g = gen()<br>&gt;&gt;&gt; next(g)<br>{&#39;lv&#39;: 5, &#39;i&#39;: 0} <br>0<br>&gt;&gt;&gt; next(g)<br>{&#39;lv&#39;: 6, &#39;i&#39;: 1} <br>1<br>&gt;&gt;&gt; next(g)<br>{&#39;lv&#39;: 7, &#39;i&#39;: 2} <br>2</pre><p>In the above code, we can see a function with a for loop, which just iterates through a list with 3 elements (range(3)=[0,1,2]) and simply increment the local variable lv in the function. If we remove the yield statement, it’ll be a normal python function.</p><p>With yield, now the function will act as a generator function. The generator function when called will return a generator object which we can use to execute the function in a controlled fashion.</p><p>In the above case (gen function), whenever we call the next with the generator object, g as the argument, Python will execute the gen function until it bumps into a yield statement, and whatever the yield statement returns will be returned as the next function call return.</p><p>Let’s breakdown the code,</p><pre>&gt;&gt;&gt; def gen():<br>...     lv = 5<br>...     for i in range(3):<br>...         print(locals())<br>...         lv = lv+1<br>...         yield i<br>&gt;&gt;&gt; g = gen()<br>&gt;&gt;&gt; print(g.gi_frame.f_locals) # will print the generator function local state/variables<br>{}</pre><p>What we did so far is just create a generator object g by calling the gen function and looking into the local variables/state of the function and it’s empty for now. It means the function execution is not started yet and so far, Python only set up the generator object for us to execute the function at our will.</p><p>Okay, let’s execute the function by calling next with g as the argument.</p><pre>&gt;&gt;&gt; next(g)<br>{&#39;lv&#39;: 5, &#39;i&#39;: 0}<br>0<br>&gt;&gt;&gt; g.gi_frame.f_locals<br>{&#39;lv&#39;: 6, &#39;i&#39;: 0}</pre><p>As you could see after calling the next, Python ran our function gen but when bumped into the yield statement, it just paused the function execution and returned the value that is yielded by the yield statement.</p><p>For our understanding, we’ve printed the local variable lv inside the function before mutating it, and then once the function execution is paused, we printed the current state of the function using the gi_frame. Now, we got our yield value but still, the function scope is not destroyed and we can still continue resuming the function execution until the final yield statement in the flow of that function is reached using the next function.</p><p>In our case, 2 morenext calls will exhaust the yields and one more call to next will throw an explicit StopIteration which we have to handle.</p><pre>&gt;&gt;&gt; next(g)<br>{&#39;lv&#39;: 6, &#39;i&#39;: 1}<br>1<br>&gt;&gt;&gt; next(g)<br>{&#39;lv&#39;: 7, &#39;i&#39;: 2}<br>2<br>&gt;&gt;&gt; next(g)<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>StopIteration</pre><p>When used in for loops, StopIteration will be handled implicitly. The above same code when used in for loop.</p><pre>&gt;&gt;&gt; g = gen()<br>&gt;&gt;&gt; for i in g:<br>...     print(i)<br>... <br>{&#39;lv&#39;: 5, &#39;i&#39;: 0}<br>0<br>{&#39;lv&#39;: 6, &#39;i&#39;: 1}<br>1<br>{&#39;lv&#39;: 7, &#39;i&#39;: 2}<br>2</pre><p>I consider yield as one of the control flow helpers in Python similar to break, pass &amp; return. But yield is a more powerful way to control a function execution by adequately structuring your function code with yield and with the generator object created, we can do the,</p><ul><li><strong>Execute</strong></li><li><strong>Pause</strong></li><li><strong>Resume</strong></li><li><strong>Send inputs</strong> to the function</li><li><strong>Terminate</strong> the function</li></ul><p>It’s almost like a 360-degree control of a function via the generator object and yield as an interface.</p><h3>Creating Generators</h3><p>Python allows 3 ways of creating generator objects,</p><ol><li>using the yield statement inside the functions as we’ve seen earlier called <strong>generator functions</strong></li></ol><pre>def gen():<br>    print(&quot;before yield&quot;)<br>    yield<br>    print(&quot;after yield&quot;)<br>ex = gen()<br>print(type(ex))<br>&gt;&gt; &lt;class &#39;generator&#39;&gt;</pre><p>2. using for loop inside the parentheses with an optional if-condition called <strong>generator expressions</strong></p><pre>numbers = (i for i in range(10))<br>numbers = (i for i in range(10) if i%2==0)<br>print(type(numbers))<br>&gt;&gt; &lt;class &#39;generator&#39;&gt;</pre><p>3. Class-based generators</p><pre>class Fib:<br>    def __init__(self):<br>        self.a, self.b = 0, 1<br>    def __iter__(self):<br>        while True:<br>            yield self.a<br>            self.a, self.b = self.b, self.a+self.b<br><br>f = iter(Fib())<br><br>------------ output ----------------<br>&gt;&gt;&gt; f = iter(Fib())<br>&gt;&gt;&gt; next(f)<br>0<br>&gt;&gt;&gt; next(f)<br>1<br>&gt;&gt;&gt; next(f)<br>1<br>&gt;&gt;&gt; next(f)<br>2<br>&gt;&gt;&gt; next(f)<br>3</pre><p>Let’s look at some generator code samples.</p><p><strong>A simple generator that does nothing</strong></p><pre># Simple generator that does nothing<br>def random_fn():<br>    yield<br><br>random_generator = random_fn()<br>print(dir(random_generator))<br><br>for random_number in random_generator:<br>    print(random_number, &quot; inside for&quot;)<br><br>----------- output --------------<br>None  inside for</pre><p><strong>Adding logic to the above generator that gives us a random number on each iteration</strong></p><pre># add logic to the above generator that gives us a random number on each iteration<br>import random<br><br>def random_fn(start, end, maximum):<br>    for i in range(maximum):<br>        yield random.randint(start, end)<br><br>random_generator = random_fn(5, 100, 10)<br><br>for random_number in random_generator:<br>    print(random_number, &quot; inside for&quot;)<br><br><br>----------- output ----------------<br>13  inside for<br>85  inside for<br>93  inside for<br>39  inside for<br>8  inside for<br>54  inside for<br>95  inside for<br>57  inside for<br>86  inside for<br>38  inside for</pre><p>We can have <strong>multiple </strong><strong>yield statements</strong> in a generator function through which we can achieve more precise control over the functions.</p><pre># having multiple yield in generators<br>def mul_yield():<br>    yield 1<br>    yield 2<br><br>mul_yield_gen = mul_yield()<br>print(next(mul_yield_gen), &quot; outside for - having multiple yield in generators&quot;)<br>print(next(mul_yield_gen), &quot; outside for - having multiple yield in generators&quot;)<br><br># print(next(mul_yield_gen)) # when uncommented will throw StopIteration exception as all the yields are completed<br>#   OR<br><br>mul_yield_gen = mul_yield()<br><br>for num in mul_yield_gen:<br>    print(num, &quot; inside for - having multiple yield in generators&quot;)<br><br><br>----------- output ----------------<br>1  outside for - having multiple yield in generators<br>2  outside for - having multiple yield in generators<br>1  inside for - having multiple yield in generators<br>2  inside for - having multiple yield in generators</pre><p><strong>Sending data to generators (coroutine?)</strong></p><pre># sending data to generators (coroutine?)<br>def mul_yield():<br>    inp = yield <br>    yield inp ** 2<br>mul_yield_gen = mul_yield()<br>next(mul_yield_gen)          # next() is equal to send(None)<br>print(mul_yield_gen.send(9)) # send sends the value to the generator, giving it the execution control <br>                             # &amp; waits for the response<br><br>----------- output ----------------<br>81</pre><p><strong>Generator Expressions</strong></p><pre># Generator expressions<br>a = (i for i in range(10))<br>print(a)<br>print(next(a))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f133d44894f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need to Know About Python Iterators — A Definitive Guide]]></title>
            <link>https://medium.com/@praba230890/everything-you-need-to-know-about-python-iterators-a-definitive-guide-493dcb0c6d88?source=rss-2bf590491572------2</link>
            <guid isPermaLink="false">https://medium.com/p/493dcb0c6d88</guid>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Prabakaran Santhanam]]></dc:creator>
            <pubDate>Thu, 13 Oct 2022 14:53:42 GMT</pubDate>
            <atom:updated>2022-10-13T14:54:38.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Everything You Need to Know About Python Iterators — A Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsR4PomzkCGy56lJSK4YEQ.jpeg" /><figcaption><a href="https://www.freepik.com/free-photo/breathtaking-view-wave-concept-surfing_11819376.htm#page=2&amp;query=sea%20surf&amp;position=15&amp;from_view=search&amp;track=sph">Image by wirestock on Freepik</a></figcaption></figure><p>Iterators are the core of how for loop works in Python. If we want to loop through the container objects like list, tuple, dictionary, set, strings, files and so, they have to be <strong>iterable</strong>.</p><p>We know that everything in Python is an object. So when we create a list, tuple, or any container type, they’ll be objects as well and every container type object in Python is an <strong>iterable</strong> object.</p><p>Basically, there are two essential things when it comes to for loop or iterating through objects: <strong>iterable</strong> &amp; <strong>iterator</strong>. Let&#39;s see the definition of them both from the official Python docs,</p><blockquote>An <strong>iterable</strong> object is an object that implements __iter__, which is expected to return an <strong>iterator</strong> object.</blockquote><blockquote>An <strong>iterator</strong> object implements __next__, which is expected to return the next element of the iterable object that returned it and to raise a StopIteration exception when no more elements are available.</blockquote><p>From the above explanations, we could be certain that every container data type in Python has an __iter__ implementation that returns an <strong>iterator</strong> object. The returned <strong>iterator</strong> will be having __next__ method using which we could get each element from the container or an <strong>iterable</strong>.</p><p>Let’s take a for loop and walk through how it works.</p><pre>lst = [1,2,3,4]<br>for i in lst:<br>    print(i)</pre><pre>dt = {1:&quot;one&quot;, 2:&quot;two&quot;}<br>for d in dt:<br>    print(dt)</pre><pre># for files <br>with open(&quot;somefile&quot;, &#39;r&#39;) as some_file:<br>    for line in some_file:<br>        print(line)</pre><pre># it goes on for all container types including tuple, set, strings</pre><p>In the above code, when the for loop initializes, it’ll call the __iter__ method of the list lst. The __iter__ method will in turn return an <strong>iterator</strong> object. The for loop will use that <strong>iterator</strong> object and call __next__ on the respective iterator.</p><p>The __next__ method will return each element from the container on each iteration. Once we iterated over all the elements and no elements are left, a StopIteration exception will be raised indicating the end of the <strong>iteration</strong>. Below is an approximate code equivalent to what I’ve described above.</p><pre>lst = [1, 2, 3, 4]<br>print(dir(lst))<br># [..., &#39;**__getitem__**&#39;, &#39;**__iter__**&#39;, &#39;append&#39;, &#39;extend&#39;, ...]</pre><pre>iterator = lst.__iter__()</pre><pre>print(dir(iterator))<br>#[..., &#39;__iter__&#39;, &#39;**__next__**&#39;, ...]</pre><pre>while True:<br>    try:<br>        print(iterator.__next__())<br>    except StopIteration:<br>	    break</pre><p>It’s the same for all the container objects like tuple, dictionary, set, strings, files and so.</p><h3>Creating custom iterator:</h3><p>We can make any Python object <strong>iterable</strong> by implementing an __iter__ method. Let&#39;s create a hypothetical Bag class that has items in them. If we want to iterate through the items just by giving the bag object to the for, we have to implement an __iter__ method that returns an <strong>iterable</strong>.</p><p>Then the for loop will basically iterate through the iterator returned by the __iter__ method.</p><pre>class Bag:<br>    def __init__(self, items=[]):<br>        self.items = items</pre><pre>    def __iter__(self):<br>        return iter(self.items)</pre><pre>bag = Bag(items=[&quot;pen&quot;, &quot;money&quot;])</pre><pre>for item in bag:<br>    print(item)</pre><p>Below is another example of creating a custom iterator. Code is a class that has raw code statements in it and we can loop through the statements of the code object directly in for loop as we have __iter__ implementation in the class.</p><pre>class Code:<br>    def __init__(self, code_block, lang, raw, line_separator=&#39;\\n&#39;):<br>        self.statements = [stmt.strip() for stmt in code_block.split(line_separator) <br>                                if stmt.strip()]<br>        self.lang = lang<br>        self.raw = raw</pre><pre>    def __iter__(self):<br>        return iter(self.statements)</pre><pre>code = Code(&quot;&quot;&quot;<br>                a = 5<br>                b = 10<br>                print(f&quot;Sum of {a} &amp; {b} is : {a+b}&quot;)<br>                &quot;&quot;&quot;, &quot;Python&quot;, True)</pre><pre>for statement in code:<br>    if code.lang == &quot;Python&quot;:<br>        eval(compile(statement, &quot;&lt;string&gt;&quot;, &quot;single&quot;))<br>    else:<br>        raise NotImplementedError</pre><p>In the above examples, we directly used the built-in method iter to create an <strong>iterator</strong> object and the iter works only for built-in types. When we have to create an <strong>iterator</strong> for a user-defined object, we have to implement __next__ method which will provide each element for iteration (both for loop and using next).</p><p>Below is an even number generator example that implements both __iter__ and __next__.</p><pre>class EvenNoGenerator:<br>    def __init__(self, limit=0):<br>        self.limit = limit<br>        self.cur = 0</pre><pre>    def __iter__(self):<br>        return self</pre><pre>    def __next__(self):<br>        self.cur = self.cur + 2<br>        if self.limit &gt; 0 and self.cur &gt; self.limit:<br>            raise StopIteration<br>        return self.cur</pre><pre>for i in EvenNoGenerator(15):<br>    print(i)</pre><h3>Oops, there is __getitem__ as well</h3><p>To be honest, I wasn’t honest with everyone about how the built-in containers are <strong>iterable,</strong> to keep things simple for understanding. It’s also possible that the container objects might be using another special method __getitem__ to iterate over the elements.</p><p>According to <a href="https://peps.python.org/pep-0234/">pep — 0324</a>,</p><blockquote><em>The two (</em><em>__iter__ &amp; </em><em>next) methods correspond to two distinct protocols:</em></blockquote><blockquote>1. An object can be iterated over with for if it implements __iter__() or __getitem__().</blockquote><blockquote>2. An object can function as an iterator if it implements next().</blockquote><blockquote><em>Container-like objects usually support protocol 1. Iterators are currently required to support both protocols. The semantics of iteration come only from protocol 2; protocol 1 is present to make iterators behave like sequences; in particular, so that code receiving an iterator can use a for-loop over the iterator.</em></blockquote><p>We can also use the __getitem__ in our custom objects instead of __iter__ and __next__ if our use case is to simply iterate over a container/sequence objects.</p><p>The Bag class example that we saw earlier can be rewritten as,</p><pre>class Bag:<br>    def __init__(self, items=[]):<br>        self.items = items</pre><pre>    def __getitem__(self, index):<br>        return self.items[index]</pre><pre>bag = Bag(items=[&quot;pen&quot;, &quot;money&quot;])</pre><pre>for item in bag:<br>    print(item)</pre><h3>StopIteration &amp; other Exceptions</h3><p>Python relies on StopIteration exception to determine the end of an iteration. So, if you are writing a custom iterator, then if you raise a StopIteration exception in your __next__ method</p><pre>class Bag:<br>    def __init__(self, items=[]):<br>        self.items = items<br>        self.cur = 0</pre><pre>    def __iter__(self):<br>        return self</pre><pre>    def __next__(self):<br>        self.cur = self.cur + 1<br>        if self.cur &lt;= len(self.items):<br>            return self.items[self.cur-1]<br>        else:<br>            raise StopIteration</pre><pre>bag = Bag(items=[&quot;pen&quot;, &quot;money&quot;])</pre><pre>for item in bag:<br>    print(item)</pre><p>In the above example, after we iterated through every element we are raising a StopIteration exception to let for loop know that there are no more elements to iterate.</p><p>We have to be careful about where we raise the StopIteration. If we raise it prematurely, then our iteration ends there itself and introduces bugs in out code. Let me modify the above code to raise StopIteration in if instead of else,</p><pre>class Bag:<br>    def __init__(self, items=[]):<br>        self.items = items<br>        self.cur = 0</pre><pre>    def __iter__(self):<br>        return self</pre><pre>    def __next__(self):<br>        self.cur = self.cur + 1<br>        if self.cur &lt;= len(self.items):<br>            print(&quot;Not interested in iteration!&quot;)<br>            raise StopIteration<br>        else:<br>            return self.items[self.cur-1]</pre><pre>bag = Bag(items=[&quot;pen&quot;, &quot;money&quot;])</pre><pre>for item in bag:<br>    print(item)</pre><p>Then the output will be just,</p><pre>Not interested in iteration!</pre><p>Also, this StopIteration should be handled when we do the iteration manually instead of for loop. Let’s say, we have a FileReader class that has both __iter__ and __next__.</p><pre>class FileReader:<br>    def __init__(self, file, mode):<br>        self.file = open(file, mode)<br>        self.mode = mode</pre><pre>    def __iter__(self):<br>        return self</pre><pre>    def __next__(self):<br>        return next(self.file)</pre><pre>    def close(self):<br>        self.file.close()</pre><p>We can create an object from the class and loop through each line of the file using for.</p><pre>for line in FileReader(&#39;testfile&#39;, &#39;r&#39;):<br>    print(line)</pre><p>But, if we have a use case, where we have to read each line arbitrarily at different places in the code instead of for, we can use next to get the lines.</p><pre>reader = FileReader(&#39;testfile&#39;, &#39;r&#39;)<br>line = next(reader)<br>print(line)<br># do something with the line</pre><pre>line = next(reader)<br>print(line)</pre><p>In such scenarios, once the file reader runs out of lines in the file, it will throw a StopIterationexception. we don’t have the for loop or any other implicit mechanism to catch the StopIteration and it’ll break the application.</p><pre>Traceback (most recent call last):<br>  File &quot;/module.py&quot;, line 21, in &lt;module&gt;<br>    line = next(reader)<br>           ^^^^^^^^^^^^<br>  File &quot;/module.py&quot;, line 10, in __next__<br>    return next(self.file)<br>           ^^^^^^^^^^^^^^^<br>StopIteration</pre><p>So, we have to make sure to handle the StopIteration explicitly when using next method on iterators. Mostly we would be silently passing the StopIteration exceptions and while doing so, we need to ensure that the exceptions other than StopIteration are propagated properly or as intended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=493dcb0c6d88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Python Context Managers]]></title>
            <link>https://medium.com/@praba230890/a-guide-to-python-context-managers-aa7db1d28e87?source=rss-2bf590491572------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa7db1d28e87</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Prabakaran Santhanam]]></dc:creator>
            <pubDate>Sun, 02 Oct 2022 12:31:30 GMT</pubDate>
            <atom:updated>2022-10-04T10:10:15.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Context Managers are a way to help the developers reduce the burden of writing repetitive code that is critical or if forgotten could cause unexpected exceptions, memory leaks, and overloading of external resources.</p><p>For example, every time someone opens a file, it is expected to be closed explicitly to ensure the data written to the file is flushed correctly and the same is saved. Below is the example of proper file opening and closing, that is expected from the developers.</p><pre>test_file = open(&quot;test_file.txt&quot;, mode=&quot;w&quot;)<br>test_file.write(&quot;This is a test file!&quot;)<br>test_file.close()</pre><p>If the close is not explicitly called,</p><ul><li>There is a possibility of data loss in case of an application crash, although Python (CPython) will try to clean up the files which are not in use by properly closing them (garbage collection)</li><li>There is a limit to the number of files that a process(application) can keep open by the Operating Systems — if crossed that limit, the application cannot open new files</li><li>Data may not be saved into the file until the close is called, which will provide incomplete data to the users who try to get the latest content from the file</li><li>Users may not be able to delete the unclosed file on some systems</li></ul><p>In the above example, it’s normal that the developers might miss calling the close method when writing a big application and it is also repetitive to keep writing the close every time a file is opened.</p><p>In the case of file handling, it’s straightforward. There could be some complicated cases like when using threads, developers might need to acquire locks before doing some operation, then release the lock and might need to do additional cleanups. There are many such scenarios that force developers to write a custom prep/cleanup function that needs to be called before/after doing something.</p><pre>import threading</pre><pre>lock = threading.Lock()<br>lock.acquire()<br>try:<br>    # do something<br>except Exception:<br>    # handle exception<br>finally:<br>    # do some resource cleanup<br>    lock.release()</pre><pre>try:<br>    # do something<br>finally:<br>    update_the_external_resource()<br>    close_or_clean_up_external_resources()</pre><p>Python introduced the context managers via with statements to ease things up and make the code more consistent. The file handling example that we’ve seen above can be rewritten with the context managers, which will handle the file closing/cleanup for us.</p><pre>with open(&quot;test_file.txt&quot;, mode=&quot;w&quot;) as test_file:<br>    test_file.write(&quot;This is a test file!&quot;)</pre><h3>How does this work?</h3><p>Whenever we use the with, the method that we use along the with should be having the magic methods __enter__ and __exit__. The open that we’ve used has __enter__ and __exit__ already written in the standard library.</p><p>So, when we use the open with with statement, it executes the __enter__ method, and whatever the enter method returns will be assigned to the test_file (which is called target). Then once the code within with the block is executed, the __exit__ method will be invoked which will close the file correctly.</p><p>Below is the equivalent of how Python will execute the above with block.</p><pre>file_manager = open(&quot;test_file.txt&quot;, mode=&quot;w&quot;)<br>file_enter = type(file_manager).__enter__<br>file_exit = type(file_manager).__exit__</pre><pre>try:<br>    test_file = file_enter(file_manager)<br>    test_file.write(&quot;This is a test file!&quot;)<br>except:<br>    # handle exception<br>finally:<br>    file_exit(file_manager)</pre><h3>Wring your own custom context managers</h3><h3>Class based</h3><p>Let’s say we want to write a worker that pulls something from a queue and does some work. Before doing the work, the worker needs to pull the task from the queue and then let the queue know that it’s working on the task. Once completed, should send a message to the queue saying the task is completed or an error message saying the task failed and why.</p><pre>class Worker:<br>    # init code __init__</pre><pre>    def __enter__(self):<br>        task = get_task_from_queue()<br>        self.task = task<br>        return self<br>    def __exit__(self, exception, value, traceback):<br>        self.send_completed_message()</pre><pre>with Worker() as worker:<br>    worker.do_task()</pre><h3>Function-based</h3><p>The same worker context manager can be implemented as a function using contextmanager decorator from contextlib. We can write a generator function that when decorated with the contextmanager decorator will become a context manager.</p><pre>from contextlib import contextmanager</pre><pre>@contextmanager<br>def get_worker():<br>    worker = Worker()<br>    worker.task = get_task_from_queue()<br>    try:<br>        yield worker<br>    finally:<br>        worker.send_completed_message()</pre><pre>with get_worker() as worker:<br>    worker.do_task()</pre><p>In function-based context managers, the code block until yield acts as the __enter__ and whatever comes after the yield statement can be considered as __exit__ method.</p><p>The above contextmanager decorator actually builds a wrapper for us with the special (magic) methods __enter__ and __exit__ on the object that it returns, which will be assigned to the target.</p><p>Below are the Python implementations of contextmanager (ignore it if it’s too complicated).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*ghf_R1QCt5BBh9mejbSH3A.png" /><figcaption>contextmanager decorator implementation in Python</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*siSMmDZEi0eFo-5CE007nw.png" /><figcaption>_DecoratorContextManager Class, the object of which will be returned from contextmanager decorator</figcaption></figure><h3>Async Context Managers</h3><p>We can also write async context managers in Python, both function and class based.</p><pre>from contextlib import asynccontextmanager</pre><pre>@asynccontextmanager<br>async def get_worker():<br>    worker = Worker()<br>    worker.task = await get_task_from_queue()<br>    try:<br>        yield worker<br>    finally:<br>        await worker.send_completed_message()</pre><pre>async def work_on_tasks():<br>    async with get_worker() as worker:<br>        return worker.do_task()</pre><pre>class AsyncWorker:<br>    # init code __init__</pre><pre>    async def __aenter__(self):<br>        task = await get_task_from_queue()<br>        self.task = task<br>        return self<br>    async def __aexit__(self, exc_type, exc, tb):<br>        await self.send_completed_message()</pre><pre>async def work_on_tasks():<br>    async with AsyncWorker() as worker:<br>        return worker.do_task()</pre><h3>Context Managers as Decorators</h3><p>We can use context managers (async as well) as decorators using ContextDecorator &amp; AsyncContextDecorator.</p><pre>from contextlib import ContextDecorator</pre><pre>class TestCm(ContextDecorator):<br>    a = 12<br>    def __enter__(self):<br>        print(&quot;enter&quot;)<br>        return self<br>    def __exit__(self, exc_type, exception, traceback):<br>        print(&quot;exit&quot;)<br>        TestCm.a = 12</pre><pre>@TestCm()<br>def play_testcm():<br>    TestCm.a = 8<br>    print(&quot;play_testcm, &quot;, TestCm.a)</pre><pre>play_testcm()</pre><pre>from asyncio import run<br>from contextlib import AsyncContextDecorator</pre><pre>class AsncTestCm(AsyncContextDecorator):<br>    a = 12<br>    async def __aenter__(self):<br>        print(&#39;async enter&#39;)<br>        return self</pre><pre>    async def __aexit__(self, *exc):<br>        print(&#39;async exit&#39;)<br>        AsncTestCm.a = 12</pre><pre>@AsncTestCm()<br>async def async_play_testcm():<br>     print(&#39;Inside async_play_testcm&#39;)</pre><pre>run(async_play_testcm())</pre><h3>How is regular context manager different from Decorators</h3><p>We can see some kind of similarity between decorator and context manager in Python. Both of them let us do something before and after executing a piece of code.</p><p>The only difference is that the decorators are for block-level codes like functions or classes, whereas the context managers are for anonymous blocks of code that can be used anywhere.</p><h3><strong>Examples from Open-Source Projects</strong></h3><h4>Class based context manager usage in Django (<a href="https://github.com/django/django/blob/main/django/db/utils.py">source</a>)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba91f18c21fb1f6f5707ee769514a26/href">https://medium.com/media/6ba91f18c21fb1f6f5707ee769514a26/href</a></iframe><h4>Class based Async context manager in aiohttp library (<a href="https://github.com/aio-libs/aiohttp/blob/master/aiohttp/client.py">source</a>)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f737718b600b131c86ecad66cfcd8b8c/href">https://medium.com/media/f737718b600b131c86ecad66cfcd8b8c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa7db1d28e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>