<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://sharmapacific.in/feed.xml" rel="self" type="application/atom+xml" /><link href="https://sharmapacific.in/" rel="alternate" type="text/html" /><updated>2025-02-19T22:23:01+05:30</updated><id>https://sharmapacific.in/feed.xml</id><title type="html">Blog</title><subtitle>A blog about technology and stuff related</subtitle><entry><title type="html">Metaclasses in Python</title><link href="https://sharmapacific.in/metaclasses-in-python/" rel="alternate" type="text/html" title="Metaclasses in Python" /><published>2020-08-19T01:11:00+05:30</published><updated>2020-08-19T01:11:00+05:30</updated><id>https://sharmapacific.in/metaclasses-in-python</id><content type="html" xml:base="https://sharmapacific.in/metaclasses-in-python/"><![CDATA[<p>In most programming languages, classes are just pieces of code that define the rules for an object, but in Python, as you must hear that everything is an object: it turns out that this is true of classes themselves. classes are actually first-class objects, they can be created at runtime, passed as parameters, returned from functions, and assigned to variables.</p>

<p>let’s look at the below example -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Tutorial</span><span class="p">:</span>
    <span class="k">pass</span>

<span class="k">print</span><span class="p">(</span><span class="n">Tutorial</span><span class="p">())</span>

<span class="c1"># Output - 
# &lt;__main__.Tutorial object at 0x7fd92c1500f0&gt;
</span></code></pre></div></div>
<p>as we can see the instance of <code class="language-plaintext highlighter-rouge">Tutorial</code> class tells us that this is an object of the main Tutorial object. at some location.</p>

<p>Now just print the class itself -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="n">Tutorial</span><span class="p">)</span>

<span class="c1"># Output - 
# &lt;class '__main__.Tutorial'&gt;
</span></code></pre></div></div>
<p>The reason we’re able to do this because the <code class="language-plaintext highlighter-rouge">Tutorial</code> class is an object, just like any other object. When you use the <code class="language-plaintext highlighter-rouge">class</code> keyword, Python creates this object automatically. It’s an instance of a metaclass - <code class="language-plaintext highlighter-rouge">type</code>.</p>

<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/bgrlcqvkq3y9bd9jtkt3.jpg" alt="Alt Text" /></p>

<blockquote>
  <p>A metaclass is the class of a class; it defines how a class behaves.</p>
</blockquote>

<p>Now for making it easier, let go into depth, Maybe you have come across the <code class="language-plaintext highlighter-rouge">type</code> keyword in Python? Which used to finding the Type of an Object -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>

<span class="c1"># Output - 
# &lt;class 'int'&gt;
</span>
<span class="k">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="s">'Hey'</span><span class="p">))</span>

<span class="c1"># Output - 
# &lt;class 'str'&gt;
</span></code></pre></div></div>

<p>As expected <code class="language-plaintext highlighter-rouge">1</code> is the type of <code class="language-plaintext highlighter-rouge">int</code> class, <code class="language-plaintext highlighter-rouge">Hey</code> is the type of <code class="language-plaintext highlighter-rouge">str</code> class, let’s find out the Type of our Class -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">Tutorial</span><span class="p">))</span>

<span class="c1"># Output - 
# &lt;class 'type'&gt;
</span></code></pre></div></div>
<p>This time, we get a printout that <code class="language-plaintext highlighter-rouge">Tutorial</code> is of type of class <code class="language-plaintext highlighter-rouge">type</code>. But what about the <code class="language-plaintext highlighter-rouge">type</code> itself? What is the type’s <code class="language-plaintext highlighter-rouge">type</code>?</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="nb">type</span><span class="p">))</span>

<span class="c1"># Output - 
# &lt;class 'type'&gt;
</span></code></pre></div></div>
<p>the type of <code class="language-plaintext highlighter-rouge">type</code> is class <code class="language-plaintext highlighter-rouge">type</code>, you maybe find this weird. Thus we find that <code class="language-plaintext highlighter-rouge">type</code> is also its own metaclass!</p>

<h2 id="understanding-how-metaclasses-work">Understanding How Metaclasses Work</h2>

<p><code class="language-plaintext highlighter-rouge">type</code> is a built-in metaclass in python. it is used to construct classes just like a class is used to construct the objects. So Whenever we create any class then the default metaclass(<code class="language-plaintext highlighter-rouge">type</code>) gets called and giving us an option to use it as an object.
That means every class in python is also an object of <code class="language-plaintext highlighter-rouge">type</code>, Therefore We can use <code class="language-plaintext highlighter-rouge">type</code> directly to make a class, without any class syntax. The type() function can be used to directly define classes by using the following three arguments -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">type</span><span class="p">(</span><span class="o">&lt;</span><span class="n">name</span><span class="o">&gt;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">bases</span><span class="o">&gt;</span><span class="p">,</span> <span class="o">&lt;</span><span class="n">dct</span><span class="o">&gt;</span><span class="p">)</span>
</code></pre></div></div>
<ul>
  <li>
    <p><strong>name</strong> - This is the internal representation of the class. This is the name of the class.</p>
  </li>
  <li>
    <p><strong>bases</strong> - This specifies anything that we inherit from a superclass or a parent class. This is a tuple of the parent class.</p>
  </li>
  <li>
    <p><strong>dct</strong> - This specifies a namespace dictionary containing definitions of class’s methods and variables.</p>
  </li>
</ul>

<p>To make it more clear -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Test</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="s">'Test'</span><span class="p">,</span> <span class="p">(),</span> <span class="p">{})</span>
</code></pre></div></div>
<p>so the above line of code is completely equivalent to this below code -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Test</span><span class="p">:</span>
    <span class="k">pass</span>
</code></pre></div></div>
<p>there’s absolutely nothing different about them.</p>

<p>Hence, if we want to modify the behavior of classes, we will need to write our own custom metaclass.</p>

<p>To create our own custom metaclass, we first have to inherit the default metaclass <code class="language-plaintext highlighter-rouge">type</code>, and implement the metaclass’s <code class="language-plaintext highlighter-rouge">__new__</code> method and/or <code class="language-plaintext highlighter-rouge">__init__</code> method.</p>

<ul>
  <li>
    <p><code class="language-plaintext highlighter-rouge">__new__</code>: This dunder method is usually overridden type’s <code class="language-plaintext highlighter-rouge">__new__</code>, to modify some properties of the class to be created, 
before calling the original <code class="language-plaintext highlighter-rouge">__new__</code> which creates the class.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">__init__</code>: This method is called when you want to control the initialization after the instance/object has been created.</p>
  </li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MyMeta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attr</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="n">attr</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attr</span><span class="p">)</span>
</code></pre></div></div>
<p>So here I have defined a simple metaclass <code class="language-plaintext highlighter-rouge">MyMeta</code>, and we’re just going to print out the attributes so we can see how they look like. after that, I have defined another class <code class="language-plaintext highlighter-rouge">Sample</code> and it’s having the metaclass <code class="language-plaintext highlighter-rouge">MyMeta</code>, with <code class="language-plaintext highlighter-rouge">name</code> and <code class="language-plaintext highlighter-rouge">age</code> variable -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Sample</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">MyMeta</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="s">'bob'</span>
    <span class="n">age</span> <span class="o">=</span> <span class="mi">24</span>
</code></pre></div></div>
<p>Now without creating an instance this stills runs as you can see the output below -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="s">'__module__'</span><span class="p">:</span> <span class="s">'__main__'</span><span class="p">,</span> <span class="s">'__qualname__'</span><span class="p">:</span> <span class="s">'Sample'</span><span class="p">,</span> <span class="s">'name'</span><span class="p">:</span> <span class="s">'bob'</span><span class="p">,</span> <span class="s">'age'</span><span class="p">:</span> <span class="mi">24</span><span class="p">}</span>
</code></pre></div></div>
<p>So how this class <code class="language-plaintext highlighter-rouge">Sample</code> has been created -</p>

<p>Interpreter sees <code class="language-plaintext highlighter-rouge">metaclass=MyMeta</code> defined in <code class="language-plaintext highlighter-rouge">Sample</code>, So now the interpreter has information that default metaclass <code class="language-plaintext highlighter-rouge">type</code> must not be used to create <code class="language-plaintext highlighter-rouge">Sample</code> class, Instead, <code class="language-plaintext highlighter-rouge">MyMeta</code> must be used to create <code class="language-plaintext highlighter-rouge">Sample</code> class.</p>

<p>So, the interpreter makes a call to <code class="language-plaintext highlighter-rouge">MyMeta</code> to create class <code class="language-plaintext highlighter-rouge">Sample</code>, When <code class="language-plaintext highlighter-rouge">MyMeta</code> is got called, <code class="language-plaintext highlighter-rouge">__new__</code> of <code class="language-plaintext highlighter-rouge">MyMeta</code> is invoked and it prints out the attributes and using <code class="language-plaintext highlighter-rouge">type</code> its construct the instance of <code class="language-plaintext highlighter-rouge">MyMeta</code> which is <code class="language-plaintext highlighter-rouge">Sample</code> and returns to us the object.</p>

<p>This metaclass only overrides object creation. All other aspects of class and object behavior are still handled by type.</p>

<p>Now We’ve covered enough theory to understand what metaclasses are and how to write custom metaclasses. Now let’s look a simple real case scenario -</p>

<p>let’s suppose we have a requirement that all attributes of your class should be in upper case, There are multiple ways to achieve this functionality, but here we are going to achieve this using <code class="language-plaintext highlighter-rouge">metaclass</code> at the module level, So in namespace dictionary(attributes) if a key doesn’t start with a double underscore we need to change it to be uppercase -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MyMeta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">atts</span><span class="p">):</span>
        
        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'current_attributes - </span><span class="si">{</span><span class="n">atts</span><span class="si">}</span><span class="se">\n</span><span class="s">'</span><span class="p">)</span>
        <span class="n">new_atts</span> <span class="o">=</span> <span class="p">{}</span>
        
        <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">atts</span><span class="p">.</span><span class="n">items</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">key</span><span class="p">.</span><span class="n">startswith</span><span class="p">(</span><span class="s">'__'</span><span class="p">):</span>
                <span class="n">new_atts</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">val</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">new_atts</span><span class="p">[</span><span class="n">key</span><span class="p">.</span><span class="n">upper</span><span class="p">()]</span> <span class="o">=</span> <span class="n">val</span>

        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'modified_attributes - </span><span class="si">{</span><span class="n">new_atts</span><span class="si">}</span><span class="s">'</span><span class="p">)</span>        
        <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">new_atts</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">Sample</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">MyMeta</span><span class="p">):</span>
    <span class="n">x</span> <span class="o">=</span> <span class="s">'bob'</span>
    <span class="n">y</span> <span class="o">=</span> <span class="mi">24</span>
    
    <span class="k">def</span> <span class="nf">say_hi</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span><span class="p">(</span><span class="s">'hii'</span><span class="p">)</span>
</code></pre></div></div>
<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">current_attributes</span> <span class="o">-</span> <span class="p">{</span><span class="s">'__module__'</span><span class="p">:</span> <span class="s">'__main__'</span><span class="p">,</span> <span class="s">'__qualname__'</span><span class="p">:</span> <span class="s">'Sample'</span><span class="p">,</span> <span class="s">'x'</span><span class="p">:</span> <span class="s">'bob'</span><span class="p">,</span> <span class="s">'y'</span><span class="p">:</span> <span class="mi">24</span><span class="p">,</span> <span class="s">'say_hi'</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">function</span> <span class="n">Sample</span><span class="p">.</span><span class="n">say_hi</span> <span class="n">at</span> <span class="mh">0x7fd92c10d048</span><span class="o">&gt;</span><span class="p">}</span>

<span class="n">modified_attributes</span> <span class="o">-</span> <span class="p">{</span><span class="s">'__module__'</span><span class="p">:</span> <span class="s">'__main__'</span><span class="p">,</span> <span class="s">'__qualname__'</span><span class="p">:</span> <span class="s">'Sample'</span><span class="p">,</span> <span class="s">'X'</span><span class="p">:</span> <span class="s">'bob'</span><span class="p">,</span> <span class="s">'Y'</span><span class="p">:</span> <span class="mi">24</span><span class="p">,</span> <span class="s">'SAY_HI'</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">function</span> <span class="n">Sample</span><span class="p">.</span><span class="n">say_hi</span> <span class="n">at</span> <span class="mh">0x7fd92c10d048</span><span class="o">&gt;</span><span class="p">}</span>
</code></pre></div></div>
<p>As you can see above we have printed the current attributes and created a dictionary that we used to represent our modified attributes.</p>

<p>Here we are just checking if the key starts with a double underscore then just adds the proper value otherwise we are adding the uppercase attribute with that corresponding value.</p>

<p>Now to make sure that this is working let’s try, I have created an instance of <code class="language-plaintext highlighter-rouge">Sample</code>, and just print one of the old attributes.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">s</span> <span class="o">=</span> <span class="n">Sample</span><span class="p">()</span>
<span class="n">s</span><span class="p">.</span><span class="n">x</span>
</code></pre></div></div>
<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">AttributeError</span> <span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">ipython</span><span class="o">-</span><span class="nb">input</span><span class="o">-</span><span class="mi">18</span><span class="o">-</span><span class="mi">87</span><span class="n">b2922593a9</span><span class="o">&gt;</span> <span class="ow">in</span> <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span>
      <span class="mi">1</span> <span class="n">s</span> <span class="o">=</span> <span class="n">Sample</span><span class="p">()</span>
<span class="o">----&gt;</span> <span class="mi">2</span> <span class="n">s</span><span class="p">.</span><span class="n">x</span>

<span class="nb">AttributeError</span><span class="p">:</span> <span class="s">'Sample'</span> <span class="nb">object</span> <span class="n">has</span> <span class="n">no</span> <span class="n">attribute</span> <span class="s">'x'</span>
</code></pre></div></div>
<p>As expected we have got an error <code class="language-plaintext highlighter-rouge">AttributeError</code>, which is totally fine because we have just modified the construction of the object, let’s try to access by modified attributes -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">.</span><span class="n">X</span><span class="p">)</span>

<span class="n">s</span><span class="p">.</span><span class="n">SAY_HI</span><span class="p">()</span>
</code></pre></div></div>
<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">bob</span>
<span class="n">hii</span>
</code></pre></div></div>

<p>This is why they call it magic because with this kind of hook into the creation of classes you can really enforce quite a bit of constraint on how classes are created</p>

<p>So for example, if you want every single class in a specific module to never be allowed to use a certain attribute or to follow a specific pattern you could set metaclasses for those specific modules.</p>

<h2 id="conclusion">Conclusion</h2>

<p>The purpose of metaclasses isn’t to replace the class/object distinction with metaclass/class - it’s to change the behavior of class definitions (and thus their instances) in some way.
A reasonable pattern of metaclass use is doing something once when a class is defined rather than repeatedly whenever the same class is instantiated. When multiple classes share the same special behavior, repeating <code class="language-plaintext highlighter-rouge">metaclass=X</code> is obviously better than repeating the specific purpose code.</p>

<h2 id="reference">Reference</h2>
<p><a href="https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python">https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python</a></p>

<p><a href="https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses/393368">https://stackoverflow.com/questions/392160/what-are-some-concrete-use-cases-for-metaclasses/393368</a></p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="productivity" /><category term="tutorial" /><category term="metaclasses" /><category term="programming" /><summary type="html"><![CDATA[In most programming languages, classes are just pieces of code that define the rules for an object, but in Python, as you must hear that everything is an object: it turns out that this is true of classes themselves. classes are actually first-class objects, they can be created at runtime, passed as parameters, returned from functions, and assigned to variables.]]></summary></entry><entry><title type="html">Monkey Patching In Python</title><link href="https://sharmapacific.in/monkey-patching-in-python/" rel="alternate" type="text/html" title="Monkey Patching In Python" /><published>2020-06-20T04:15:00+05:30</published><updated>2020-06-20T04:15:00+05:30</updated><id>https://sharmapacific.in/monkey-patching-in-python</id><content type="html" xml:base="https://sharmapacific.in/monkey-patching-in-python/"><![CDATA[<h1 id="what-is-monkey-patching">What is Monkey patching</h1>
<p>In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime, which means monkey patch is a piece of Python code that extends or modifies other code at runtime.</p>

<p>Monkey patching can only be done in dynamic languages, of which python is a good example. In Monkey patching, we reopen the existing classes or methods in class at runtime and alters the behavior, which should be used cautiously, or you should use it only when you really need to. As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.</p>

<p>It is often used to replace or extends a method on the module or class level with a custom implementation.</p>

<p>Let’s Implementation monkey patching -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MonkeyPatch</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">num</span><span class="p">):</span>
        <span class="bp">self</span><span class="p">.</span><span class="n">num</span> <span class="o">=</span> <span class="n">num</span>

    <span class="k">def</span> <span class="nf">addition</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">num</span> <span class="o">+</span> <span class="n">other</span><span class="p">)</span>
    
<span class="n">obj</span> <span class="o">=</span> <span class="n">MonkeyPatch</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="n">obj</span><span class="p">.</span><span class="n">addition</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span>
</code></pre></div></div>
<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="mi">30</span>
</code></pre></div></div>
<p>As you can see below, now only two methods <code class="language-plaintext highlighter-rouge">__init__</code> and <code class="language-plaintext highlighter-rouge">addition</code> and are available for the above class object. (You can use <code class="language-plaintext highlighter-rouge">dir(obj)</code> also to get the members of the object)</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">inspect</span> 

<span class="n">inspect</span><span class="p">.</span><span class="n">getmembers</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">predicate</span><span class="o">=</span><span class="n">inspect</span><span class="p">.</span><span class="n">ismethod</span><span class="p">)</span>                                                                                                                                       
</code></pre></div></div>
<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[(</span><span class="s">'__init__'</span><span class="p">,</span>
  <span class="o">&lt;</span><span class="n">bound</span> <span class="n">method</span> <span class="n">MonkeyPatch</span><span class="p">.</span><span class="n">__init__</span> <span class="n">of</span> <span class="o">&lt;</span><span class="n">__main__</span><span class="p">.</span><span class="n">MonkeyPatch</span> <span class="nb">object</span> <span class="n">at</span> <span class="mh">0x7f32495d7c50</span><span class="o">&gt;&gt;</span><span class="p">),</span>
 <span class="p">(</span><span class="s">'addition'</span><span class="p">,</span>
  <span class="o">&lt;</span><span class="n">bound</span> <span class="n">method</span> <span class="n">MonkeyPatch</span><span class="p">.</span><span class="n">addition</span> <span class="n">of</span> <span class="o">&lt;</span><span class="n">__main__</span><span class="p">.</span><span class="n">MonkeyPatch</span> <span class="nb">object</span> <span class="n">at</span> <span class="mh">0x7f32495d7c50</span><span class="o">&gt;&gt;</span><span class="p">)]</span>
</code></pre></div></div>
<p>In the above piece code, we have already defined a <code class="language-plaintext highlighter-rouge">MonkeyPatch</code> class with an <code class="language-plaintext highlighter-rouge">addition</code> method, and later on, we are adding a new method to the <code class="language-plaintext highlighter-rouge">MonkeyPatch</code> class. Suppose the new method is as follows.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">subtraction</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">num2</span><span class="p">):</span>
    <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">num</span> <span class="o">-</span> <span class="n">num2</span>
</code></pre></div></div>
<p>Now how we add the above method to the <code class="language-plaintext highlighter-rouge">MonkeyPatch</code> class, simply just place <code class="language-plaintext highlighter-rouge">subtraction</code> function into <code class="language-plaintext highlighter-rouge">MonkeyPatch</code> class with an assignment statement, as below -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">MonkeyPatch</span><span class="p">.</span><span class="n">subtraction</span> <span class="o">=</span> <span class="n">subtraction</span>
</code></pre></div></div>
<p>the newly created <code class="language-plaintext highlighter-rouge">subtraction</code> function would be available for all existing instances as well as a new instance also, Let’s do some practical now -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">inspect</span>

<span class="n">inspect</span><span class="p">.</span><span class="n">getmembers</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">predicate</span><span class="o">=</span><span class="n">inspect</span><span class="p">.</span><span class="n">ismethod</span><span class="p">)</span>
</code></pre></div></div>
<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[(</span><span class="s">'__init__'</span><span class="p">,</span>
  <span class="o">&lt;</span><span class="n">bound</span> <span class="n">method</span> <span class="n">MonkeyPatch</span><span class="p">.</span><span class="n">__init__</span> <span class="n">of</span> <span class="o">&lt;</span><span class="n">__main__</span><span class="p">.</span><span class="n">MonkeyPatch</span> <span class="nb">object</span> <span class="n">at</span> <span class="mh">0x7f28186b8c88</span><span class="o">&gt;&gt;</span><span class="p">),</span>
 <span class="p">(</span><span class="s">'addition'</span><span class="p">,</span>
  <span class="o">&lt;</span><span class="n">bound</span> <span class="n">method</span> <span class="n">MonkeyPatch</span><span class="p">.</span><span class="n">addition</span> <span class="n">of</span> <span class="o">&lt;</span><span class="n">__main__</span><span class="p">.</span><span class="n">MonkeyPatch</span> <span class="nb">object</span> <span class="n">at</span> <span class="mh">0x7f28186b8c88</span><span class="o">&gt;&gt;</span><span class="p">),</span>
 <span class="p">(</span><span class="s">'subtraction'</span><span class="p">,</span>
  <span class="o">&lt;</span><span class="n">bound</span> <span class="n">method</span> <span class="n">subtraction</span> <span class="n">of</span> <span class="o">&lt;</span><span class="n">__main__</span><span class="p">.</span><span class="n">MonkeyPatch</span> <span class="nb">object</span> <span class="n">at</span> <span class="mh">0x7f28186b8c88</span><span class="o">&gt;&gt;</span><span class="p">)]</span>
</code></pre></div></div>
<p>Did you notice for the existing object <code class="language-plaintext highlighter-rouge">obj</code> which we have defined earlier contained the newly created function, let’s check it out if the newly created function will work for the existing instance -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">obj</span><span class="p">.</span><span class="n">subtraction</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>               <span class="c1"># Working as expected
</span><span class="mi">9</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">obj_1</span> <span class="o">=</span> <span class="n">MonkeyPatch</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>          <span class="c1"># create some new object
</span><span class="o">&gt;&gt;&gt;</span> <span class="n">obj_1</span><span class="p">.</span><span class="n">subtraction</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="mi">8</span>
</code></pre></div></div>
<p><code class="language-plaintext highlighter-rouge">obj.subtraction</code> work as expected, but Keep in mind if a method already exists with the same name then this will change the behavior of the existing method.</p>

<h1 id="things-to-keep-in-mind">Things to keep in mind</h1>
<p>The best thing is not to monkey patch. You can define child classes for the ones you want to alter. Still, if monkey patch needed then follow these rules -</p>

<ol>
  <li>Use if you have a really good reason(like - temporary critical hotfix)</li>
  <li>Write proper documentation describing the reason for monkey patch</li>
  <li>Documentation should contain the information about the removal of the monkey patch and what to watch for. Lots of monkey patches are temporary, so they should be easy to remove.</li>
  <li>Try to make monkey patch as transparent as possible also place monkey patch code in separate files</li>
</ol>

<h1 id="conclusion">Conclusion</h1>
<p>Now we have learned how to do a monkey patch in Python. However, it has its own drawbacks and should be used carefully. Well, this often means the bad architecture of your application, and is not a good design decision, because it creates a discrepancy between the original source code on disk and the observed behavior and can be very confusing when troubleshooting.</p>

<h1 id="reference">Reference</h1>
<p>https://en.wikipedia.org/wiki/Monkey_patch
https://stackoverflow.com/questions/5626193/what-is-monkey-patching</p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="tutorial" /><category term="beginners" /><category term="productivity" /><category term="datascience" /><summary type="html"><![CDATA[What is Monkey patching In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime, which means monkey patch is a piece of Python code that extends or modifies other code at runtime.]]></summary></entry><entry><title type="html">SpeedUp Python List and Dictionary</title><link href="https://sharmapacific.in/speedup-python-list-and-dictionary/" rel="alternate" type="text/html" title="SpeedUp Python List and Dictionary" /><published>2020-05-03T22:42:00+05:30</published><updated>2020-05-03T22:42:00+05:30</updated><id>https://sharmapacific.in/speedup-python-list-and-dictionary</id><content type="html" xml:base="https://sharmapacific.in/speedup-python-list-and-dictionary/"><![CDATA[<p>Today, we will be discussing the optimization technique in Python. In this article, you will get to know to speed up your code by avoiding the re-evaluation inside a list and dictionary.</p>

<p>Here I have written the decorator function to calculate the execution time of a function.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">functools</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">timeit</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
    <span class="o">@</span><span class="n">functools</span><span class="p">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">func</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">newfunc</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">startTime</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span>
        <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="n">elapsedTime</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">startTime</span>
        <span class="k">print</span><span class="p">(</span><span class="s">'function - {}, took {} ms to complete'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">func</span><span class="p">.</span><span class="n">__name__</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="n">elapsedTime</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">)))</span>
    <span class="k">return</span> <span class="n">newfunc</span>
</code></pre></div></div>

<p>let’s move to the actual function</p>

<h2 id="avoid-re-evaluation-in-lists">Avoid Re-evaluation in Lists</h2>

<p><strong>Evaluating <code class="language-plaintext highlighter-rouge">nums.append</code> inside the loop</strong></p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">timeit</span>
<span class="k">def</span> <span class="nf">append_inside_loop</span><span class="p">(</span><span class="n">limit</span><span class="p">):</span>
    <span class="n">nums</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">limit</span><span class="p">:</span>
        <span class="n">nums</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">num</span><span class="p">)</span>

<span class="n">append_inside_loop</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9999999</span><span class="p">)))</span>
</code></pre></div></div>
<p>In the above function <code class="language-plaintext highlighter-rouge">nums.append</code> function references that are re-evaluated each time through the loop. After execution, The total time taken by the above function</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">o</span><span class="o">/</span><span class="n">p</span> <span class="o">-</span> <span class="n">function</span> <span class="o">-</span> <span class="n">append_inside_loop</span><span class="p">,</span> <span class="n">took</span> <span class="mi">529</span> <span class="n">ms</span> <span class="n">to</span> <span class="n">complete</span>
</code></pre></div></div>

<p><strong>Evaluating <code class="language-plaintext highlighter-rouge">nums.append</code> outside the loop</strong></p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">timeit</span>
<span class="k">def</span> <span class="nf">append_outside_loop</span><span class="p">(</span><span class="n">limit</span><span class="p">):</span>
    <span class="n">nums</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">append</span> <span class="o">=</span> <span class="n">nums</span><span class="p">.</span><span class="n">append</span>
    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">limit</span><span class="p">:</span>
        <span class="n">append</span><span class="p">(</span><span class="n">num</span><span class="p">)</span>

<span class="n">append_outside_loop</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9999999</span><span class="p">)))</span>
</code></pre></div></div>
<p>In the above function, I evaluate <code class="language-plaintext highlighter-rouge">nums.append</code> outside the loop and used <code class="language-plaintext highlighter-rouge">append</code> inside the loop as a variable. Total time is taken by the above function</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">o</span><span class="o">/</span><span class="n">p</span> <span class="o">-</span> <span class="n">function</span> <span class="o">-</span> <span class="n">append_outside_loop</span><span class="p">,</span> <span class="n">took</span> <span class="mi">328</span> <span class="n">ms</span> <span class="n">to</span> <span class="n">complete</span>
</code></pre></div></div>
<p>As you can see when I have evaluated the <code class="language-plaintext highlighter-rouge">append = nums.append</code> outside the <code class="language-plaintext highlighter-rouge">for</code> loop as a local variable, it took less time and speed-up the code by <code class="language-plaintext highlighter-rouge">201 ms</code>.</p>

<p>The same technique we can apply to the dictionary case also, look at the below example</p>

<h2 id="avoid-re-evaluation-in-dictionary">Avoid Re-evaluation in Dictionary</h2>

<p><strong>Evaluating <code class="language-plaintext highlighter-rouge">data.get</code> each time inside the loop</strong></p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">timeit</span>
<span class="k">def</span> <span class="nf">inside_evaluation</span><span class="p">(</span><span class="n">limit</span><span class="p">):</span>
    <span class="n">data</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">limit</span><span class="p">:</span>
        <span class="n">data</span><span class="p">[</span><span class="n">num</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>

<span class="n">inside_evaluation</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9999999</span><span class="p">)))</span>
</code></pre></div></div>
<p>Total Time taken by the above function -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">o</span><span class="o">/</span><span class="n">p</span> <span class="o">-</span> <span class="n">function</span> <span class="o">-</span> <span class="n">inside_evaluation</span><span class="p">,</span> <span class="n">took</span> <span class="mi">1400</span> <span class="n">ms</span> <span class="n">to</span> <span class="n">complete</span>
</code></pre></div></div>

<p><strong>Evaluating <code class="language-plaintext highlighter-rouge">data.get</code> outside the loop</strong></p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">timeit</span>
<span class="k">def</span> <span class="nf">outside_evaluation</span><span class="p">(</span><span class="n">limit</span><span class="p">):</span>
    <span class="n">data</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="n">get</span> <span class="o">=</span> <span class="n">data</span><span class="p">.</span><span class="n">get</span>
    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">limit</span><span class="p">:</span>
        <span class="n">data</span><span class="p">[</span><span class="n">num</span><span class="p">]</span> <span class="o">=</span> <span class="n">get</span><span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>


<span class="n">outside_evaluation</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9999999</span><span class="p">)))</span>
</code></pre></div></div>
<p>Total time taken by the above function -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">o</span><span class="o">/</span><span class="n">p</span> <span class="o">-</span> <span class="n">function</span> <span class="o">-</span> <span class="n">outside_evaluation</span><span class="p">,</span> <span class="n">took</span> <span class="mi">1189</span> <span class="n">ms</span> <span class="n">to</span> <span class="n">complete</span>
</code></pre></div></div>
<p>As you can see we have speed-up the code here by <code class="language-plaintext highlighter-rouge">211 ms</code>.</p>

<p>I hope you like the explanation of the optimization technique in Python for the list and dictionary. Still, if any doubt or improvement regarding it, ask in the comment section. Also, don’t forget to share your optimization technique.</p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="productivity" /><category term="tutorial" /><category term="beginners" /><summary type="html"><![CDATA[Today, we will be discussing the optimization technique in Python. In this article, you will get to know to speed up your code by avoiding the re-evaluation inside a list and dictionary.]]></summary></entry><entry><title type="html">Mutable Default Arguments in Python</title><link href="https://sharmapacific.in/mutable-default-arguments-in-python/" rel="alternate" type="text/html" title="Mutable Default Arguments in Python" /><published>2020-03-20T02:36:00+05:30</published><updated>2020-03-20T02:36:00+05:30</updated><id>https://sharmapacific.in/mutable-default-arguments-in-python</id><content type="html" xml:base="https://sharmapacific.in/mutable-default-arguments-in-python/"><![CDATA[<p>Objects of built-in types like (int, float, bool, str, tuple, Unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable.
A mutable object can change its state or contents and immutable objects cannot.</p>

<p>This is a very simple definition of a Mutable and Immutable object in Python. Now coming to the interesting part which is Mutable Default Object in function definitions.</p>

<p>I have written a very simple function as below -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">foobar</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">[]):</span>
    <span class="n">data</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">data</span>
</code></pre></div></div>
<p>In the above function, I set <code class="language-plaintext highlighter-rouge">data</code> to a list(Mutable object) as a default argument. Now let’s execute this function -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="n">foobar</span><span class="p">(</span><span class="mi">12</span><span class="p">))</span>
<span class="p">[</span><span class="mi">12</span><span class="p">]</span>
</code></pre></div></div>
<p>The output is as expected, Now execute multiple times -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="n">foobar</span><span class="p">(</span><span class="mi">22</span><span class="p">))</span>
<span class="p">[</span><span class="mi">12</span><span class="p">,</span> <span class="mi">22</span><span class="p">]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="n">foobar</span><span class="p">(</span><span class="mi">32</span><span class="p">))</span>
<span class="p">[</span><span class="mi">12</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">32</span><span class="p">]</span>
</code></pre></div></div>
<p>What is going on here? As you can see, the first time, the function returns exactly what we expected. On the second and all subsequent passes the same list is used in each call.</p>
<h2 id="why-is-this-happening"><strong>Why is this happening</strong></h2>

<p>Python’s default arguments are evaluated once when the function is defined, not each time the function is called. When Python encounters it, the first thing it will do is compile it in order to create a code object for this function. While this compilation step is done, Python evaluates and then stores the default arguments in the function object itself.</p>

<p>So, let’s do some introspection, to clear the confusions, I have taken a few lines of code as below-</p>
<ul>
  <li>Function Before Execution -</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">l</span><span class="o">=</span><span class="p">[]):</span>
    <span class="n">l</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</code></pre></div></div>
<p>After function executes this definition, You can check the default attribute for this function. by using <code class="language-plaintext highlighter-rouge">__defaults__</code>.</p>
<blockquote>
  <p>About <code class="language-plaintext highlighter-rouge">__defaults__</code> 
A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value.</p>
</blockquote>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">.</span><span class="n">__defaults__</span>
<span class="p">([],)</span>
</code></pre></div></div>
<p>The result an empty list as the only entry in <code class="language-plaintext highlighter-rouge">__defaults__</code></p>
<ul>
  <li>Function After Execution-</li>
</ul>

<p>Let’s now execute this function and check the defaults.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">.</span><span class="n">__defaults__</span>
<span class="p">([</span><span class="mi">10</span><span class="p">],)</span>
</code></pre></div></div>
<p>Astonished? The value inside the object changes, Consecutive calls to the function will now simply append to that embedded list object:</p>

<p>Let’s execute the function multiple times:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">()</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">foo</span><span class="p">.</span><span class="n">__defaults__</span>
<span class="p">([</span><span class="mi">10</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">10</span><span class="p">],)</span>

</code></pre></div></div>

<p>The reason why this is happening because default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time).</p>

<h2 id="the-solution"><strong>The Solution</strong></h2>

<p>Now, the question is how to code <code class="language-plaintext highlighter-rouge">foobar</code> in order to get the behavior that we expected.</p>

<p>Fortunately, the solution is straightforward. The mutable objects used as defaults are replaced by None, and then the arguments are tested for None.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">foobar</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">data</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">data</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">data</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">foobar</span><span class="p">(</span><span class="mi">12</span><span class="p">)</span>
<span class="p">[</span><span class="mi">12</span><span class="p">]</span>
</code></pre></div></div>

<p>So, by replacing mutable default arguments with None solved our problem.</p>

<h2 id="good-use-of-mutable-default-argument">Good Use of Mutable Default Argument</h2>
<p>However, Mutable Default Argument have some good use-case also as following-</p>

<p>1.Binding local variable to the current value of the outer variable in a callback</p>

<p>2.Cache/Memoization</p>

<p>I hope you like the explanation of Mutable Default Arguments in Python. Still, if any doubt or improvement regarding it, ask in the comment section.</p>

<p>References:</p>

<p>https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy</p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="productivity" /><category term="tutorial" /><category term="beginners" /><summary type="html"><![CDATA[Objects of built-in types like (int, float, bool, str, tuple, Unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable. A mutable object can change its state or contents and immutable objects cannot.]]></summary></entry><entry><title type="html">Assignment vs Shallow Copy vs Deep Copy in Python</title><link href="https://sharmapacific.in/assignment-vs-shallow-copy-vs-deep-copy-in-python/" rel="alternate" type="text/html" title="Assignment vs Shallow Copy vs Deep Copy in Python" /><published>2020-02-02T22:57:00+05:30</published><updated>2020-02-02T22:57:00+05:30</updated><id>https://sharmapacific.in/assignment-vs-shallow-copy-vs-deep-copy-in-python</id><content type="html" xml:base="https://sharmapacific.in/assignment-vs-shallow-copy-vs-deep-copy-in-python/"><![CDATA[<p>Today, we will be discussing the copy in Python. There are three ways we can do it. In this article, you will get to know what each operation does and how they are different.</p>

<p>1 - Assignment Operator <code class="language-plaintext highlighter-rouge">(=)</code></p>

<p>2 - Shallow Copy</p>

<p>3 - Deep copy</p>

<h2 id="assignment-operator-"><strong>Assignment Operator (=)</strong></h2>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span> <span class="o">=</span> <span class="n">a</span>
</code></pre></div></div>
<p>In the above example of the assignment operator, It does not make a copy of the Python objects instead it copying a memory address (or pointer) from <code class="language-plaintext highlighter-rouge">a</code> to <code class="language-plaintext highlighter-rouge">b</code>, <code class="language-plaintext highlighter-rouge">(b=a)</code>. Which means both <code class="language-plaintext highlighter-rouge">a</code> &amp; <code class="language-plaintext highlighter-rouge">b</code> pointing to the same memory address.</p>

<p>Here we can use the <code class="language-plaintext highlighter-rouge">id()</code> method to get the address of the object in memory and check if both lists are pointing the same memory.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="bp">True</span>

<span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="s">'id of a - {}, id of b - {}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)))</span>
<span class="nb">id</span> <span class="n">of</span> <span class="n">a</span> <span class="o">-</span> <span class="mi">140665942562048</span><span class="p">,</span> <span class="nb">id</span> <span class="n">of</span> <span class="n">b</span> <span class="o">-</span> <span class="mi">140665942562048</span>

</code></pre></div></div>
<p>So, here if you would edit the new list, It’ll get updated in the original list also -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">b</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
</code></pre></div></div>
<p>Because there is only one instance of that list in the memory.</p>

<h2 id="shallow-copy"><strong>Shallow Copy</strong></h2>

<p>A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.</p>

<p>we have 3 different ways to create a shallow copy -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">nums</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>      

<span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">copy</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">m1</span> <span class="o">=</span> <span class="n">copy</span><span class="p">.</span><span class="n">copy</span><span class="p">(</span><span class="n">nums</span><span class="p">)</span>       <span class="c1"># make a shallow copy by using copy module
</span><span class="o">&gt;&gt;&gt;</span> <span class="n">m2</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">nums</span><span class="p">)</span>    <span class="c1"># make a shallow copy by using the factory function
</span><span class="o">&gt;&gt;&gt;</span> <span class="n">m3</span> <span class="o">=</span> <span class="n">nums</span><span class="p">[:]</span>       <span class="c1"># make a shallow copy by using the slice operator
</span></code></pre></div></div>
<p>Here all the above lists contains the same values as the original list -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="n">nums</span> <span class="o">==</span> <span class="n">m1</span> <span class="o">==</span> <span class="n">m2</span> <span class="o">==</span> <span class="n">m3</span><span class="p">)</span>
<span class="bp">True</span>
</code></pre></div></div>

<p>but the memory address of each is different -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="s">'nums_id - {}, m1_id - {}, m2_id - {}, m3_id = {}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">nums</span><span class="p">),</span> <span class="nb">id</span><span class="p">(</span><span class="n">m1</span><span class="p">),</span> <span class="nb">id</span><span class="p">(</span><span class="n">m2</span><span class="p">),</span> <span class="nb">id</span><span class="p">(</span><span class="n">m3</span><span class="p">)))</span>
<span class="n">nums_id</span> <span class="o">-</span> <span class="mi">140665942650624</span><span class="p">,</span> <span class="n">m1_id</span> <span class="o">-</span> <span class="mi">140665942758976</span><span class="p">,</span> <span class="n">m2_id</span> <span class="o">-</span> <span class="mi">140665942759056</span><span class="p">,</span> <span class="n">m3_id</span> <span class="o">=</span> <span class="mi">140665942692000</span>
</code></pre></div></div>
<p>This means that this time, each list’s object has its own, independent memory address.</p>

<p>Now move to the more interesting part. If the original list is a compound object (e.g. a list of lists), then after shallow copy new list elements are still referencing the original elements. 
So, if you modify the mutable elements like lists, the changes will be reflected on the original elements. Let’s look at the below example to get a better understanding -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">copy</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span> <span class="o">=</span> <span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]]</span>            
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span> <span class="o">=</span> <span class="n">copy</span><span class="p">.</span><span class="n">copy</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>

<span class="o">&gt;&gt;&gt;</span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="bp">False</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span>
<span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span>
<span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]]</span>      <span class="c1"># changes reflected in original list also
</span>
</code></pre></div></div>
<p>As you see in the above example while we are modifying the internal list elements in the new list, it’s getting updated in the original list also, because <code class="language-plaintext highlighter-rouge">a[0]</code> and <code class="language-plaintext highlighter-rouge">b[0]</code> are still pointing to the same memory address(original list).</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="k">print</span><span class="p">(</span><span class="s">'a[0] - {} , b[0] - {}'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]),</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">])))</span>       
<span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="mi">140399422977280</span> <span class="p">,</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="mi">140399422977280</span>
<span class="o">&gt;&gt;&gt;</span>

<span class="o">&gt;&gt;&gt;</span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="bp">True</span>
<span class="o">&gt;&gt;&gt;</span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="bp">True</span>
</code></pre></div></div>
<p>So the new list <code class="language-plaintext highlighter-rouge">b</code> has its own memory address but its elements do not.  because in shallow copy instead of copying the list’s elements to the new object, It simply copies the references to their memory addresses, Therefore while we are making changes to the original object it’s reflecting in copied objects and vice versa.</p>

<p>This is a characteristic of shallow copy.</p>

<h2 id="deep-copy"><strong>Deep copy</strong></h2>
<blockquote>
  <p>A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.</p>
</blockquote>

<p>Creating a deep copy is slower because you are making new copies for everything. In this rather than just copy the address of the compound objects, It Simply makes a full copy of all the list’s elements (simple and compound objects) of the original list and allocates different memory address for the new list and then assigns them the copied elements.</p>

<p>To achieve the deep copy we have to import the <code class="language-plaintext highlighter-rouge">copy</code> module. And use <code class="language-plaintext highlighter-rouge">copy.deepcopy()</code>.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">copy</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span> <span class="o">=</span> <span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]]</span>  
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span> <span class="o">=</span> <span class="n">copy</span><span class="p">.</span><span class="n">deepcopy</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>                     

<span class="o">&gt;&gt;&gt;</span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="bp">False</span>

<span class="o">&gt;&gt;&gt;</span> <span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>      <span class="c1"># memory address is different      
</span><span class="bp">False</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">append</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>            <span class="c1"># modify the list                                                                                                                                            
</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">a</span>
<span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">8</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">b</span>
<span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]]</span>        <span class="c1"># New list’s elements didn’t get affected
</span></code></pre></div></div>
<p>As you see above the original list does not get affected.</p>

<blockquote>
  <p>The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances).</p>
</blockquote>

<p>Hope you like the explanation of Assignment Operator, Shallow Copy and Deep Copy. Still, if any doubt or improvement regarding Copy in Python, ask in the comment section.</p>

<p>References:
https://docs.python.org/2/library/copy.html</p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="productivity" /><category term="tutorial" /><category term="beginners" /><summary type="html"><![CDATA[Today, we will be discussing the copy in Python. There are three ways we can do it. In this article, you will get to know what each operation does and how they are different.]]></summary></entry><entry><title type="html">Pickling and Unpickling in python Explained</title><link href="https://sharmapacific.in/pickling-and-unpickling-in-python-explained/" rel="alternate" type="text/html" title="Pickling and Unpickling in python Explained" /><published>2020-01-22T01:44:00+05:30</published><updated>2020-01-22T01:44:00+05:30</updated><id>https://sharmapacific.in/pickling-and-unpickling-in-python-explained</id><content type="html" xml:base="https://sharmapacific.in/pickling-and-unpickling-in-python-explained/"><![CDATA[<p>Pickling allows you to serialize and de-serializing Python object structures. In short, Pickling is a way to convert a python object into a character stream so that this character stream contains all the information necessary to reconstruct the object in another python script.</p>

<p>To successfully reconstruct the object, The Pickled byte stream contains instructions to the unpicker to reconstruct the original object structure along with instruction operands, which help in populating the object structure.</p>

<h2 id="pickle-protocols"><strong>Pickle protocols:</strong></h2>

<p>There are currently 6 different protocols that can be used for Pickling. The higher the protocol used, the more recent the version of Python needed to read the Pickle produced. To know more about <a href="https://docs.python.org/3/library/pickle.html">Pickle Protocol</a>.</p>

<p>Pickle has two main methods. The first one is a <code class="language-plaintext highlighter-rouge">dump</code>, which dumps an object to a file object and the second one is <code class="language-plaintext highlighter-rouge">load</code>, which loads an object from a file object.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pickle.dump(object, file_obj, protocol)
</code></pre></div></div>

<p>This function takes three arguments -</p>

<ol>
  <li>Python object to serialize.</li>
  <li>File object in which the serialized python object must be stored.</li>
  <li>Protocol (If a protocol is not specified, protocol 0 is used. If the protocol is specified as a negative value or <code class="language-plaintext highlighter-rouge">HIGHEST_PROTOCOL</code>, the highest protocol version available will be used.)</li>
</ol>

<p>So let’s continue to practical:</p>
<ul>
  <li>First of all, we have to import it through the following command:
    <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pickle</span>
</code></pre></div>    </div>
  </li>
</ul>

<p>Below is the example of pickling and unpickling -</p>
<h3 id="pickling">Pickling</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pickle</span>

<span class="k">def</span> <span class="nf">pickle_data</span><span class="p">():</span>
    <span class="n">data</span> <span class="o">=</span> <span class="p">{</span>
                <span class="s">'name'</span><span class="p">:</span> <span class="s">'Prashant'</span><span class="p">,</span>
                <span class="s">'profession'</span><span class="p">:</span> <span class="s">'Software Engineer'</span><span class="p">,</span>
                <span class="s">'country'</span><span class="p">:</span> <span class="s">'India'</span>
        <span class="p">}</span>
    <span class="n">filename</span> <span class="o">=</span> <span class="s">'PersonalInfo'</span>
    <span class="n">outfile</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s">'wb'</span><span class="p">)</span>
    <span class="n">pickle</span><span class="p">.</span><span class="n">dump</span><span class="p">(</span><span class="n">data</span><span class="p">,</span><span class="n">outfile</span><span class="p">)</span>
    <span class="n">outfile</span><span class="p">.</span><span class="n">close</span><span class="p">()</span>
    
<span class="n">pickle_data</span><span class="p">()</span>
</code></pre></div></div>
<p>To Open the file we used <code class="language-plaintext highlighter-rouge">open</code> function, The first argument should be the name of your file and the second argument is <code class="language-plaintext highlighter-rouge">wb</code>, <code class="language-plaintext highlighter-rouge">wb</code> refers the writing in binary mode. This means that the data will be written in the form of byte objects.</p>

<h3 id="unpickling">Unpickling</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">pickle</span>

<span class="k">def</span> <span class="nf">unpickling_data</span><span class="p">():</span>
    <span class="nb">file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span><span class="s">'rb'</span><span class="p">)</span>
    <span class="n">new_data</span> <span class="o">=</span> <span class="n">pickle</span><span class="p">.</span><span class="n">load</span><span class="p">(</span><span class="nb">file</span><span class="p">)</span>
    <span class="nb">file</span><span class="p">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">new_data</span>


<span class="k">print</span><span class="p">(</span><span class="n">unpickling_data</span><span class="p">())</span>
</code></pre></div></div>
<p>Here <code class="language-plaintext highlighter-rouge">r</code> stands for reading mode and the <code class="language-plaintext highlighter-rouge">b</code> stands for binary mode. You’ll be reading a binary file.
The output of the Unpickling function is the same as we pickled.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'Prashant'</span><span class="p">,</span> <span class="s">'profession'</span><span class="p">:</span> <span class="s">'Software Engineer'</span><span class="p">,</span> <span class="s">'country'</span><span class="p">:</span> <span class="s">'India'</span><span class="p">}</span>
</code></pre></div></div>
<h2 id="what-can-be-pickled"><strong>What can be pickled?</strong></h2>
<p>The following data types can be pickled:</p>

<ul>
  <li>Booleans,</li>
  <li>Integers,</li>
  <li>Floats,</li>
  <li>Complex numbers,</li>
  <li>(normal and Unicode) Strings,</li>
  <li>Tuples,</li>
  <li>Lists,</li>
  <li>Sets, and Dictionaries that contain pickable objects.</li>
  <li>Built-in functions defined at the top level of a module</li>
  <li>Classes that are defined at the top level of a module</li>
</ul>

<h2 id="common-usecase-of-pickling"><strong>Common UseCase of Pickling</strong></h2>

<ol>
  <li>To save a program’s state data to disk so that it can carry on where it left off when restarted (persistence)</li>
  <li>Sending Python data over a TCP connection in a multi-core or distributed system (marshalling)</li>
  <li>Storing Python objects in a database</li>
</ol>

<h2 id="dangers-of-pickling"><strong>Dangers of Pickling</strong></h2>

<p>The documentation of the Pickle module states:</p>

<blockquote>
  <p>The Pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.</p>
</blockquote>

<h2 id="safe-implementation-of-pickle"><strong>Safe implementation of Pickle</strong></h2>
<ul>
  <li>The Pickle should never be used between unknown parties.</li>
  <li>Ensure the parties exchanging Pickle have an encrypted network connection.</li>
  <li>In case of unsecured connection, any alteration in Pickle can be verified by using a cryptographic signature. Pickle can be signed before the transmission, and its signature can be verified before loading it on the receiver side.</li>
</ul>

<p>I hope that you now have a fair understanding of Pickling/Unpickling in python.</p>

<h2 id="reference"><strong>Reference</strong></h2>
<p><a href="https://docs.python.org/3.8/library/pickle.html">https://docs.python.org/3.8/library/pickle.html</a></p>

<p><a href="https://stackoverflow.com/questions/7501947/understanding-pickling-in-python">https://stackoverflow.com/questions/7501947/understanding-pickling-in-python</a></p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="productivity" /><category term="tutorial" /><category term="beginners" /><summary type="html"><![CDATA[Pickling allows you to serialize and de-serializing Python object structures. In short, Pickling is a way to convert a python object into a character stream so that this character stream contains all the information necessary to reconstruct the object in another python script.]]></summary></entry><entry><title type="html">Garbage Collection in Python</title><link href="https://sharmapacific.in/garbage-collection-in-python/" rel="alternate" type="text/html" title="Garbage Collection in Python" /><published>2019-11-29T01:39:00+05:30</published><updated>2019-11-29T01:39:00+05:30</updated><id>https://sharmapacific.in/garbage-collection-in-python</id><content type="html" xml:base="https://sharmapacific.in/garbage-collection-in-python/"><![CDATA[<p>In languages like C or C++, the programmer is responsible for dynamic allocation and deallocation of memory on the heap. But in python programmer does not have to preallocate or deallocate memory.</p>

<p>Python uses following garbage collection algorithms for memory management.</p>

<ul>
  <li>
    <p>Reference counting</p>
  </li>
  <li>
    <p>Cycle-detecting algorithm (Circular References)</p>
  </li>
</ul>

<h3 id="reference-counting">Reference counting</h3>

<p>Reference counting is a simple procedure where referenced objects are deallocated when there is no reference to them in a program.
In short, When the reference count becomes <code class="language-plaintext highlighter-rouge">0</code>, the object is deallocated(frees its allocated memory).</p>

<p>Let’s have a look at below example -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">calculate_sum</span><span class="p">(</span><span class="n">num1</span><span class="p">,</span> <span class="n">num2</span><span class="p">):</span>
    <span class="n">total</span> <span class="o">=</span> <span class="n">num1</span> <span class="o">+</span> <span class="n">num2</span>
    <span class="k">print</span><span class="p">(</span><span class="n">total</span><span class="p">)</span>
</code></pre></div></div>

<p>In the above example, We have three local references <code class="language-plaintext highlighter-rouge">num1</code>, <code class="language-plaintext highlighter-rouge">num2</code> and <code class="language-plaintext highlighter-rouge">total</code>. Here <code class="language-plaintext highlighter-rouge">total</code> is different from <code class="language-plaintext highlighter-rouge">num1</code> and <code class="language-plaintext highlighter-rouge">num2</code> because it only has reference inside the block thus its reference count is 1, <code class="language-plaintext highlighter-rouge">num1</code> and <code class="language-plaintext highlighter-rouge">num2</code> referenced outside the block so maybe their reference count more than one.</p>

<p>So, here when the function has finished execution the referenced count of <code class="language-plaintext highlighter-rouge">total</code> reduced to <code class="language-plaintext highlighter-rouge">0</code>. Since it tracked by the garbage collector.</p>

<p>The garbage collector finds out that the <code class="language-plaintext highlighter-rouge">total</code> is no longer referenced(reference count field reaches <code class="language-plaintext highlighter-rouge">0</code>) and frees its allocated memory.</p>

<p>The Variables, which are declared outside of functions, such variables do not get destroyed even after function has finished execution.</p>

<p>We can do the manual deletion also using the <code class="language-plaintext highlighter-rouge">del</code> statement. <code class="language-plaintext highlighter-rouge">del</code> statement removes a variable and its reference. When the reference count reaches <code class="language-plaintext highlighter-rouge">0</code>, it will be collected by the garbage collector.</p>

<p>The reference counting algorithm has some issues also, such as circular references -</p>

<h3 id="circular-references">Circular References</h3>

<p>A reference cycle occurs when one or more objects are referencing each other.</p>

<p><img src="https://thepracticaldev.s3.amazonaws.com/i/wd5do4dybewld70sqjko.jpg" alt="Alt Text" /></p>

<p>As you can see in the above image, the <code class="language-plaintext highlighter-rouge">list</code> object is pointing to itself, and <code class="language-plaintext highlighter-rouge">object1</code> and <code class="language-plaintext highlighter-rouge">object2</code> are pointing to each other. The reference count for such objects is always at least <code class="language-plaintext highlighter-rouge">1</code>.</p>

<p>Let’s go to the practical -</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">gc</span>

<span class="n">gc</span><span class="p">.</span><span class="n">set_debug</span><span class="p">(</span><span class="n">gc</span><span class="p">.</span><span class="n">DEBUG_SAVEALL</span><span class="p">)</span> 

<span class="n">lst</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">lst</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">lst</span><span class="p">)</span>

<span class="n">lst_address</span> <span class="o">=</span> <span class="nb">id</span><span class="p">(</span><span class="n">lst</span><span class="p">)</span>

<span class="k">del</span> <span class="n">lst</span>

<span class="n">object_1</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">object_2</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">object_1</span><span class="p">[</span><span class="s">'obj2'</span><span class="p">]</span> <span class="o">=</span> <span class="n">object_2</span>
<span class="n">object_2</span><span class="p">[</span><span class="s">'obj1'</span><span class="p">]</span> <span class="o">=</span> <span class="n">object_1</span>

<span class="n">obj_address</span> <span class="o">=</span> <span class="nb">id</span><span class="p">(</span><span class="n">object_1</span><span class="p">)</span>

<span class="k">del</span> <span class="n">object_1</span><span class="p">,</span> <span class="n">object_2</span>
</code></pre></div></div>
<p>In the above example, the <code class="language-plaintext highlighter-rouge">del</code> statement removes the variable and its reference to the objects.</p>

<p>Let’s check-it deleted variables using <code class="language-plaintext highlighter-rouge">gc.collect</code>, <code class="language-plaintext highlighter-rouge">gc.collect</code> saves to <code class="language-plaintext highlighter-rouge">gc.garbage</code> instead of deleting.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="n">gc</span><span class="p">.</span><span class="n">collect</span><span class="p">()</span>
<span class="mi">3</span>
</code></pre></div></div>
<p>When we delete a variable, we only delete the <code class="language-plaintext highlighter-rouge">__main__</code> reference. Now we don’t have access to <code class="language-plaintext highlighter-rouge">lst</code>, <code class="language-plaintext highlighter-rouge">object_1</code> and <code class="language-plaintext highlighter-rouge">object_2</code> at all, but these variables still have 1 reference, it means reference count is 1, the reference count algorithm will not collect it.</p>

<p>Check the reference count as below-</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">sys</span>
<span class="k">print</span><span class="p">(</span><span class="n">sys</span><span class="p">.</span><span class="n">getrefcount</span><span class="p">(</span><span class="n">obj_address</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="n">sys</span><span class="p">.</span><span class="n">getrefcount</span><span class="p">(</span><span class="n">lst_address</span><span class="p">))</span>

<span class="mi">2</span>
<span class="mi">2</span>
<span class="c1"># 1 from the variable and 1 from getrefcount
</span></code></pre></div></div>
<p>Multiply this number by 1 Million objects and you may have absolutely a serious memory leak issue.</p>

<p>For this kind of Reference cycle, Python has another algorithm specially dedicated to discovering and destroying circular references. It is also the only controllable part of <a href="https://docs.python.org/3.6/library/gc.html">Python’s GC</a></p>

<h3 id="summary">Summary</h3>
<p>Python has 2 Garbage Collection algorithms. One for dealing with reference count, When the reference count reaches <code class="language-plaintext highlighter-rouge">0</code>, it removes the object and frees its allocated memory. The other is the Cycle-detecting algorithm which discovers and destroys circular references.</p>

<p>I hope that you now have a fair understanding of the Garbage Collection algorithms in python.</p>

<h3 id="reference">Reference</h3>
<p><a href="https://rushter.com/blog/python-garbage-collector/">https://rushter.com/blog/python-garbage-collector/</a></p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="beginners" /><category term="productivity" /><category term="tutorial" /><summary type="html"><![CDATA[In languages like C or C++, the programmer is responsible for dynamic allocation and deallocation of memory on the heap. But in python programmer does not have to preallocate or deallocate memory.]]></summary></entry><entry><title type="html">Global Interpreter Lock (GIL) in Python</title><link href="https://sharmapacific.in/global-interpreter-lock-gil-in-python/" rel="alternate" type="text/html" title="Global Interpreter Lock (GIL) in Python" /><published>2019-11-28T00:55:00+05:30</published><updated>2019-11-28T00:55:00+05:30</updated><id>https://sharmapacific.in/global-interpreter-lock-gil-in-python</id><content type="html" xml:base="https://sharmapacific.in/global-interpreter-lock-gil-in-python/"><![CDATA[<p>Any operation which is executed in the interpreter, GIL ensures that the interpreter is held by a single thread at a particular instant of time. it means that only one thread can be in a state of execution at any point in time.</p>

<p>Let’s take an example -</p>
<ul>
  <li>Single-Threaded</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">threading</span> <span class="kn">import</span> <span class="n">Thread</span>

<span class="n">COUNT</span> <span class="o">=</span> <span class="mi">50000000</span>

<span class="k">def</span> <span class="nf">countdown</span><span class="p">(</span><span class="n">num</span><span class="p">):</span>
    <span class="k">while</span> <span class="n">num</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">num</span> <span class="o">-=</span> <span class="mi">1</span>

<span class="n">start</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">countdown</span><span class="p">(</span><span class="n">COUNT</span><span class="p">)</span>
<span class="n">end</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span>

<span class="k">print</span><span class="p">(</span><span class="s">'Time is taken by single_threaded - {} Sec.'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">end</span> <span class="o">-</span> <span class="n">start</span><span class="p">)</span>
</code></pre></div></div>

<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Time</span> <span class="ow">is</span> <span class="n">taken</span> <span class="n">by</span> <span class="n">single_threaded</span> <span class="o">-</span> <span class="mf">1.9384803771972656</span> <span class="n">Sec</span><span class="p">.</span>
</code></pre></div></div>

<ul>
  <li>Multi-Threaded</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">threading</span> <span class="kn">import</span> <span class="n">Thread</span>

<span class="n">COUNT</span> <span class="o">=</span> <span class="mi">50000000</span>

<span class="k">def</span> <span class="nf">countdown</span><span class="p">(</span><span class="n">num</span><span class="p">):</span>
    <span class="k">while</span> <span class="n">num</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">num</span> <span class="o">-=</span> <span class="mi">1</span>

<span class="n">t1</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">countdown</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">COUNT</span><span class="o">//</span><span class="mi">2</span><span class="p">,))</span>
<span class="n">t2</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">countdown</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">COUNT</span><span class="o">//</span><span class="mi">2</span><span class="p">,))</span>

<span class="n">start</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span>
<span class="n">t1</span><span class="p">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">t2</span><span class="p">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">()</span>
<span class="n">end</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span>

<span class="k">print</span><span class="p">(</span><span class="s">'Time is taken by multi_threaded - {} Sec.'</span><span class="p">.</span><span class="nb">format</span><span class="p">(</span><span class="n">end</span> <span class="o">-</span> <span class="n">start</span><span class="p">))</span>
</code></pre></div></div>

<p>Output -</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Time</span> <span class="ow">is</span> <span class="n">taken</span> <span class="n">by</span> <span class="n">multi_threaded</span> <span class="o">-</span> <span class="mf">1.905367784500122</span> <span class="n">Sec</span><span class="p">.</span>
</code></pre></div></div>

<p>As you can see both the example <strong>single-threaded</strong> and <strong>multi-threaded</strong> take almost the same time to finish the execution because GIL restricts CPU to only work with a single thread.
So even if your system could be have multiple cores/processors. And multiple cores allow multiple threads to execute simultaneously. But since the interpreter is held by a single thread.  So Python threads cannot take advantage of multiple cores also.</p>

<h3 id="how-two-threads-perform-both-cpu-and-io-operations-during-execution--">How two threads perform both CPU and <code class="language-plaintext highlighter-rouge">I/O</code> operations during execution -</h3>

<ol>
  <li>The python interpreter creates a process and spawns the threads.</li>
  <li>When Thread 1 starts execution, it’ll acquire the GIL and lock it.</li>
  <li>Thread 2 has to wait for GIL to be released by Thread 1.</li>
  <li>In case if Thread 1 is waiting for IO from the client, it releases the GIL and  Thread 2 will acquire it and start the execution.</li>
  <li>Now suppose If Thread 1 gets the IO, Then Thread 1 has to wait for GIL to be release by Thread 2.</li>
</ol>

<p>A thread waiting for the GIL will do a timed wait on the GIL, with a preset interval that can be modified with <a href="https://docs.python.org/3/library/sys.html#sys.setswitchinterval">sys.setswitchinterval</a>.</p>

<p>Note that Python’s GIL is only really an issue for CPython, the reference implementation. Other implementations like Jython and IronPython don’t have a GIL, because the platforms they are built on Java for Jython, .NET for IronPython, they handle dynamic memory management differently, and so can safely run the Python code in multiple threads at the same time.</p>

<h3 id="why-cpython-use-gil--">Why CPython use GIL -</h3>

<p>Python is not get executed directly, it gets compiled into Python bytecode and bytecode is executed.</p>

<p>Python uses automatic memory management via garbage collection, implemented with a technique called <a href="https://dev.to/sharmapacific/garbage-collection-in-python-1d4g">reference counting</a>.</p>

<p>Python internally manages a data structure containing all object reference count, and when an object reference count reaches 0 it removes the object and frees its allocated memory.
However, race conditions in multithreaded programming made it so that the object reference count could be updated incorrectly, making it so that objects could be erroneously freed or never freed at all. One way to solve this problem is with more granular locking like locks are set on every shared object, but this would create issues such as increased overhead due to a lot of locks acquire/release requests, as well as increase the possibility of deadlock.</p>

<p>The Python developers instead chose to solve this problem by placing a lock around the entire interpreter, making each thread acquire this lock when it runs Python bytecode.  This avoids a lot of the performance issues around excessive locking but effectively serializes bytecode execution.</p>

<h3 id="why-use-multithreading-when-gil-exists--">Why use Multithreading when GIL exists -</h3>

<p>Suppose a Web application that receives requests from clients, does some query to the database and return the response to the client. While Waiting for IO to complete may take 90% (or more than that) of the time the request is processed. When a single-threaded application is waiting for IO and it just not using the core and the core is available for execution. So such application has a room for other threads to execute even on a single core.</p>

<p>So in this kind of case when one thread waiting for IO, it releases GIL and another thread can continue execution.</p>

<h3 id="benefits--">Benefits -</h3>
<ol>
  <li>It is faster in the single-threaded case.</li>
  <li>It is faster in the multi-threaded case for IO-bound programs.</li>
  <li>It is faster in the multi-threaded case for CPU-bound programs that do their compute-intensive work in C libraries.</li>
</ol>

<blockquote>
  <p><a href="https://docs.python.org/3.7/library/threading.html">Quote from the Python threading documentation</a>
In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use <a href="https://docs.python.org/3.7/library/multiprocessing.html#introduction">multiprocessing</a> or <a href="https://docs.python.org/3.7/library/concurrent.futures.html#processpoolexecutor">concurrent.futures.ProcessPoolExecutor</a>. 
However, threading is still an appropriate model if you want to run multiple [I/O-bound tasks simultaneously] (https://docs.python.org/3.7/library/threading.html).</p>
</blockquote>

<p>The GIL is a problem if, and only if, you are doing CPU-intensive work in pure Python. Many Python libraries solve this issue by using C extensions to bypass the GIL.</p>

<p>I hope that you now have a fair understanding of the Global Interpreter Lock in python.</p>

<h3 id="reference">Reference</h3>
<p><a href="https://rohanvarma.me/GIL/">https://rohanvarma.me/GIL/</a></p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="tutorial" /><category term="beginners" /><category term="productivity" /><summary type="html"><![CDATA[Any operation which is executed in the interpreter, GIL ensures that the interpreter is held by a single thread at a particular instant of time. it means that only one thread can be in a state of execution at any point in time.]]></summary></entry><entry><title type="html">How to Return JSON-Encoded Response for non-dict object</title><link href="https://sharmapacific.in/how-to-return-json-encoded-response-for-non-dict-object/" rel="alternate" type="text/html" title="How to Return JSON-Encoded Response for non-dict object" /><published>2019-11-27T23:17:00+05:30</published><updated>2019-11-27T23:17:00+05:30</updated><id>https://sharmapacific.in/how-to-return-json-encoded-response-for-non-dict-object</id><content type="html" xml:base="https://sharmapacific.in/how-to-return-json-encoded-response-for-non-dict-object/"><![CDATA[<p>An HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/JSON.</p>

<p>The first parameter, data, should be a dict instance. If non-dict object is passed as the first argument, a TypeError will be raised.</p>

<h4 id="example-dict-instance">Example dict instance:</h4>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">JsonResponse</span>

<span class="k">def</span> <span class="nf">user</span><span class="p">(</span><span class="n">req</span><span class="p">):</span>
    <span class="n">response</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s">'id'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
        <span class="s">'name'</span><span class="p">:</span> <span class="s">'Tom'</span><span class="p">,</span>
        <span class="s">'status'</span><span class="p">:</span> <span class="n">Active</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">JsonResponse</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="example-non-dict-object">Example non-dict object:</h4>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>return JsonResponse([1, 2, 3, 4])
</code></pre></div></div>

<p>TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False</p>

<p>By default, the JsonResponse’s first parameter, data, should be a dict instance. To pass any other JSON-serializable object you must set the safe parameter to False.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>return JsonResponse([1, 2, 3, 4], safe=False)
</code></pre></div></div>

<p>The safe boolean parameter defaults to True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed).</p>]]></content><author><name></name></author><category term="blog" /><category term="django" /><category term="beginners" /><category term="python" /><category term="tutorial" /><summary type="html"><![CDATA[An HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/JSON.]]></summary></entry><entry><title type="html">When to use continue, pass and break in python</title><link href="https://sharmapacific.in/when-to-use-continue-pass-and-break-in-python/" rel="alternate" type="text/html" title="When to use continue, pass and break in python" /><published>2019-11-27T23:16:00+05:30</published><updated>2019-11-27T23:16:00+05:30</updated><id>https://sharmapacific.in/when-to-use-continue-pass-and-break-in-python</id><content type="html" xml:base="https://sharmapacific.in/when-to-use-continue-pass-and-break-in-python/"><![CDATA[<h3 id="continue"><strong>continue</strong></h3>
<p>continue forces the loop to start at the next iteration. In short, continue will jump back to the top of the loop</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>a = [0, 1, 2]
for element in a:
    if not element:
        continue
    print(element)
</code></pre></div></div>
<p>output-</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1
2
</code></pre></div></div>
<p><strong>UseCase</strong>: The continue statement can be used to skip the current iteration only. Loop does not terminate but continues on with the next iteration.</p>
<h3 id="pass"><strong>pass</strong></h3>
<p>while pass means there is no code to execute here, it passes execution to the next statement. So pass will continue processing.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>a = [0, 1, 2]
for element in a:
     if not element:
         pass
     print(element)
</code></pre></div></div>
<p>output-</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0
1
2
</code></pre></div></div>
<p><strong>UseCase</strong>: You can use pass statement when you have created a method but have not implemented, yet.</p>
<h3 id="break"><strong>break</strong></h3>
<p>The break statement provides you with the opportunity to exit out of a loop when a given condition is triggered.</p>
<pre><code class="language-`">a = [0, 1, 2, 3, 4, 5]
for element in a:
    if element == 3:
        break
    print(element)
</code></pre>
<p>output-</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0
1
2
</code></pre></div></div>
<p><strong>UseCase</strong>: The break statement can use in a program to break out of a loop for the matching condition.</p>]]></content><author><name></name></author><category term="blog" /><category term="python" /><category term="beginners" /><category term="productivity" /><category term="codequality" /><summary type="html"><![CDATA[continue continue forces the loop to start at the next iteration. In short, continue will jump back to the top of the loop a = [0, 1, 2] for element in a: if not element: continue print(element) output- 1 2 UseCase: The continue statement can be used to skip the current iteration only. Loop does not terminate but continues on with the next iteration. pass while pass means there is no code to execute here, it passes execution to the next statement. So pass will continue processing. a = [0, 1, 2] for element in a: if not element: pass print(element) output- 0 1 2 UseCase: You can use pass statement when you have created a method but have not implemented, yet. break The break statement provides you with the opportunity to exit out of a loop when a given condition is triggered. a = [0, 1, 2, 3, 4, 5] for element in a: if element == 3: break print(element) output- 0 1 2 UseCase: The break statement can use in a program to break out of a loop for the matching condition.]]></summary></entry></feed>