<?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 Shahriar Tajbakhsh on Medium]]></title>
        <description><![CDATA[Stories by Shahriar Tajbakhsh on Medium]]></description>
        <link>https://medium.com/@s16h?source=rss-7f95b3128eaf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VTqN8FQPYTxWRDXsy3GVPQ.png</url>
            <title>Stories by Shahriar Tajbakhsh on Medium</title>
            <link>https://medium.com/@s16h?source=rss-7f95b3128eaf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:18:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@s16h/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[Underscores in Python]]></title>
            <link>https://medium.com/swlh/underscores-in-python-c67abf7a67d1?source=rss-7f95b3128eaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c67abf7a67d1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shahriar Tajbakhsh]]></dc:creator>
            <pubDate>Wed, 21 Oct 2020 12:49:43 GMT</pubDate>
            <atom:updated>2020-10-28T16:15:49.250Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we’ll go through the different uses of the _ character in Python. Like with many things in Python, we’ll see that different usages of _ are mostly (not always!) a matter of convention. Here are the five different cases we’ll cover:</p><ol><li>Single lone underscore (e.g. _)</li><li>Single underscore before a name (e.g. _total)</li><li>Single underscore after a name (e.g. total_)</li><li>Single underscore in numeric literals (e.g. 100_000)</li><li>Double underscore before a name (e.g. __total)</li><li>Double underscore before and after a name (e.g. __init__)</li></ol><h3>1. Single lone underscore (_)</h3><p>This is typically used in 3 cases:</p><h4><strong>In the interpreter</strong></h4><p>The _ name points to the result of the last executed statement in an interactive interpreter session. This was first done by the standard CPython interpreter, but others have followed as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb66b28ccce373adf692f9aa86001271/href">https://medium.com/media/fb66b28ccce373adf692f9aa86001271/href</a></iframe><h4><strong>As a name</strong></h4><p>This is somewhat related to the previous point. _ is used as a <em>throw-away</em> name. This will allow the next person reading your code to know that, by convention, a certain name is assigned but not intended to be used. For instance, you may not be interested in the actual value of a loop counter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/848f568d5fad8b0d411271f473801686/href">https://medium.com/media/848f568d5fad8b0d411271f473801686/href</a></iframe><h4><strong>i18n</strong></h4><p>You may also see _ being used as a function. In that case, it is often the name used for the function that does internationalisation and localisation string translation lookups. This <em>seems</em> to have originated from and follow the corresponding C convention. For instance, as seen in the <a href="https://docs.djangoproject.com/en/dev/topics/i18n/translation/">Django documentation for translation</a>, you may have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fdadadb1adedfa4a6ae60a335dd72c0/href">https://medium.com/media/1fdadadb1adedfa4a6ae60a335dd72c0/href</a></iframe><p>The second and third purposes can conflict, so you should avoid using _ as a throw-away name in any code block that also uses it for i18n lookup and translation.</p><h3>2. Single underscore before a name (e.g. _total)</h3><p>A single underscore before a name is used to specify that the name is to be treated as “private” by a programmer. It’s <em>kind of</em>* a convention so that the next person (likely yourself) reading your code knows that a name starting with _ is for internal use. As the <a href="https://docs.python.org/3/tutorial/classes.html#private-variables">Python documentation notes</a>:</p><blockquote>a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.</blockquote><p>*I say <em>kind of</em> a convention because it actually does mean something to the interpreter; if you from &lt;module/package&gt; import *, none of the names that start with an _ will be imported unless the module’s/package’s __all__ list explicitly contains them. See ‘<a href="https://medium.com/@s16h/importing-star-in-python-88fe9e8bd4d2">Importing </a><a href="https://medium.com/@s16h/importing-star-in-python-88fe9e8bd4d2">* in Python</a>’ for more on this.</p><h3>3. Single underscore after a name (e.g. total_)</h3><p>A single underscore after a name is used to avoid a name from shadowing another name. It’s certainly a convention. For example, if you want to name something format, in order to avoid shadowing the <a href="https://docs.python.org/3/library/functions.html#format">Python’s builtin </a><a href="https://docs.python.org/3/library/functions.html#format">format</a>, you’d instead call it format_.</p><p>On a funny note, my preferred Twitter username is @s16h, but that was already taken, so, my Twitter username is actually <a href="https://twitter.com/s16h_">@s16h_</a> 🤣 follow me while you’re here!</p><h3>4. Single underscore in numeric literals (e.g. 100_000)</h3><p><a href="https://www.python.org/dev/peps/pep-0515/">PEP 515</a> proposed extending Python’s syntax so that underscores can be used as visual separators for digit grouping purposes in integral, floating-point and complex number literals. The rationale being:</p><blockquote>This is a common feature of other modern languages, and can aid readability of long literals, or literals whose value should clearly separate into parts, such as bytes or words in hexadecimal notation.</blockquote><p>So, you can do stuff like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156611cb85c278fa1d9df73d5942b282/href">https://medium.com/media/156611cb85c278fa1d9df73d5942b282/href</a></iframe><h3>5. Double underscore before a name (e.g. __total)</h3><p>The use of double underscore (__) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python <a href="http://en.wikipedia.org/wiki/Name_mangling">mangles</a> these names and it is used to avoid name clashes with names defined by subclasses. As the <a href="https://docs.python.org/3/tutorial/classes.html#tut-private">Python documentation notes</a>, any identifier of the form __spam (at least two leading underscores, and <strong>at most one trailing underscore</strong>) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.</p><p>Take the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ff6fa62f17e8d8ae38752a8b846d880/href">https://medium.com/media/8ff6fa62f17e8d8ae38752a8b846d880/href</a></iframe><p>As expected, _internal_use doesn’t change, but __method_name is mangled to _ClassName__method_name. Now, if you create a subclass of A, say B (argh, bad, bad names!) then you can’t easily override A‘s __method_name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2037941a8a851721225f12a5750b625c/href">https://medium.com/media/2037941a8a851721225f12a5750b625c/href</a></iframe><p>The intended behaviour here is almost equivalent to final methods in Java and normal (non-virtual) methods in C++.</p><h3>6. Double underscore before and after a name (e.g. __init__)</h3><p>These are <a href="https://docs.python.org/3/reference/datamodel.html#specialnames">special method names</a> used by Python. As far as you’re concerned, this is just a convention, a way for the Python system to use names that won’t conflict with user-defined names. You then typically override these methods and define the desired behaviour for when Python calls them. For example, you often override the __init__ method when writing a class.</p><p>There is nothing to stop you from writing your own special-method-looking name (but, please don’t):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/538da35a7ae1e4d0bac51bdb1e9ef1c4/href">https://medium.com/media/538da35a7ae1e4d0bac51bdb1e9ef1c4/href</a></iframe><p>It’s best to stay away from this type of naming and let only Python-defined special names follow this convention.</p><p>That’s all! If you enjoyed reading this, <a href="https://twitter.com/s16h_">follow me on Twitter</a>. Otherwise, <a href="https://twitter.com/s16h_">follow me on Twitter</a>, and tell me how much you hated reading this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c67abf7a67d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/underscores-in-python-c67abf7a67d1">Underscores in Python</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s `NotImplemented` Type]]></title>
            <link>https://s16h.medium.com/pythons-notimplemented-type-2d720137bf41?source=rss-7f95b3128eaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d720137bf41</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shahriar Tajbakhsh]]></dc:creator>
            <pubDate>Fri, 18 May 2018 14:40:28 GMT</pubDate>
            <atom:updated>2020-04-28T11:48:52.680Z</atom:updated>
            <content:encoded><![CDATA[<p>This post discusses Python’s <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> built-in constant/type; what it is, what it means and when it should be used.</p><h4>What is it?</h4><pre>&gt;&gt;&gt; type(NotImplemented)<br>&lt;type &#39;NotImplementedType&#39;&gt;</pre><p><a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> is one of Python’s six constants living in the built-in namespace. The others are <a href="https://docs.python.org/3/library/constants.html#False">False</a>, <a href="https://docs.python.org/3/library/constants.html#True">True</a>, <a href="https://docs.python.org/3/library/constants.html#None">None</a>, <a href="https://docs.python.org/3/library/constants.html#Ellipsis">Ellipsis</a> and <a href="https://docs.python.org/3/library/constants.html#__debug__">__debug__</a>. Similar to <a href="https://docs.python.org/3/library/constants.html#Ellipsis">Ellipsis</a>, <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> <em>can</em> be reassigned (shadowed). Assignments to it, even as an attribute name, do <strong>not</strong> raise a SyntaxError. So it isn’t really a “real/true” constant. <strong>Of course, we should never ever re-assign it.</strong> But, for completeness:</p><pre>&gt;&gt;&gt; None = &#39;hello&#39;<br>...<br>SyntaxError: can&#39;t assign to keyword<br>&gt;&gt;&gt; NotImplemented<br>NotImplemented<br>&gt;&gt;&gt; NotImplemented = &#39;do not&#39;<br>&gt;&gt;&gt; NotImplemented<br>&#39;do not&#39;</pre><h4>What does it mean and when should it be used?</h4><p><a href="https://docs.python.org/3/library/constants.html">NotImplemented</a> is a special value which should be returned by the binary special methods (e.g. <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__">__eq__()</a>, <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__">__lt__()</a>, <a href="https://docs.python.org/3/reference/datamodel.html#object.__add__">__add__()</a>, <a href="https://docs.python.org/3/reference/datamodel.html#object.__rsub__">__rsub__()</a>, etc.) to indicate that the operation is not implemented with respect to the other type; it may be returned by the in-place binary special methods (e.g. <a href="https://docs.python.org/3/reference/datamodel.html#object.__imul__">__imul__()</a>, <a href="https://docs.python.org/3/reference/datamodel.html#object.__iand__">__iand__()</a>) for the same purpose. Also, its truth value is True:</p><pre>&gt;&gt;&gt; bool(NotImplemented)<br>True</pre><p>You might be asking yourself, “But I thought I should raise a <a href="https://docs.python.org/3/library/exceptions.html#NotImplementedError">NotImpementedError</a> when an operation is not implemented!”. We’ll see, with some examples, why that shouldn’t be the case when implementing binary special methods.</p><p>Let’s show the use of the NotImplemented constant by coding <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__">__eq__()</a> for two very basic (and useless) classes A and B. [For this simple example, <a href="https://docs.python.org/3/reference/datamodel.html#object.__ne__">__ne__()</a> won’t be implemented to avoid distraction, but in general, every time <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__">__eq__()</a> is implemented, <a href="https://docs.python.org/3/reference/datamodel.html#object.__ne__">__ne__()</a> should also be implemented unless there is a good reason for it not to be.]</p><pre># example.py</pre><pre>class A(object):<br>    def __init__(self, value):<br>        self.value = value</pre><pre>    def __eq__(self, other):<br>        if isinstance(other, A):<br>            print(&#39;Comparing an A with an A&#39;)<br>            return other.value == self.value<br>        if isinstance(other, B):<br>            print(&#39;Comparing an A with a B&#39;)<br>            return other.value == self.value<br>        print(&#39;Could not compare A with the other class&#39;)<br>        return NotImplemented</pre><pre>class B(object):<br>    def __init__(self, value):<br>        self.value = value</pre><pre>    def __eq__(self, other):<br>        if isinstance(other, B):<br>            print(&#39;Comparing a B with another B&#39;)<br>            return other.value == self.value<br>        print(&#39;Could not compare B with the other class&#39;)<br>        return NotImplemented</pre><p>Now, in the interpreter:</p><pre>&gt;&gt;&gt; from example import A, B<br>&gt;&gt;&gt; a1 = A(1)<br>&gt;&gt;&gt; b1 = B(1)</pre><p>We can now experiment with different calls to <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__">__eq__()</a> and see what happens. As a reminder, in Python, a == b results in a.__eq__(b) being called:</p><pre>&gt;&gt;&gt; a1 == a1<br>Comparing an A with an A<br>True</pre><p>As expected, a1 is equal to a1 (itself) and the __eq__() in class A took care of this comparison. Comparing b1 with itself will also yield a similar result:</p><pre>&gt;&gt;&gt; b1 == b1<br>Comparing a B with another B<br>True</pre><p>What if we now compare a1 with b1? Since in A’s __eq__() will check for other being an instance of B, we expect a1.__eq__(b1) to deal with the comparison and return <a href="https://docs.python.org/3/library/constants.html#True)">True</a>:</p><pre>&gt;&gt;&gt; a1 == b1<br>Comparing an A with a B<br>True</pre><p>And that is the case. Now, if we compare b1 with a1 (i.e. invoke b1.__eq__(a1)), we would expect <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> to be returned. This is because B’s __eq__() only compares against other B instances. Let’s see what happens:</p><pre>&gt;&gt;&gt; b1 == a1<br>Could not compare B against the other class<br>Comparing an A with a B<br>True</pre><p>Clever! b1.__eq__(a1) method returning <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> caused A’s __eq__() method to be called and since a comparison between A and B was defined in A’s __eq__() then we got the correct result (True).</p><p>And that is what returning <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> does. <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> tells the runtime that it should ask someone else to satisfy the operation. In the expression b1 == a1, b1.__eq__(a1) returns <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> which tells Python to try a1.__eq__(b1). Since a1 knows enough to return <a href="https://docs.python.org/3/library/constants.html#True)">True</a>, then the expression can succeed. If A’s __eq__() also returned <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a>, then the runtime would fall back to the built-in behaviour for equality which is based on object identity (which in CPython, is the object’s address in memory).</p><p>Note that raising a <a href="https://docs.python.org/3/library/exceptions.html#NotImplementedError">NotImpementedError</a> when b1.__eq__(a1) fails would break out of the code unless caught, whereas <a href="https://docs.python.org/3/library/constants.html#NotImplemented">NotImplemented</a> doesn’t get raised and can result in/be used for further tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d720137bf41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Importing `*` in Python]]></title>
            <link>https://s16h.medium.com/importing-star-in-python-88fe9e8bd4d2?source=rss-7f95b3128eaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/88fe9e8bd4d2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shahriar Tajbakhsh]]></dc:creator>
            <pubDate>Wed, 09 May 2018 15:42:42 GMT</pubDate>
            <atom:updated>2020-04-28T11:49:20.745Z</atom:updated>
            <content:encoded><![CDATA[<p>This post discusses Python’s from &lt;module&gt; import * and from &lt;package&gt; import *, how they behave and why it may be (is!) a bad idea to use them.</p><h4>Importing `*` from a module</h4><p>from &lt;module&gt; import * means “I want access to all the names in &lt;module&gt; that I’m meant to have access to”. So, let’s say we have the following something.py:</p><pre># something.py</pre><pre>public_variable = 42<br>_private_variable = 141</pre><pre>def public_function():<br>    print(&quot;I&#39;m a public function! yay!&quot;)</pre><pre>def _private_function():<br>    print(&quot;Ain&#39;t nobody accessing me from another module...usually&quot;)</pre><pre>class PublicClass(object):<br>    pass</pre><pre>class _WeirdClass(object):<br>    pass</pre><p>In the <a href="https://docs.python.org/3/tutorial/interpreter.html">Python Interpreter</a>, we can execute from something import * and see the following:</p><pre>&gt;&gt;&gt; from something import *<br>&gt;&gt;&gt; public_variable<br>42<br>&gt;&gt;&gt; _private_variable<br>...<br>NameError: name &#39;_private_variable&#39; is not defined<br>&gt;&gt;&gt; public_function()<br>&quot;I&#39;m a public function! yay!&quot;<br>&gt;&gt;&gt; _private_function()<br>...<br>NameError: name &#39;_private_function&#39; is not defined<br>&gt;&gt;&gt; c = PublicClass()<br>&gt;&gt;&gt; c<br>&lt;something.PublicClass object at ...&gt;<br>&gt;&gt;&gt; c = _WeirdClass()<br>...<br>NameError: name &#39;_WeirdClass&#39; is not defined</pre><p>So, from something import * imports all the names from something other than the names that start with an _; because they are conventionally meant to be <a href="https://docs.python.org/3/tutorial/classes.html#private-variables">private</a>.</p><h4>Ermm, that’s not too bad! Is that `__all__`?</h4><p>What’s not mentioned above is what __all__ is. <em>__all__ is a list of strings defining what symbols in a module (or a package as we’ll see later) will be exported when </em><em>from &lt;module&gt; import * is used on the module.</em> If we don’t define __all__ (we didn’t in something.py above), the default behaviour of import * is to import all names except those beginning with an underscore (_). Again, since conventionally an underscore is used to say a symbol is <a href="https://docs.python.org/3/tutorial/classes.html#private-variables">private</a>, that all makes sense. Let’s see what happens when we define our own __all__ in something.py:</p><pre># something.py</pre><pre>__all__ = [&#39;_private_variable&#39;, &#39;PublicClass&#39;]</pre><pre># The rest is the same as before</pre><pre>public_variable = 42<br>_private_variable = 141</pre><pre>def public_function():<br>    print(&quot;I&#39;m a public function! yay!&quot;)</pre><pre>def _private_function():<br>    print(&quot;Ain&#39;t nobody accessing me from another module...usually&quot;)</pre><pre>class PublicClass(object):<br>    pass</pre><pre>class _WeirdClass(object):<br>    pass</pre><p>Now, we expect from something import * to only import the _private_variable and PublicClass names:</p><pre>&gt;&gt;&gt; from something import *<br>&gt;&gt;&gt; public_variable<br>...<br>NameError: name &#39;public_variable&#39; is not defined<br>&gt;&gt;&gt; _private_variable<br>0<br>&gt;&gt;&gt; public_function()<br>...<br>NameError: name &#39;public_function&#39; is not defined<br>&gt;&gt;&gt; _private_function()<br>...<br>NameError: name &#39;_private_function&#39; is not defined<br>&gt;&gt;&gt; c = PublicClass()<br>&gt;&gt;&gt; c<br>&lt;something.PublicClass object at ...&gt;<br>&gt;&gt;&gt; c = _WeirdClass()<br>...<br>NameError: name &#39;_WeirdClass&#39; is not defined</pre><h4>What about packages?</h4><p>When <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package">importing * from a package</a>, __all__ does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when we use from &lt;package&gt; import *.</p><p>However, the difference is, when you omit the declaration of __all__ in a package’s __init__.py, the statement from &lt;package&gt; import * will not import anything at all (not entirely true; <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package">Read this</a> for the truth).</p><h4>But, why is this bad?</h4><p>Before proceeding, in your <a href="https://docs.python.org/3/tutorial/interpreter.html">Python Interpreter</a>, import this and read <a href="http://legacy.python.org/dev/peps/pep-0020/">The Zen of Python</a> again (read it to your kids every night before they sleep too).</p><blockquote>Explicit is better than implicit.</blockquote><p>from &lt;module&gt; import * is not explicit. It isn’t telling us anything about what we’re importing or what names we’re bringing into our namespace. It would be much better to explicitly specify and import everything we need; that way, a reader (most likely your future self) won’t be confused about where a variable/function/class/etc. used in the code comes from, which leads us to:</p><blockquote>Readability counts.</blockquote><p>Even if a lot of names are required, it’s still much clearer to import them one by one, explicitly. Use <a href="http://legacy.python.org/dev/peps/pep-0328/">PEP 328</a>:</p><pre>from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text, <br>        LEFT, DISABLED, NORMAL, RIDGE, END)</pre><p>You now know exactly what you have in your namespace and a quick ctrl+f (figuratively speaking) can tell you where a name has come from.</p><p>Also, you are always at risk if/when the module/package author decides to change the contents of the list (add/remove stuff to/from it). Then, either:</p><ol><li>The author has removed a string from __all__. If your code was using that name, your code will raise a NameError and it’ll be harder to find out why.</li><li>The author has added [many] new strings to __all__. You may not need all/any of the new names and you’re just bloating your namespace with stuff you don’t care about. They may even shadow some other names without you realising.</li></ol><p>Of course, sometimes it may be useful or necessary to import * from modules and/or packages. However, it’s best to make sure you really have to before doing it. In my experience, this construct is usually used as a result of laziness more than anything else.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88fe9e8bd4d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Optional `else` in Python’s `try` Statement]]></title>
            <link>https://s16h.medium.com/the-optional-else-in-pythons-try-statement-deb0079212e8?source=rss-7f95b3128eaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/deb0079212e8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shahriar Tajbakhsh]]></dc:creator>
            <pubDate>Sun, 06 May 2018 12:15:07 GMT</pubDate>
            <atom:updated>2020-04-28T11:49:28.050Z</atom:updated>
            <content:encoded><![CDATA[<p>This post discusses the else clause in Python’s <a href="https://docs.python.org/3.4/reference/compound_stmts.html#the-try-statement">try statement</a>. Although this particular use of else may not be as forgotten and controversial as <a href="https://medium.com/@s16h/the-forgotten-optional-else-in-python-loops-90d9c465c830">its use in Python loops</a>, a gentle reminder of how it works and when it’s useful may still be beneficial. Please note that this post only focuses on the else clause of the try statement and does not intend to cover the entire try statement. For a pretty good initial explanation of how the entire try statement works, refer to the <a href="https://docs.python.org/3/reference/compound_stmts.html#the-try-statement">official Python documentation on this topic</a>.</p><p>A “normal” stripped down try statement seen regularly looks something like this:</p><pre>try:<br>    # some code that might raise exception<br>except:<br>    # code to handle exception<br>finally:<br>    # code to run regardless of exception</pre><p>This is “normal” in the sense that to anyone coming from most other programming languages can understand/guess what it means:</p><ul><li>Some code will be tried to be executed.</li><li>If an exception is raised, the `except` block is executed, if not, it isn’t.</li><li>Regardless of an exception being raised or not, the code in the `finally` block will be executed.</li></ul><p>The big difference between exception handling in Python and other languages is that in Python using exceptions for flow control is common and normal. In fact, in many cases, you <em>must</em> use exceptions for control-flow. This is where the else clause comes in.</p><p>The optional else clause, which has to be before the finally clause (if there is one), is executed if and when control flows off the end of the try clause. Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement. So, for example:</p><pre>&gt;&gt;&gt; try:<br>...    print(&quot;Try: I&#39;ll try not to raise an exception.&quot;)<br>... except:<br>...    print(&quot;Except: You hopefully won&#39;t see me.&quot;)<br>... else:<br>...    print(&quot;Else: No exceptions was raised.&quot;)<br>... finally:<br>...    print(&quot;Finally: I&#39;m going to run anyway.&quot;)<br>...<br>Try: I&#39;ll try not to raise an exception.<br>Else: No exceptions was raised.<br>Finally: I&#39;m going to run anyway.</pre><h4>But, why!?</h4><p>As mentioned earlier, it is very common to use Python’s try statement as to control the flow of our program. So, the else clause is a very neat way of executing some code if an exception <em>isn’t</em> raised.</p><p>For instance, one way to check if a file exists is:</p><pre>try:<br>    f = open(&#39;some-file.txt&#39;)<br>except IOError:<br>    print(&quot;File doesn&#39;t exist :-(&quot;)<br>else:<br>    print(&quot;File exists!&quot;)</pre><p>If some-file.txt exists and opens successfully, then an exception will not be raised and the else clause will be executed (File exists! will be printed). Otherwise, the else clause will not be executed (File doesn’t exist :-( will be printed).</p><p>Also, without the else clause, the only option to run additional code before finalisation (which is rare) would be the clumsy practice of adding the code to the try clause. This is clumsy because it risks raising exceptions in code that wasn’t intended to be protected by the try statement.</p><p>In general, in Python, there is probably not a case where you have no choice but to use the else clause in a try statement. But, besides allowing you to control the flow of your program without much hassle, it <em>will</em> often make the code more elegant, readable and Pythonic as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb0079212e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Forgotten Optional `else` in Python Loops]]></title>
            <link>https://medium.com/swlh/the-forgotten-optional-else-in-python-loops-90d9c465c830?source=rss-7f95b3128eaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d9c465c830</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shahriar Tajbakhsh]]></dc:creator>
            <pubDate>Sat, 28 Apr 2018 14:43:09 GMT</pubDate>
            <atom:updated>2020-10-28T16:21:52.841Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we’ll discuss Python’s for...else and while...else syntax, one of the most rarely used and misunderstood features in Python.</p><p>Both <a href="https://docs.python.org/3.4/reference/compound_stmts.html#for">for</a> and <a href="https://docs.python.org/3.4/reference/compound_stmts.html#the-while-statement">while</a> loops in Python also take an optional else suite (like <a href="https://docs.python.org/3/tutorial/controlflow.html#if-statements">the </a><a href="https://docs.python.org/3/tutorial/controlflow.html#if-statements">if statement</a> and <a href="https://docs.python.org/3/reference/compound_stmts.html#the-try-statement">the </a><a href="https://docs.python.org/3/reference/compound_stmts.html#the-try-statement">try statement</a> do), which executes if the loop iteration completes normally. In other words, the else suite will be executed if we don’t exit the loop in any way other than its natural way. So, no break statements, no return statement, or no exceptions being raised inside the loop. Consider a simple (and useless) example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9d6cc3e7ade98c5620c47f6361398c/href">https://medium.com/media/6b9d6cc3e7ade98c5620c47f6361398c/href</a></iframe><p>In the code above, we iterate over range(5) and print each number. Since we let the loop complete normally, the else suite is also executed and Iterated over everything :) is printed. Conversely, if we stop the loop, say with a break statement, then the else suite will not be executed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4782c205ef11e7a371cf8ddd53b29e/href">https://medium.com/media/af4782c205ef11e7a371cf8ddd53b29e/href</a></iframe><p>Note that the else suite will be executed even if the sequences being iterated over by the loop is empty; after all, the loop is still completing normally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74f5efd60d4c5610914e8044e50cce70/href">https://medium.com/media/74f5efd60d4c5610914e8044e50cce70/href</a></iframe><p>Also, let’s not forget, all the above apply to while…else as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20e82338d67c8e4bb010e520f8fcf95e/href">https://medium.com/media/20e82338d67c8e4bb010e520f8fcf95e/href</a></iframe><h4>But, why!?</h4><p>A common use case for the else clause in loops is to implement search loops; say you’re performing a search for an item that meets a particular condition, and need to perform additional processing or raise an error if no acceptable value is found:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8d4bfeb412200ddc6cdf7bccc86e440/href">https://medium.com/media/e8d4bfeb412200ddc6cdf7bccc86e440/href</a></iframe><p>Without the else clause you would need to set a flag and then check that later to see if any of the values met the condition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57359856adf68a5ed43c9d2119600afd/href">https://medium.com/media/57359856adf68a5ed43c9d2119600afd/href</a></iframe><p>This isn’t really a big deal and it’s how you have to do it in many other languages. But like many other features of Python, the else clause can result in a more elegant and Pythonic code. Arguably, in the example above, using it makes the code more <a href="http://legacy.python.org/dev/peps/pep-0020/">The Zen of Python</a>-friendly:</p><p>There is not a case where you have no choice but to use the else clause in a loop; you can always use flags etc. but the else clause can often make the code more elegant and readable. One might think it’s Pythonic and it makes intentions clearer (Hi!), while others might think it’s confusing and redundant! Personally, I stick to using the else clause in loops unless there is another approach that is more readable (I guess, for me, it usually all boils down to how readable the code will be).</p><p>That’s all! If you enjoyed reading this, <a href="https://twitter.com/s16h_">follow me on Twitter</a>. Otherwise, <a href="https://twitter.com/s16h_">follow me on Twitter</a>, and tell me how much you hated reading this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d9c465c830" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-forgotten-optional-else-in-python-loops-90d9c465c830">The Forgotten Optional `else` in Python Loops</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>