<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Bhavani Ravi</title>
    <description>The latest articles on Forem by Bhavani Ravi (@bhavaniravi).</description>
    <link>https://forem.com/bhavaniravi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F129059%2F347b1007-6f80-4a9c-9d1e-5170f3414197.jpg</url>
      <title>Forem: Bhavani Ravi</title>
      <link>https://forem.com/bhavaniravi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/bhavaniravi"/>
    <language>en</language>
    <item>
      <title>Python super() vs Base.__init__ Method</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Mon, 08 Jan 2024 08:58:00 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/python-super-vs-baseinit-method-1mmp</link>
      <guid>https://forem.com/bhavaniravi/python-super-vs-baseinit-method-1mmp</guid>
      <description>&lt;p&gt;When defining a subclass, there are different ways to call the __init__ method of a parent class. Let’s start with a base class and go through each of these methods.&lt;/p&gt;

&lt;p&gt;For this blog, it’s better that you open a sample.py python file and follow along.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Base&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;object&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Base created&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Method 1 :: Using Parent Reference Directly
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChildA&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Base&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;Base&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Child A initlaized&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Method 2:: Using Super with child class
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChildB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Base&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Child B initlaized&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ChildB&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Method 3:: Using the super method
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChildC&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Base&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Child C initlaized&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Questions
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;What are the pros and cons of each method?&lt;/li&gt;
&lt;li&gt;Is there one single right way to do this?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When you run this code as a single Python script, initializing child classes A, B, and C., You will notice absolutely no difference.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;cA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ChildA&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;cB&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ChildB&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;cC&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ChildC&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How can we demystify this? Let’s start with the documentation.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;As of &lt;a href="https://docs.python.org/3/library/functions.html#super"&gt;Python3&lt;/a&gt; super() is same as super(ChildB, self).__init__(). That rules out one of the three methods.&lt;/li&gt;
&lt;li&gt;To compare Base.__init__(self) and super().__init__() we need multiple Inheritance. Consider the following snippet
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Base1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;     
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Base 1 created&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;     
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Base2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;     
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Base 2created&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;     
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s write the subclasses&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;A1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Base1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Base2&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;     
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Child A1 Initialized&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;     
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;A2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Base2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Base1&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;     
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Child A Initialized&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;     
        &lt;span class="nf"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt; &lt;span class="nf"&gt;__init__ &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s initialize the objects&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;a1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;A1&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;a2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;A2&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On running the above snippet, we get the following Output.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;Base&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;created&lt;/span&gt;
&lt;span class="n"&gt;Base&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;created&lt;/span&gt;
&lt;span class="n"&gt;Child&lt;/span&gt; &lt;span class="n"&gt;A1&lt;/span&gt; &lt;span class="n"&gt;initialized&lt;/span&gt;

&lt;span class="n"&gt;Base&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;created&lt;/span&gt;
&lt;span class="n"&gt;Base&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;created&lt;/span&gt;
&lt;span class="n"&gt;Child&lt;/span&gt; &lt;span class="n"&gt;A2&lt;/span&gt; &lt;span class="n"&gt;initialized&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case of class A1(Base1, Base2) Base1 is initialized first, followed by Base2. It’s the inverse for class A2. We can conclude that the methods are called based on the order of specification.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When you use the Base1.__init__() method, you lose out on this feature of Python&lt;/li&gt;
&lt;li&gt;When you introduce new hierarchies, renaming the classes will become a nightmare&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So how does Python know which function to call first, introducing MRO(Method Resolution Order)&lt;/p&gt;

&lt;h3&gt;
  
  
  Method Resolution Order
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Method Resolution Order(MRO) denotes the way a programming language resolves a method or attribute.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the case of single inheritance, the attribute is searched only at a single level, with multiple inheritance Python interpreter looks for the attribute in itself then its parents in the order of inheritance. In case of A1 -&amp;gt; Base 1 -&amp;gt; Base 2&lt;/p&gt;

&lt;p&gt;One can use the mro function to find the method resolution order of any particular class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;A2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mro&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="err"&gt;' &lt;/span&gt;&lt;span class="nc"&gt;__main__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;A2&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;, &amp;lt;class &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="n"&gt;__main__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Base2&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;, &amp;lt;class &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="n"&gt;__main__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Base1&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;, &amp;lt;class &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="nb"&gt;object&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Last Punch
&lt;/h3&gt;

&lt;p&gt;Comment out the super calls in base class and check the ouput of your script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Base1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Base 1 created&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# super(). __init__ () 
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Base2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nf"&gt;print &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Base 2 created&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# super(). __init__ ()
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What do you see?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;Base&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;created&lt;/span&gt;
&lt;span class="n"&gt;Child&lt;/span&gt; &lt;span class="n"&gt;A1&lt;/span&gt; &lt;span class="n"&gt;initlaized&lt;/span&gt;
&lt;span class="n"&gt;Base&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;created&lt;/span&gt;
&lt;span class="n"&gt;Child&lt;/span&gt; &lt;span class="n"&gt;A2&lt;/span&gt; &lt;span class="n"&gt;initlaized&lt;/span&gt;

&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="err"&gt;' &lt;/span&gt;&lt;span class="nc"&gt;__main__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;A2&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;, &amp;lt;class &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="n"&gt;__main__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Base2&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;, &amp;lt;class &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="n"&gt;__main__&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Base1&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;, &amp;lt;class &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="nb"&gt;object&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;&amp;gt;]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In spite of having Base1 and Base2 in the MRO list, mro won’t resolve the order unless the super() function is propagated all the way up to the base class, i.e., Python propagates the search for the attribute only until it finds one. Comment on the init method in Base1 and see for yourself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Base1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;pass&lt;/span&gt;

    &lt;span class="c1"&gt;# def __init__ (self):
&lt;/span&gt;    &lt;span class="c1"&gt;# self.prop1 = "Base 1"
&lt;/span&gt;    &lt;span class="c1"&gt;# self.prop11 = "Base 11"
&lt;/span&gt;    &lt;span class="c1"&gt;# print ("Base 1 created")
&lt;/span&gt;    &lt;span class="c1"&gt;# # super(). __init__ ()
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since Python can’t find the __init__ method in Base1 it checks Base2 before sending it all the way to object class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Base 2 created
Child A1 initlaized

Base 2 created
Child A2 initlaized
[&amp;lt;class ' __main__.A2'&amp;gt;, &amp;lt;class ' __main__.Base2'&amp;gt;, &amp;lt;class ' __main__.Base1'&amp;gt;, &amp;lt;class 'object'&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;People ask me why I love Python so much. It’s not because Python is simple and easy. It is all these things Python does to make things easy for us, sometimes a little hard, too :)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gumroad.com/l/LaFSj"&gt;_Want to build a project with Python, Join the Python to Project Bootcamp&lt;/a&gt;&lt;/p&gt;

</description>
      <category>django</category>
      <category>flask</category>
      <category>python</category>
    </item>
    <item>
      <title>Caching in Python</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Tue, 10 Jan 2023 19:50:03 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/caching-in-python-4aa0</link>
      <guid>https://forem.com/bhavaniravi/caching-in-python-4aa0</guid>
      <description>&lt;p&gt;Caching, is a concept that was gifted to software world from the hardware world. A cache is a temporary storage area that stores the used items for easy access. To put it in layman’s terms, it is the chair we all have.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.pinimg.com%2Foriginals%2F74%2F0d%2F3f%2F740d3fdb2d44fa270923baca7036d9c5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.pinimg.com%2Foriginals%2F74%2F0d%2F3f%2F740d3fdb2d44fa270923baca7036d9c5.png" alt="Image result for a chair with clothes memes"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This blog covers the basics of&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What are Caches?&lt;/li&gt;
&lt;li&gt;Caching Operations&lt;/li&gt;
&lt;li&gt;Cache Eviction Policies&lt;/li&gt;
&lt;li&gt;Implementation of Cache Eviction Policies&lt;/li&gt;
&lt;li&gt;Distributed Caching&lt;/li&gt;
&lt;li&gt;Caching In Python&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conventional Caches
&lt;/h2&gt;

&lt;p&gt;In the world of computer science, Caches are the hardware components that store the result of computation for easy and fast access. The major factor that contributes to the speed is its memory size and its location. The memory size of the cache is way less than an RAM. This reduces the number of scans to retrieve data. Caches are located closer to the consumer (CPU) hence the less latency.&lt;/p&gt;

&lt;h2&gt;
  
  
  Caching Operations
&lt;/h2&gt;

&lt;p&gt;There are two broad types of caches operation. Cache such as Browser caches, server caches, Proxy Caches, Hardware caches works under the principle of &lt;code&gt;read&lt;/code&gt; and &lt;code&gt;write&lt;/code&gt; caches.&lt;/p&gt;

&lt;p&gt;When dealing with caches we always have a huge chunk of memory which is time consuming to read and write to, DB, hard disk, etc., Cache is a piece of software/hardware sitting on top of it making the job faster.&lt;/p&gt;

&lt;h3&gt;
  
  
  Read Cache
&lt;/h3&gt;

&lt;p&gt;A read cache is a storage that stores the accessed items. Every time the client requests data from storage, the request hits the cache associated with the storage.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If the requested data is available on the cache, then it is a &lt;strong&gt;cache hit&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1XYx5MptiwNKcOL608AxhKnqwz3YreBRW" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1XYx5MptiwNKcOL608AxhKnqwz3YreBRW" alt="https://drive.google.com/uc?id=1XYx5MptiwNKcOL608AxhKnqwz3YreBRW"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;if not it is a &lt;strong&gt;Cache miss&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D151KU5oOAY1txG-u1Fdg6gigFkiHlUGKv" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D151KU5oOAY1txG-u1Fdg6gigFkiHlUGKv" alt="https://drive.google.com/uc?id=151KU5oOAY1txG-u1Fdg6gigFkiHlUGKv"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Now when accessing a data from cache some other process changes the data at this point you need to reload the cache with the newly changed data this it is a &lt;strong&gt;Cache invalidation&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1AbAc3ksg7ypkbHU0dS3L8_1_YEzG-fqJ" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1AbAc3ksg7ypkbHU0dS3L8_1_YEzG-fqJ" alt="https://drive.google.com/uc?id=1AbAc3ksg7ypkbHU0dS3L8_1_YEzG-fqJ"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Write Cache
&lt;/h3&gt;

&lt;p&gt;Write caches as the name suggests enables fast writes. Imagine a write-heavy system and we all know that writing to a DB is costly. Caches come handy and handle the DB write load which is later updated to the DB in batches. It is important to notice that, the data between the DB and the cache should always be synchronized. There are 3 ways one can implement a write cache.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Write Through&lt;/li&gt;
&lt;li&gt;Write Back&lt;/li&gt;
&lt;li&gt;Write Around&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1eLnTzi2raas9OLnQoH3E0hyzHv5u89Gf" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1eLnTzi2raas9OLnQoH3E0hyzHv5u89Gf" alt="https://drive.google.com/uc?id=1eLnTzi2raas9OLnQoH3E0hyzHv5u89Gf"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Write Through
&lt;/h4&gt;

&lt;p&gt;The write to the DB happens through the cache. Every time a new data is written in the cache it gets updated in the DB.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages&lt;/strong&gt; - There won’t be a mismatch of data between the cache and the storage&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Disadvantage&lt;/strong&gt; - Both the cache and the storage needs to be updated creating an overhead instead of increasing the performance&lt;/p&gt;

&lt;h4&gt;
  
  
  Write Back
&lt;/h4&gt;

&lt;p&gt;Write back is when the cache asynchronously updates the values to the DB at set intervals.&lt;/p&gt;

&lt;p&gt;This method swaps the advantage and disadvantage of &lt;em&gt;Write through&lt;/em&gt;. Though writing to a cache is faster of &lt;strong&gt;Data loss and inconsistency&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Write Around
&lt;/h4&gt;

&lt;p&gt;Write the data directly to the storage and load the cache only when the data is read.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A cache is not overloaded with data that is not read immediately after a write&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
    - Reduces the latency of the write-through method
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reading recently written data will cause a cache miss and is not suitable for such use-cases.
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Cache Eviction Policies
&lt;/h2&gt;

&lt;p&gt;Caches make the reads and write fast. Then it would only make sense to read and write all data to and from caches instead of using DBs. But, remember the speed comes only because caches are small. Larger the cache, longer it will take to search through it.&lt;/p&gt;

&lt;p&gt;So it is important that we optimize with space. Once a cache is full, We can make space for new data only by removing the ones are already in the cache. Again, it cannot be a guessing game, we need to maximize the utilization to optimize the output.&lt;/p&gt;

&lt;p&gt;The algorithms used to arrive at a decision of which data needs to be discarded from a cache is a &lt;strong&gt;cache eviction policy&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;LRU - Least Recently Used&lt;/li&gt;
&lt;li&gt;LFU - Least Frequently Used&lt;/li&gt;
&lt;li&gt;MRU - Most Recently Used&lt;/li&gt;
&lt;li&gt;FIFO - First In First Out&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  LRU - Least Recently Used
&lt;/h4&gt;

&lt;p&gt;As the name suggest when a cache runs out of space remove the &lt;code&gt;least recently used&lt;/code&gt; element. It is simple and easy to implement and sounds fair but for caching &lt;code&gt;frequency of usage&lt;/code&gt; has more weight than when it was last accessed which brings us to the next algorithm.&lt;/p&gt;

&lt;h4&gt;
  
  
  LFU - Least Frequently Used
&lt;/h4&gt;

&lt;p&gt;LFU takes both the age and frequency of data into account. But the problem here is frequently used data stagnates in the cache for a long time&lt;/p&gt;

&lt;h4&gt;
  
  
  MRU - Most Recently Used
&lt;/h4&gt;

&lt;p&gt;Why on earth will someone use an MRU algorithm after talking about the frequency of usage? Won’t we always re-read the data we just read? Not necessarily. Imaging the image gallery app, the images of an album gets cached and loaded when you swipe right. What about going back to the previous photo? Yes, the probability of that happening is less.&lt;/p&gt;

&lt;h4&gt;
  
  
  FIFO - First In First Out
&lt;/h4&gt;

&lt;p&gt;When caches start working like queues, you will have an FIFO cache. This fits well for cases involving pipelines of data sequentially read and processed.&lt;/p&gt;

&lt;h2&gt;
  
  
  LRU Implementation
&lt;/h2&gt;

&lt;p&gt;Caches are basically a hash table. Every data that goes inside it is hashed and stored making it accessible at O(1).&lt;/p&gt;

&lt;p&gt;Now how do we kick out the least recently used item, we by far only have a hash function and it’s data. We need to store the order of access in some fashion.&lt;/p&gt;

&lt;p&gt;One thing we can do is have an array where we enter the element as and when it is accessed. But calculating frequency in this approach becomes an overkill. We can’t go for another Hash table it is not an access problem.&lt;/p&gt;

&lt;p&gt;A doubly linked list might fit the purpose. Add an item to the linked list every time it is accessed and maintain it’s a reference in a hash table enabling us to access it at O(1).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2F0x0fff.com%2Fwp-content%2Fuploads%2F2015%2F02%2FLRUCache.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2F0x0fff.com%2Fwp-content%2Fuploads%2F2015%2F02%2FLRUCache.jpg" alt="https://i2.wp.com/0x0fff.com/wp-content/uploads/2015/02/LRUCache.jpg?fit=709%2C436&amp;amp;ssl=1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When the element is already present, remove it from its current position and add it to the end of the linked list.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where to Place the Caches?
&lt;/h2&gt;

&lt;p&gt;The closer the caches are to its consumer faster it is. Which might implicitly mean to place caches along with the webserver in case of a web application. But there are a couple of problems&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When a server goes down, we lose all the data associated with the server’s cache &lt;/li&gt;
&lt;li&gt;When there is a need to increase the size of the cache it would invade the memory allocated for the server.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D17PYGD6Qvlq3fQvc0nNVE7mU0vx03Uq3-" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D17PYGD6Qvlq3fQvc0nNVE7mU0vx03Uq3-" alt="https://drive.google.com/uc?id=17PYGD6Qvlq3fQvc0nNVE7mU0vx03Uq3-"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The most viable solution is to maintain a cache outside the server. Though it incorporates additional latency, it is worth for the reliability of caches.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Distributed Caching&lt;/strong&gt; is the concept of hosting a cache outside the server and scaling it independently.&lt;/p&gt;

&lt;h2&gt;
  
  
  When to Implement Caches?
&lt;/h2&gt;

&lt;p&gt;Finding the technologies to implement caches is the easiest of all steps. Caches promises high speed APIs and it might feel stupid not to incorporate them, but if you do it for wrong reasons, it just adds additional overhead to the system. So before implementing caches make sure&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The hit to your data store is high&lt;/li&gt;
&lt;li&gt;You have done everything you can to improve the speed at DB level.&lt;/li&gt;
&lt;li&gt;You have learnt and researched on various caching methodologies and systems and found what fits your purpose.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Implementation In Python
&lt;/h2&gt;

&lt;p&gt;To understand caching we need to understand the data we are dealing with. For this example I am using a simple MongoDB Schema of &lt;code&gt;User&lt;/code&gt; and &lt;code&gt;Event&lt;/code&gt; collections.&lt;/p&gt;

&lt;p&gt;We will have APIs to get &lt;code&gt;User&lt;/code&gt; and &lt;code&gt;Event&lt;/code&gt; by their associated IDs. The following code snippet comprise a helper function to get a respective document from MongoDB&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def read_document(db, collection, _id):
    collection = db[collection]
    return collection.find_one({"_id": _id})

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Python inbuilt LRU-Caching
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import jsonify
from functools import lru_cache

@app.route(“/user/&amp;lt;uid&amp;gt;“)
@lru_cache()
def get_user(uid):

    try:
        return jsonify(read_user(db, uid))
    except KeyError as e:
        return jsonify({”Status": “Error”, “message”: str(e)})

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

&lt;/div&gt;



&lt;p&gt;LRU-Caching like you see in the following example is easy to implement since it has out of the box Python support. But there are some disadvantages&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is simple that it can’t be extended for advanced functionalities&lt;/li&gt;
&lt;li&gt;Supports only one type of caching algorithm&lt;/li&gt;
&lt;li&gt;LRU-Caching is a classic example of server side caching, hence there is a possibility of memory overload in server.&lt;/li&gt;
&lt;li&gt;Cache timeout is not implicit, invalidate it manually&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Caching In Python Flask
&lt;/h3&gt;

&lt;p&gt;To support other caches like redis or memcache, Flask-Cache provides out of the box support.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;config = {’CACHE_TYPE’: ‘redis’} # or memcache
app = Flask( __name__ )
app.config.from_mapping(config)
cache = Cache(app)

@app.route(“/user/&amp;lt;uid&amp;gt;“)
@cache.cached(timeout=30)
def get_user(uid):
    try:
        return jsonify(read_user(db, uid))
    except KeyError as e:
        return jsonify({”Status": “Error”, “message”: str(e)})

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

&lt;/div&gt;



&lt;p&gt;With that, We have covered what caches are, when to use one and how to implement it in Python Flask.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://msol.io/blog/tech/youre-probably-wrong-about-caching/" rel="noopener noreferrer"&gt;You’re Probably Wrong About Caching&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fullstackpython.com/caching.html" rel="noopener noreferrer"&gt;Caching - Full Stack Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/@Alibaba_Cloud/redis-vs-memcached-in-memory-data-storage-systems-3395279b0941" rel="noopener noreferrer"&gt;Redis Vs Memcache&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=bIWnQ3F1eLA" rel="noopener noreferrer"&gt;Caching - A Trip Down the Rabbit Hole&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.mnot.net/blog/caching/" rel="noopener noreferrer"&gt;All About Caching&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>python</category>
      <category>caching</category>
      <category>redis</category>
    </item>
    <item>
      <title>7 Programming Anti-Patterns</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Sat, 23 Jul 2022 17:35:53 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/7-programming-anti-patterns-4jje</link>
      <guid>https://forem.com/bhavaniravi/7-programming-anti-patterns-4jje</guid>
      <description>&lt;h3&gt;
  
  
  Things to unlearn as you move from CodeNewbie to Developer
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jo_xDMnI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ADKoo7Ocu_vuvbv9w" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jo_xDMnI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ADKoo7Ocu_vuvbv9w" alt="" width="880" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Do you know “Spaghetti code”? The code base where everything lies everywhere and no one knows where what starts and where things end. It sounds like a plot for a project to end in a boom. But there are other equally scary anti-patterns you must avoid to run a successful project and to set yourself as an experienced developer.&lt;/p&gt;

&lt;p&gt;Anti-patterns are bad programming practices. Every programmer has their style. Certain styles would cause more harm to the codebase than good.&lt;/p&gt;

&lt;p&gt;Knowing, Recognizing, and steering away from anti-patterns will set you up for a good start in your Software Development journey.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Copy-Paste(Voodo) programming
&lt;/h3&gt;

&lt;p&gt;Copying text word-by-word is a practice writers use to develop their writing style. As a Python trainer, I have strongly vouched for &lt;a href="https://twitter.com/BhavaniRavi_/status/1317484513375649792?s=20&amp;amp;t=ikIjc1E2r7ZuFodQEMFTNw"&gt;copy-pasting code&lt;/a&gt; as a way of learning programming patterns and idioms.&lt;/p&gt;

&lt;p&gt;That is great when you are practicing. The problem arises when you bring this practice to work. E.g., when I was a newbie developer, I copied a piece of code to read files from stackoverflow and played around with it, and it seemed to work all fine until I gave it some real input and my system froze. I did not account for processing large files. The program loaded the whole file into the memory and took over my system.&lt;/p&gt;

&lt;p&gt;Blindly copy-pasting code without understanding the crux of it will do more harm to you and the system you are building.&lt;/p&gt;

&lt;p&gt;So, what is the alternative? Should you never copy-paste from Stackoverflow?&lt;/p&gt;

&lt;h3&gt;
  
  
  How to Copy for Practice?
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Understand the problem, write it down&lt;/li&gt;
&lt;li&gt;Find a solution that you find useful&lt;/li&gt;
&lt;li&gt;Copy-paste it into your code editor&lt;/li&gt;
&lt;li&gt;add comments to each line depending on your understanding&lt;/li&gt;
&lt;li&gt;Add print statements to prove your understanding is right&lt;/li&gt;
&lt;li&gt;Run the code&lt;/li&gt;
&lt;li&gt;Validate your assumptions&lt;/li&gt;
&lt;li&gt;If the code doesn’t solve the problem, tweak it&lt;/li&gt;
&lt;li&gt;Once the code works, make it better — easier to read, test, and optimize for space and time&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  How to Copy-Paste at work?
&lt;/h3&gt;

&lt;p&gt;When copy-pasting at work, see how the code interacts with the rest of the system.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Does it solve the problem you’re trying to address?&lt;/li&gt;
&lt;li&gt;Does this hold good for all test cases?&lt;/li&gt;
&lt;li&gt;Does the code style match with the rest of the codebase&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. Cargo Cult programming
&lt;/h3&gt;

&lt;p&gt;It’s Friday evening. Your customer has reported a high-priority bug. Every alert is going off on slack. The management wants a fix ASAP. You don’t know the root cause of the bug, but you know adding an if statement will suppress it &lt;em&gt;“for now”&lt;/em&gt;. That’s cargo-cult programming.&lt;/p&gt;

&lt;p&gt;Including code or program structures that serve no real purpose or understanding of the underlying problem by trial and approach is called &lt;strong&gt;Cargo cult programming&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It might sound a lot like Voodo programming, but the focus here is on viewing solutions clearly as a larger part of the system rather than whether it works or not.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.1 Cargo Cult Software Engineering
&lt;/h3&gt;

&lt;p&gt;Cargo cult software engineering is when you adopt a SE practice based on its popularity or mandated as &lt;em&gt;“best practice”&lt;/em&gt; without understanding the reasoning behind it.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to Avoid Cargo Cult Programming?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Know the system before making changes to it&lt;/li&gt;
&lt;li&gt;Ensure quick fixes are patched in only after the bug has been identified&lt;/li&gt;
&lt;li&gt;Ensure to make educated decisions about incorporating practices&lt;/li&gt;
&lt;li&gt;Incorporate code review and pair programming in your development practice&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3. A Big Ball of Mud
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;A big ball of mud is a software system lacking perceivable architecture. Although undesirable from a software engineering point of view, such systems are common in practice due to business pressures, developer turnover, and code entropy. They are a type of design anti-pattern.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  To Avoid Ball of Mud
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Understand the problem at hand, write it down&lt;/li&gt;
&lt;li&gt;Split them into individual solvable pieces&lt;/li&gt;
&lt;li&gt;Think of these pieces as individual functions&lt;/li&gt;
&lt;li&gt;Merge repeating sections into a single function. Always DRY (Do not repeat yourself)&lt;/li&gt;
&lt;li&gt;Solve the individual problems(use stackoverflow only here)&lt;/li&gt;
&lt;li&gt;Write tests for the individual pieces and how they work together&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A codebase is already a big ball of mud that needs refactored. Make a deal with your product team and get some time on this engineering effect. It will help you fast-track future development.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Code/Design smell
&lt;/h3&gt;

&lt;p&gt;Spinning up a set of features without proper design often results in a Code/Design smell. Poor design decisions will leave the system fragile and challenging to maintain.&lt;/p&gt;

&lt;p&gt;Adding code to an already flawed design will result in the accumulation of technical debt.&lt;/p&gt;

&lt;p&gt;One of the easiest ways to identify code smell is to look for&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Functions doing more than one task leave room for design smell.&lt;/li&gt;
&lt;li&gt;Classes/Modules that are too long&lt;/li&gt;
&lt;li&gt;Code is not segregated into functions and modules&lt;/li&gt;
&lt;li&gt;Code not testable&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5. Ego Programming
&lt;/h3&gt;

&lt;p&gt;Ego programming is when a programmer infuses their programming style as opposed to the one adopted by the organization because they have done so.&lt;/p&gt;

&lt;p&gt;E.g., In Python, one-liners are fancy but tend to make life difficult for other developers.&lt;/p&gt;

&lt;p&gt;When the whole Python world follows snake_case for naming functions, it won't hold good for one person to use camelCase only because they come from JS.&lt;/p&gt;

&lt;p&gt;There is no harm in developers trying to infuse a change that will improve the lives of other developers. Whenever such change is incorporated, certain checks should pass.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Is the code readable?&lt;/li&gt;
&lt;li&gt;Is the code modifiable?&lt;/li&gt;
&lt;li&gt;Is the code testable?&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  6. Golden Hammer
&lt;/h3&gt;

&lt;p&gt;Using one solution to every problem since it was proven successful in the past. Just because one tool, solution, or hack worked for some problem, it won’t work for all problems.&lt;/p&gt;

&lt;p&gt;Google might invest a whole SRE team to support the scale of millions, but when it comes to you, all you need is an alerting system ensuring you’re paged when things go down.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Boat Anchor
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;You know how project managers are; they will come back with more features. I have heard more than one tech lead mentioning this.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Adding more code to support a feature that you &lt;strong&gt;&lt;em&gt;might need in the future&lt;/em&gt;&lt;/strong&gt; is a boat anchor problem. It increases complexity.&lt;/p&gt;

&lt;p&gt;I already hear you saying, &lt;em&gt;“But I know my PM they will come back with features”&lt;/em&gt;. In that case, leave in abstractions, not the actual logic.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. Dead Code
&lt;/h3&gt;

&lt;p&gt;Have you ever come across a function where no team member knows what it does, but it works and is referred to everywhere. That’s dead code because&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;no one knows how to change/fix it.&lt;/li&gt;
&lt;li&gt;One day, one tweak, and it’s going to make the system dead&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Fixing Dead Code
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;From your POV, write down what the code does in a text editor line by line&lt;/li&gt;
&lt;li&gt;Add test cases to test each line of the code&lt;/li&gt;
&lt;li&gt;Run the test cases one by one as the test passes, and add a comment next to it&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Special Thanks to &lt;a href="https://twitter.com/bowrna_p"&gt;Bowrna&lt;/a&gt; and &lt;a href="https://twitter.com/StalwartCoder"&gt;Abhishek&lt;/a&gt; for proofreading the blog&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://thelearning.dev/7-programming-anti-patterns"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>software</category>
      <category>softwaredevelopment</category>
      <category>learningtocode</category>
      <category>softwaredesign</category>
    </item>
    <item>
      <title>Pytest — How to test that a function is called with specific parameters?</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Mon, 27 Jun 2022 03:12:52 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/pytest-how-to-test-that-a-function-is-called-with-specific-parameters-22n9</link>
      <guid>https://forem.com/bhavaniravi/pytest-how-to-test-that-a-function-is-called-with-specific-parameters-22n9</guid>
      <description>&lt;p&gt;Unit tests are written to test single possible units of your system. When you interact with an external system, such as reading a file from AWS S3, your tests must run without any dependency on this external system. The standard testing practice for this use case is to mock the function interacting with this external system and ensure everything else works as expected.&lt;/p&gt;

&lt;p&gt;To illustrate this example, Let’s start with a simple Python function that reads data from a CSV and writes it to another CSV.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def read_data(input_path=None, output_path=None): 
    input_path = input_path or "input_data/data.csv" 
    output_path = output_path or "output_data/output.csv" 
    with open(input_path, "r") as fin: 
        with open(output_path, "w") as fout: 
            fout.write(fin.read())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The test case we are interested in is to ensure that the open function is called with the passed param and not the default. Since open is a Python built-in, we don't have to test its logic explicitly.&lt;/p&gt;

&lt;p&gt;Let’s start by mocking the builtins.open built-in mock_open function using the patch decorator.&lt;br&gt;
&lt;/p&gt;

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

from unittest.mock import patch, mock_open, call

[@patch](http://twitter.com/patch)("builtins.open", new_callable=mock_open, read_data="data")
def test_file_logic(mock_open_obj):
    read_data(input_path, output_path)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we have to ensure the read_data function calls the open method with the expected input and output path. assert_has_calls is a function of the mock object, which will check the trace of calls and ensure that the call with specific params is present.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pytest 
import script 
from unittest.mock import patch, mock_open, call 

@patch("builtins.open", new_callable=mock_open, read_data="data") def test_file_logic(mock_open_obj): 
    read_data(input_path, output_path)     
    mock_open_obj.assert_has_calls([call(expected_output_path, "w"),         
                                    call(expected_input_path, "r")], 
                                    any_order=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The any_order is important because open go through various stack trace like __enter__ and doesn't appear in the order.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://thelearning.dev/pytest-how-to-test-that-a-function-is-called-with-specific-parameters"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>django</category>
      <category>pytest</category>
      <category>python</category>
      <category>unittest</category>
    </item>
    <item>
      <title>How to Create a Download Button Using React</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Thu, 02 Jun 2022 03:09:54 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/how-to-create-a-download-button-using-react-emf</link>
      <guid>https://forem.com/bhavaniravi/how-to-create-a-download-button-using-react-emf</guid>
      <description>&lt;h4&gt;
  
  
  A guide on creating a download button using React.
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GA5BXUlN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AxqyPKaWSUKLDpS3l" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GA5BXUlN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AxqyPKaWSUKLDpS3l" alt="" width="880" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When I was building &lt;a href="https://100ideas.in"&gt;100 Ideas&lt;/a&gt;, I wanted to give users an option to export their content in a text file. It was super simple. This post is an attempt to share that knowledge and log it for the future. Assuming you already know the basics of React, let's begin.&lt;/p&gt;

&lt;h4&gt;
  
  
  Create a Button
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="btnDiv"&amp;gt;
     &amp;lt;button id="downloadBtn" value="download"&amp;gt;Download&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Add Event Handler
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const downloadTxtFile = () =&amp;gt; {
    console.log("download logic goes here")
}

&amp;lt;div className="btnDiv"&amp;gt;
     &amp;lt;button id="downloadBtn" onClick={downloadTxtFile} value="download"&amp;gt;Download&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need to hook an event handler to the button's onClick event. Let's do that and see if everything works.&lt;/p&gt;

&lt;h4&gt;
  
  
  Add Download Logic
&lt;/h4&gt;

&lt;p&gt;To download a file, we need four things.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The content that's supposed to go into the file&lt;/li&gt;
&lt;li&gt;The file object&lt;/li&gt;
&lt;li&gt;A link to download the file object&lt;/li&gt;
&lt;li&gt;Finally, simulate that the user clicking the link
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const downloadTxtFile = () =&amp;gt; {
    // text content
    const texts = ["line 1", "line 2", "line 3"]

// file object
    const file = new Blob(texts, {type: 'text/plain'});

// anchor link
    const element = document.createElement("a");
    element.href = URL.createObjectURL(file);
    element.download = "100ideas-" + Date.now() + ".txt";

// simulate link click
    document.body.appendChild(element); // Required for this to work in FireFox
    element.click();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Notes&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Date.now() is to add the timestamp to file downloads&lt;/li&gt;
&lt;li&gt;The file blob doesn't add a newline to the texts automatically. You can use [texts.join('\n')] to add a new line&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://thelearning.dev/how-to-download-files-on-button-click-reactjs"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;




</description>
      <category>webdev</category>
      <category>css</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>3 Steps Improve Code Readability</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Fri, 09 Jul 2021 23:02:53 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/3-steps-improve-code-readability-n1g</link>
      <guid>https://forem.com/bhavaniravi/3-steps-improve-code-readability-n1g</guid>
      <description>&lt;p&gt;Do you want to write great code or step up as a developer? Every programmer wants to write perfect code, but due to ever-demanding business needs, hustle culture, we need to make trade-offs. We often don’t get to write that ideal code we dream of. Despite all that, we can ensure that the code we write is reasonably good. Here are three tips that I use that prevent your code from becoming a noodly mess.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Design Before Code
&lt;/h3&gt;

&lt;p&gt;Instead of jumping ahead and starting to code, when you see a problem, take a step back, and I said the problem into a chunk of solvable pieces. You lose the power of visualization when you start dealing with files with classes and functions. The program deconstruction helps us to look at the problems on a deeper level. I often take a piece of paper and lay down the necessary modules to solve the problem and visualize how they interact.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Is it Maintainable?
&lt;/h3&gt;

&lt;p&gt;Once you have a solid design, it’s time to poke holes in it and find flaws. Does it bear the load the Product managers going to bring in for the next release? Trust me, “Agile,” “Hustle,” and “startups” are not doing us any favor. You don’t have to over-engineer, but being aware of future changes lets us design change-friendly interfaces.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Is it intuitive?
&lt;/h3&gt;

&lt;p&gt;An intuitive Codebase is a step up from readable code. Remember, you are not coding just for yourself. You are coding for your team, your future self, and as the common joke goes, the Psychopath will take over your code 10 years from now. A well-modularised code that reads like English is much better than a single file with 200 lines.&lt;/p&gt;

&lt;p&gt;Look at the following example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;questions = read_quiz_questions() 
for question in questions: 
     display_question(question) 
     answer = get_answer() 
     calculate_score(question, answer)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without telling much about what this program does, You understand what’s happening. It’s more than readable. It’s intuitive.&lt;/p&gt;

&lt;p&gt;The above methods ensure that the code is easy to consume for other team members or the future you. While these give you reasonably good code, remember that it is just a starting point. Just because you are doing the above three doesn’t mean ignoring test cases, documentation, design patterns, etc. We will touch base on them in future posts.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://thelearning.dev/blog/3-steps-write-readable-code/"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>learningtocode</category>
      <category>codereview</category>
      <category>cleancode</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>Practice for Perfection</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Mon, 05 Jul 2021 15:45:08 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/practice-for-perfection-3l67</link>
      <guid>https://forem.com/bhavaniravi/practice-for-perfection-3l67</guid>
      <description>&lt;p&gt;Let’s say you are watching a youtube video. A youtube video that shows you how to wear a tie. Assuming that you have no prior knowledge of how to tie a tie, do you think you will acquire that skill by watching the video. Nope! I wish I have that kind of magic in me. Unfortunately, we are all humans. There is only one way to do it.&lt;/p&gt;

&lt;p&gt;First, you have to buy a tie, if you already don’t own one. Next, you gotta stand in front of the mirror, have the video on by the side. Try to follow through the video step by step. If you make a mistake, you unwrap it and try again. After 10 attempts or so, it gets a little better. Maybe at the 15th attempt, you jump up in joy because you finally got it.&lt;/p&gt;

&lt;p&gt;Not just tieing a tie, you can’t learn a skill without practicing it. Think about this, can you build your muscles just by watching your trainer workout? Can you learn pottery by watching a video? Remember all the skills you possess today, right from riding a bike to reading this piece of text. You learned it by practice.&lt;/p&gt;

&lt;p&gt;Don’t stop before starting. Pick up that skill you want to acquire, practice every day until it finally clicks.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://thelearning.dev/blog/practice-for-perfection/"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OZvc9kxV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AianeH2yZLSS5jmJD" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OZvc9kxV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AianeH2yZLSS5jmJD" alt=""&gt;&lt;/a&gt;Photo by &lt;a href="https://www.pexels.com/@fauxels?utm_content=attributionCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=pexels"&gt;fauxels&lt;/a&gt; from &lt;a href="https://www.pexels.com/photo/photo-of-keyboard-near-mouse-3184460/?utm_content=attributionCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=pexels"&gt;Pexels&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>100daysofcode</category>
      <category>practice</category>
      <category>learningtocode</category>
    </item>
    <item>
      <title>5 Packages that Python Devs Use Everyday</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Fri, 11 Jun 2021 05:15:41 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/5-packages-that-python-devs-use-everyday-24o8</link>
      <guid>https://forem.com/bhavaniravi/5-packages-that-python-devs-use-everyday-24o8</guid>
      <description>&lt;p&gt;As a Python developer, our life lives and revolves around the packages we use. For every problem we have, there is a package in Pypy that would lend its helping hand. Out of them, the following are some of the libraries that developers use every day. These packages are so special that it gets mentioned in almost every interview, there is a rich community around each of them&lt;/p&gt;

&lt;h3&gt;
  
  
  Pandas
&lt;/h3&gt;

&lt;p&gt;Anytime someone talks about data manipulation or data analytics, Pandas is your way to go. It has a &lt;a href="https://thelearning.dev/blog/learn-pandas-through-documentation"&gt;rich set of features&lt;/a&gt; that would help you in the Data Science world and the web world. I have found Pandas almost useful in anything from data transformation to data streaming across various data points.&lt;/p&gt;

&lt;p&gt;Stars — 29.9K&lt;/p&gt;

&lt;p&gt;Contributors- 970&lt;/p&gt;

&lt;p&gt;Stackoverflow Questions — 203,458 questions&lt;/p&gt;

&lt;h3&gt;
  
  
  Flask/Django
&lt;/h3&gt;

&lt;p&gt;The moment you want to build a web application, Flask or Django would be your go-to options. Django comes with many pre-defined modules that get you up and running without a lot of effort. If you have customization and unique functionalities in your web app, flask might be a better option. Both serve it’s purpose well and has rich features.&lt;/p&gt;

&lt;h4&gt;
  
  
  Flask
&lt;/h4&gt;

&lt;p&gt;Stars — 55.5K&lt;/p&gt;

&lt;p&gt;Contributors- 538&lt;/p&gt;

&lt;p&gt;Stackoverflow Questions — 45,720 Questions&lt;/p&gt;

&lt;h4&gt;
  
  
  Django
&lt;/h4&gt;

&lt;p&gt;Stars — 57.7K&lt;/p&gt;

&lt;p&gt;Contributors- 723&lt;/p&gt;

&lt;p&gt;Stackoverflow Questions — 267,651 Questions&lt;/p&gt;

&lt;h3&gt;
  
  
  Requests
&lt;/h3&gt;

&lt;p&gt;Another common use case of Python other than building web apps and APIs is consuming existing APIs. Requests library had made it real simple for developers with just 4 key functions. Requests rule the API consumption spectrum of Python despite having urllib in its stdlib&lt;/p&gt;

&lt;p&gt;Stars — 45.3K&lt;/p&gt;

&lt;p&gt;Contributors — 563&lt;/p&gt;

&lt;p&gt;Stackoverflow Questions — 16,909 Questions&lt;/p&gt;

&lt;h3&gt;
  
  
  Pytest
&lt;/h3&gt;

&lt;p&gt;Pytest is gaining popularity because of its ease of use and makes writing test-cases a pleasurable experience. Just like requests, despite having the unittest built-in in the Python library, Pytest has proven to be an efficient and effective way of writing test cases.&lt;/p&gt;

&lt;p&gt;Stars — 7.37K&lt;/p&gt;

&lt;p&gt;Contributors- 518&lt;/p&gt;

&lt;p&gt;Stackoverflow Questions — 6401 Questions&lt;/p&gt;

&lt;h3&gt;
  
  
  SQLAlchemy
&lt;/h3&gt;

&lt;p&gt;SQLAlchemy is one of the richest python packages. Every time a Python developer thinks of databases, they will think of SQLAlchemy. People often think SQLAlchemy is all about ORMs for non-Django people, but that’s not the case. SQLAlchemy provides a developer complete control over how they want to play with DBs. Want to run raw queries? You got it. Want to use a complete object-driven approach? You got it. Got a DB already and want to build on top of it, reflect the DB into objects and proceed&lt;/p&gt;

&lt;p&gt;Stars — 3.82K&lt;/p&gt;

&lt;p&gt;Contributors- 356&lt;/p&gt;

&lt;p&gt;StackOverflow Questions — 18,595 Questions&lt;/p&gt;

&lt;p&gt;As a Python Developer, I never start a project without one of these libraries. All the libraries come with rich documentation, so what are you waiting for? Fire up your code editor, pip install, and start experimenting with their examples.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Evolve from a Python newbie to a software Engineer. Be the first to get more Resources, tutorials, blog posts, paid and free workshops — &lt;a href="https://mailchi.mp/e1cea5c7347f/thelearningdev"&gt;&lt;strong&gt;Subscribe&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://thelearning.dev/blog/5-famous-python-packages/"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>codenewbie</category>
      <category>python</category>
      <category>coding</category>
      <category>learningtocode</category>
    </item>
    <item>
      <title>How to get past the beginner stage in Python?</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Sat, 05 Jun 2021 04:28:25 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/how-to-get-past-the-beginner-stage-in-python-2o55</link>
      <guid>https://forem.com/bhavaniravi/how-to-get-past-the-beginner-stage-in-python-2o55</guid>
      <description>&lt;p&gt;So you learned python, picked one of the best tutorials online, and aced through it. You loved Python and decided it was the one. But you ended up feeling completely lost when you tried to do your own project. It feels as if you have learned nothing.&lt;/p&gt;

&lt;p&gt;You wonder if those hours you have spent on learning the language is utter waste, that you missed something. You are urged to start from the beginning again in hopes of finding something new, only to end up with the same old variables, data structures, and loops.&lt;/p&gt;

&lt;p&gt;You switch to other online resources, books that teach Python, but the result are the same. The next resort is to look for advanced python concepts and receive pointers like&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Start building your own projects&lt;/li&gt;
&lt;li&gt;Learn advanced concepts&lt;/li&gt;
&lt;li&gt;Solve Leetcode problems&lt;/li&gt;
&lt;li&gt;Keep experimenting&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By this time, either it feels too humongous of a steep climb, or you have concluded programming not something that’s meant for you.&lt;/p&gt;

&lt;p&gt;I would have suggested the same 3 months back. Infact I would have even nudged you to attend my &lt;a href="https://gum.co/LaFSj"&gt;Bootcamp&lt;/a&gt;. As I was teaching the last batch, something came out. It’s not the technology, programming construct, or what I taught that made the difference. What made the difference was the ability to split the problem into smaller solvable chunks. It is this ability that gave my students to tackle any projects that they wanted to build. You would be using this skill years into the industry as a Software Engineer.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;As soon as I started to program in chunks, I realized how everything pieced together.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So how to do it? Given a problem, how do you dissect them into smaller solvable chunks? Like how the construction of a building starts with a basement followed by layers of other constructional elements, your program starts with a base structure and layers of logic plugged into it. The skill is not rocket science but comes with a little bit of practice. Your practice can be as simple as solving a single problem in a single Python script.&lt;/p&gt;

&lt;h3&gt;
  
  
  Program Construction
&lt;/h3&gt;

&lt;p&gt;Let’s start with an example, &lt;strong&gt;A calculator program that does the basic mathematical operation.&lt;/strong&gt; Your first intuition might be to start searching “How would you write a calculator app in Python?” instead, hold your horses. The goal is not to find the answer but to train your brain to solve the problem by yourself.&lt;/p&gt;

&lt;p&gt;Now take down a piece of paper or open a notepad and answer these questions? It might not come naturally the first few times and that’s completely fine. But before moving on write down the answers.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What are the core functionalities of the script?&lt;/li&gt;
&lt;li&gt;What inputs do I need to achieve it?&lt;/li&gt;
&lt;li&gt;How do I get the user input?&lt;/li&gt;
&lt;li&gt;What data do I need to achieve it?&lt;/li&gt;
&lt;li&gt;Do I need to store anything? If so, how? — Files, DB, cloud storage&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is a tip to ace it, have a conversation like talking to your friend. As the questions that are popping up and answer them. Spend about 10 minutes on it. Set the timer and start&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Done? Continue reading at&lt;/em&gt; &lt;a href="https://www.thelearning.dev/blog/python-next-steps/"&gt;&lt;em&gt;https://thelearning.dev&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>mindset</category>
      <category>codenewbie</category>
      <category>python</category>
    </item>
    <item>
      <title>Build a Python App with HarperDB</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Thu, 11 Feb 2021 14:35:59 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/build-a-python-app-with-harperdb-2egp</link>
      <guid>https://forem.com/bhavaniravi/build-a-python-app-with-harperdb-2egp</guid>
      <description>&lt;p&gt;With the boom of SaaS, people want to spend more time solving business problems rather than spend their time dealing with technical problems like managing a database.&lt;/p&gt;

&lt;p&gt;DBaaS (Database as a service) entered the SaaS ecosystem to solve just that. While you are busy solving business problems, services like &lt;a href="https://harperdb.io?utm_source=Bhavaniblog"&gt;HarperDB&lt;/a&gt; will take care of managing, scaling, replicating, and optimizing your databases.&lt;/p&gt;

&lt;p&gt;HarperDB is a cloud service that exposes your data via an API endpoint, making it language agnostic. It supports all major languages like Python, Java, NodeJS, etc.,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--faoJiDvy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/834/1%2AkihXqW6RHr8PcUqHFXUGyw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--faoJiDvy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/834/1%2AkihXqW6RHr8PcUqHFXUGyw.png" alt="" width="834" height="325"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  HarperDB — SQL vs NoSQL
&lt;/h3&gt;

&lt;p&gt;If you have worked with MySQL or Mongo, you will get the pros and cons of both. While relational systems provide concrete transactional and ACID properties, NoSQL DB works wonders for reading dominant use cases or streaming data.&lt;/p&gt;

&lt;p&gt;HarperDB wants to bring the best of both worlds to the database community by providing a system that.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Scales like a NoSQL system&lt;/li&gt;
&lt;li&gt;Is ACID Compliant&lt;/li&gt;
&lt;li&gt;Cost and Computing efficient&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Python App with HarperDB
&lt;/h3&gt;

&lt;p&gt;Now that we have understood what HarperDB brings to the table let’s build an application using Python while parallelly exploring the features provided by HarperDB.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;:: The rest of the blog assumes that you have a fair understanding of Python and Flask. For an in-depth tutorial on API, schema, and application design, check out&lt;/em&gt;&lt;a href="https://medium.com/bhavaniravi/build-your-1st-python-web-app-with-flask-b039d11f101c"&gt;&lt;em&gt;my flask starter tutorial&lt;/em&gt;&lt;/a&gt; &lt;em&gt;and come back here.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you are a “&lt;em&gt;show me the code”&lt;/em&gt; kind of person, &lt;a href="https://github.com/bhavaniravi/python-harperdb-app-tutorial"&gt;check out the Github repository&lt;/a&gt;, or if you want to follow along, here is the summary of steps we will perform.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Setup HarperDB instance&lt;/li&gt;
&lt;li&gt;Create a Schema and Database&lt;/li&gt;
&lt;li&gt;Create a Python Project&lt;/li&gt;
&lt;li&gt;Accessing HarperDB via python-SDK&lt;/li&gt;
&lt;li&gt;Creating and exposing the REST APIs&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Setup HarperDB Instance
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Create your HarperDB account
&lt;/h4&gt;

&lt;p&gt;The signup process is super smooth. All you have to do is go to the &lt;a href="https://studio.harperdb.io/sign-up?utm_source=Bhavaniblog"&gt;HarperDB signup page&lt;/a&gt; and fill in your details.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6bDJPvEr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/790/0%2AsjNLVFwxV4SPJ7yv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6bDJPvEr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/790/0%2AsjNLVFwxV4SPJ7yv.png" alt="" width="790" height="460"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Create a new DB instance
&lt;/h4&gt;

&lt;p&gt;Once you are inside the account, you can create the DB instance. Harper’s free tier provides 1 GB of free storage and 0.5 GB of RAM.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--a4YebPML--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ADPLhDuNljWhqTAgh.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--a4YebPML--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ADPLhDuNljWhqTAgh.jpg" alt="" width="880" height="457"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on create a DB instance. You will have two options.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create an HarperDB cloud instance that is created, managed, and scaled by HarperDB itself.&lt;/li&gt;
&lt;li&gt;Install HarperDB in your own server and add it to the UI.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DlmJ7lKI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/809/0%2A52gXuz1Ur4MvmvVA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DlmJ7lKI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/809/0%2A52gXuz1Ur4MvmvVA.png" alt="" width="809" height="396"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For this blog, I am going to stick with the cloud instance. Give your DB instance a name, select the tier, username, password, and click on create. Make a note of the username and password. It will come in handy when we connect to this DB from our python app.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iKn3OnT_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/499/0%2AEVS-HScQVQTn1R0F.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iKn3OnT_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/499/0%2AEVS-HScQVQTn1R0F.png" alt="" width="499" height="458"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The instance will take a few minutes to spin up. Once it is ready, we can create tables as per the needs of our application.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Application
&lt;/h3&gt;

&lt;p&gt;We all want to read books. I truly believe that the habit of reading books is essential for upgrading your thoughts. Now, if that motivated you enough, you would jump the bandwagon and start reading 100 books, but that’s not essential. Reading books is all about quality than quantity.&lt;/p&gt;

&lt;p&gt;Let’s build a Book Journal app where we&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Track the book we are reading, Add a Book Name, Start Date, End Date, URL, Author and Why are you reading this book&lt;/li&gt;
&lt;li&gt;Add our notes, thoughts, and highlights.&lt;/li&gt;
&lt;li&gt;Export notes for summary/blogs&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Create schema and tables
&lt;/h3&gt;

&lt;p&gt;Let’s start building the application by creating the necessary schema and tables. Click on the created DB instance, create a schema and table.&lt;/p&gt;

&lt;p&gt;Besides the table name, HarperDB also asks to enter or assign the field for a hash_attribute. This attribute is similar to a Primary Key in a relational database, used as the unique identifier(inserted_hashes) for each record. A good name for hash attribute would be just id or something more meaningful to the table book_id&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9epz0dAT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/500/0%2AU56O7oBkh6FEBnLb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9epz0dAT--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/500/0%2AU56O7oBkh6FEBnLb.png" alt="" width="500" height="315"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The created table will have basic fields like the hash_attribute, created, and updated time. HarperDB will automatically add additional fields when we insert data later.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jVAa9gfg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ATkcRB-gRSBCSK4kF.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jVAa9gfg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ATkcRB-gRSBCSK4kF.png" alt="" width="880" height="370"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating Python Application
&lt;/h3&gt;

&lt;p&gt;For the python app, we are going to use a flask app with &lt;em&gt;harperdb-python-SDK&lt;/em&gt;. Start by cloning the sample repo and checking out the tutorial branch.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone [git@github.com](mailto:git@github.com):bhavaniravi/python-harperdb-app-tutorial.git
git checkout tutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The packages required for this app are in requirements.txt Let’s install them using the pippython package manager.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Accessing DB using Harper Python SDK
&lt;/h3&gt;

&lt;p&gt;HarperDB provides Python, Java, Node, Rust SDKs. These SDKs make the CRUD apps as easy as calling a function. Once we have this logic in place, it is just a matter of exposing them via our APIs.&lt;/p&gt;

&lt;p&gt;Get the DB_URL from the HarperDB cloud username and password we noted earlier and add them to the file. To create a .env file, rename the file from the repo, and update the following fields.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_URL=""
DB_USER=""
DB_PASSWORD=""
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s Connect to the HarperDB instance using the above credentials. In a typical MVC pattern, all the DB related logic goes into the models file. Open models.py add the following code.&lt;br&gt;
&lt;/p&gt;

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

from dotenv import load_dotenv
load_dotenv() # loads the .env file 

schema = f"book_repo"

db = harperdb.HarperDB(
    url=os.environ["DB_URL"],
    username=os.environ["DB_USER"],
    password=os.environ["DB_PASSWORD"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the model file using python app/model.py. We have connected to HarperDB successfully if there are no errors. We will use the above dbobject to create, delete and update DB records.&lt;/p&gt;

&lt;h3&gt;
  
  
  HarperDB Python SDK — A sneak peek
&lt;/h3&gt;

&lt;p&gt;The HarperDB Python SDK includes Python3 implementations of HarperDB API functions and wrappers for an object-oriented interface. &lt;a href="https://github.com/HarperDB/harperdb-sdk-python"&gt;Here is the GitHub repo&lt;/a&gt;. We will be using the following in our book application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ayKXTz9X--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/909/0%2AsqEjYvNt3l6Et9to.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ayKXTz9X--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/909/0%2AsqEjYvNt3l6Et9to.png" alt="" width="880" height="273"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Using the SDK methods, we can write our own models.py file, which creates, updates, deletes the books from the table&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class BookModel:
    table = "books"
    def create(self, book_list):
        return db.insert(schema, self.table, book_list)

    def update(self, book_list):
        return db.update(schema, self.table, book_list)

    def delete(self, id):
        return db.delete(schema, self.table, [id])

    def get(self, id):
        return db.search_by_hash(schema, self.table, [id], get_attributes=['*'])

    def get_all(self):
        return db.sql(f"select * from {schema}.{self.table}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have added a &lt;a href="https://github.com/bhavaniravi/python-harperdb-app-tutorial/blob/main/app/service.py"&gt;BookService&lt;/a&gt; class in service.pya module that ingests business logic. TheBookService acts the controller of our MVC comes in handy to use adding notes to a specific book. It packages the request JSON and uses the &lt;strong&gt;update&lt;/strong&gt; method internally.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from models import BookModel

class BookService:
    def __init__ (self):
        self.model = BookModel()

    def create(self, params):
        return self.model.create(params)

    def update(self, item_id, params):
        if isinstance(params, dict):
            params = [params]

        for param in params:
            param["id"] = item_id

        return self.model.update(params)

    def delete(self, item_id):
        return self.model.delete(item_id)

    def get_all(self):
        response = self.model.get_all()
        return response

    def get(self, book_id):
        response = self.model.get(book_id)
        return response

    def add_notes(self, item_id, notes):
        if isinstance(notes, dict):
            notes = [notes]
        return self.update(item_id, {"notes":notes})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Exposing and consuming APIs
&lt;/h3&gt;

&lt;p&gt;Let’s create a flask app, and that uses BookService and expose our book CRUD API. If you are new to Flask, do switch to the &lt;a href="https://medium.com/bhavaniravi/build-your-1st-python-web-app-with-flask-b039d11f101c"&gt;flask beginner tutorial&lt;/a&gt;. Here is a little flask primer for you to get going forward.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# hello.py
from flask import Flask # import flask
app = Flask( __name__ ) # create an app instance

@app.route("/") # at the end point /
def hello(): # call method hello
    return "Hello World!" # which returns "hello world"

if __name__ == " __main__": # on running python app.py
    app.run(debug=True, port=5000) # run the flask app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the above code to app/hello.py and run python app/hello.py it will start a flask app. Open localhost:5000 in your browser, and you will see your hello world flask app.&lt;/p&gt;

&lt;p&gt;The cloned version of our book app’sapp/app.py the file looks like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, request, jsonify
from dotenv import load_dotenv
load_dotenv(verbose=True)

# import BookService Here

app = Flask( __name__ )

_# Add the Flask routes here_ 

if __name__ == " __main__":
    app.run(debug=True, host='0.0.0.0', port=8888)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For us to integrate the API endpoints with the BookService we need to import it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# import BookService Here
**from service import BookService**
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, let’s add the independent flask routes to create, update, delete and add notes to the books app.&lt;/p&gt;

&lt;h4&gt;
  
  
  Create Book
&lt;/h4&gt;

&lt;p&gt;For the create API, we will route /booksrequests via the HTTP POST method. It calls the BookService we created earlier to call our DB via HarperDB SDK, which creates and returns unique IDs. The response from HarperDB is converted into a JSON string using the Flaskjsonify method and returned as an HTTP response.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app.py

@app.route("/book", methods=["POST"])
def create_book():
    return jsonify(BookService().create(request.get_json()))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start the application by running python app/app.py&lt;/p&gt;

&lt;p&gt;To test our API, I have used the &lt;a href="https://insomnia.rest/"&gt;insomnia application&lt;/a&gt;and configured the APIs. You can also configure using the &lt;a href="https://github.com/bhavaniravi/python-harperdb-app-tutorial/blob/main/insomnia-api-consumer.json"&gt;insomnia-api-consumer.json&lt;/a&gt; file from the repo. Download and install insomnia. To import the API consumer, click on the drop-down at the left corner and click on Import/Export&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dZbETTad--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AIGH1BclMtTQEMWrrcqQDYQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dZbETTad--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AIGH1BclMtTQEMWrrcqQDYQ.png" alt="" width="880" height="337"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on import data -&amp;gt; From file and choose the &lt;a href="https://github.com/bhavaniravi/python-harperdb-app-tutorial/blob/main/insomnia-api-consumer.json"&gt;insomnia-api-consumer.json&lt;/a&gt; from the file picker.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--quJ6oP-c--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Aj6uzW8-6fMz2xireUSVbpQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--quJ6oP-c--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Aj6uzW8-6fMz2xireUSVbpQ.png" alt="" width="880" height="474"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You will have all the book APIs configured once the insomnia file is uploaded. Select the create_bookfrom left nav bar and click on the send button. You will see the API response on the right.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note down one of the book IDs. We will use it when testing the other APIs.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sjoauMIk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AEQ3M1WIvmkYhSTQB.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sjoauMIk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AEQ3M1WIvmkYhSTQB.png" alt="" width="880" height="362"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Similarly, we can create the rest of the APIs and test them using the insomnia app.&lt;/p&gt;

&lt;h4&gt;
  
  
  Update Book
&lt;/h4&gt;

&lt;p&gt;For the update API, we will route /booksrequests via the HTTP PUT method along with a . The acts as a template to receive book IDs generated by create API.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: The rest of the APIs calls the respective&lt;/em&gt;&lt;em&gt;BookService method.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app.py

@app.route("/book/&amp;lt;book_id&amp;gt;", methods=["PUT"])
def update_book(book_id):
    return jsonify(BookService().update(book_id, request.get_json()))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When testing the update API on insomnia, select update_bookand ensure that you replace the existing ID with the one you noted down from create API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Mcg2cwSG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AHAKck8i5px9ZNlwTck8shw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Mcg2cwSG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AHAKck8i5px9ZNlwTck8shw.png" alt="" width="880" height="238"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Get book details
&lt;/h4&gt;

&lt;p&gt;To get a book detail, we will route /books/requests via the HTTP GET method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app.py

@app.route("/book/&amp;lt;book_id&amp;gt;", methods=["GET"])
def get_book(book_id):
    return jsonify(BookService().get(book_id))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mfsGCUlY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AS7ygH5TYz8DCrxQJ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mfsGCUlY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AS7ygH5TYz8DCrxQJ.png" alt="" width="880" height="303"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Add notes
&lt;/h4&gt;

&lt;p&gt;To add notes to the API, we pass the book ID to /note POST API. Internally the service method calls the book update and adds the note to the respective book.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app.py

@app.route("/book/&amp;lt;book_id&amp;gt;/note", methods=["POST"])
def add_notes(book_id):
    return jsonify(BookService().add_notes(book_id, request.get_json()))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ayTkAzhH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AVojV_PaFygNwshC-.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ayTkAzhH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AVojV_PaFygNwshC-.png" alt="" width="880" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Though notes are stored as a param of books, we give it a logical separation using a different API. As an exercise, try adding notes via the update API we created before.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Once you have used these APIs to add, update and remove books, you can check these records in the HarperDB studio interface.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UrlOmRgL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Anf9vHjx_KjBye2LcSb6IsA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UrlOmRgL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Anf9vHjx_KjBye2LcSb6IsA.png" alt="" width="880" height="351"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;_Voila!!! W_e have successfully built the backend of our &lt;strong&gt;Book Journal app.&lt;/strong&gt; With a Database as a service like HarperDB, you can achieve a lot by writing as little code as possible. Got an idea? Focus on working on the solution, leave the rest to the experts.&lt;/p&gt;

&lt;h3&gt;
  
  
  Further Reading
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Security in HarperDB — &lt;a href="https://harperdb.io/developers/documentation/security/"&gt;https://harperdb.io/developers/documentation/security/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;SQL vs. NoSQL — &lt;a href="https://harperdb.io/developers/documentation/sql-overview/sql-features-matrix/"&gt;https://harperdb.io/developers/documentation/sql-overview/sql-features-matrix/&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>flask</category>
      <category>apps</category>
      <category>python</category>
      <category>harperdb</category>
    </item>
    <item>
      <title>Coding vs Coffee</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Sun, 18 Oct 2020 14:00:00 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/coding-vs-coffee-2ham</link>
      <guid>https://forem.com/bhavaniravi/coding-vs-coffee-2ham</guid>
      <description>&lt;p&gt;I have forever been a lover of coffee. When I say forever, it’s right from when I was 2, to be precise. Yes, I do remember my first smell of coffee. Unfortunately, neither I nor my mom are the best coffee makers in the world. Not that it’s terrible or anything, but it’s not the best I have drunk.&lt;/p&gt;

&lt;p&gt;Now let’s come to the act of drinking coffee itself. I am not an addict, I drink 2 cups of coffee a day, and that’s about it. Occasionally, rarely 4. Coffee lovers always have this pride that no one can love coffee as they do. I had that, too, for a brief period. Maybe I didn’t transform into an adult completely.&lt;/p&gt;

&lt;p&gt;For you to fight over your love for coffee, you have to be in the presence of good coffee. If not, everyone would just call out “coffee is bad” and mind their own business. In the presence of good coffee, love comes to life. Your eyes close as you sip through that hot gold savoring it every bit. Let me stop right there before I convert this into another poetry about coffee.&lt;/p&gt;

&lt;p&gt;Fortunately or unfortunately, good coffee was beyond my reach until I was 23. As I said, the coffee lovers started rising, and we all started sharing how much we love coffee. It was a celebration every time we have coffee together. There is black, dark, light, cold, whatnot—the varieties, the colors, the experiences.&lt;/p&gt;

&lt;p&gt;As a coffee lover, It would be unfair to compare my love for coffee with my fellow mates. To imagine that their love is better to mine. Just because an expresso shot doesn’t excite me doesn’t mean I am a bad coffee lover. My inability to take a sip of black coffee can’t question my love for coffee, Right?&lt;/p&gt;

&lt;p&gt;Similarly, if you love technology, it doesn’t matter how much other people love it, what tool they are using, how fast they can gulp a concept down. You all have your own taste and your own pace.&lt;/p&gt;

&lt;p&gt;No technology is better than the other. It’s all essential, it’s all necessary.&lt;/p&gt;

&lt;p&gt;As a technologist, let’s come together and share our love for technology just like we did for coffee: the varieties, the colors, the experiences, the good and the bad.&lt;/p&gt;

&lt;p&gt;Let’s share what we learned. Let’s spread knowledge.&lt;/p&gt;

</description>
      <category>coding</category>
      <category>coffee</category>
    </item>
    <item>
      <title>Machine Learning Resources with Projects</title>
      <dc:creator>Bhavani Ravi</dc:creator>
      <pubDate>Sun, 18 Oct 2020 00:00:00 +0000</pubDate>
      <link>https://forem.com/bhavaniravi/machine-learning-resources-with-projects-1h8f</link>
      <guid>https://forem.com/bhavaniravi/machine-learning-resources-with-projects-1h8f</guid>
      <description>&lt;p&gt;With the boom of machine learning and Artificial intelligence, One of the questions I get frequently asked is&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;How to get started with machine learning? &lt;/li&gt;
&lt;li&gt;What books do you suggest? &lt;/li&gt;
&lt;li&gt;Do you suggest any courses? etc.,&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But the most common question is there are so many resources which one to follow. Worry not! I have curated resources that worked for so many people. The resources come with some projects for you to try out the concepts you learn.&lt;/p&gt;

&lt;p&gt;Now you may get carried away by all the links and books here. Machine learning has a learning curve and usually takes six months of constant effort. Do not give up because you do not understand anything in the first few weeks. One can become a master only by continuous practice.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The resources focused on applied ML and not the core of machine learning. This is a starting point. Once you can build a few models, you can dig deeper to understand how they work.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://machinelearningmastery.com/start-here/"&gt;Machine Learning Mastery&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Machine Learning mastery has an extensive set of roadmaps and blog posts that can guide you through the journey of transforming yourself into an ML Engineer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://amzn.to/37hyb0C"&gt;Hands-on Machine Learning with sklearn, Keras and tensorflow2&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I cannot thank this book enough because it takes you through every step of building an ML pipeline. With each chapter, you get a little closer to becoming an ML Engineer. By the time you finish the book, you will know how to tackle an ML problem.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://www.udemy.com/course/machinelearning/"&gt;Machine Learning A-Z course&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Similar to the above book, this course has helped me simplify my understanding of machine learning. Until then, I thought it was a huge technology that takes years to master. The course suggested few mental models on how to approach each ML problem, which came in handy later when solving intensive problems.&lt;/p&gt;

&lt;h2&gt;
  
  
  Projects
&lt;/h2&gt;

&lt;p&gt;Pretty much every exercise on Kaggle is a project worth building. While my focus is is mostly on text and NLP, you should focus on different kinds of problems like numerical, categorical, predictive, clustering, etc., The above resources should prepare you for the following projects.&lt;/p&gt;

&lt;h3&gt;
  
  
  Examples
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Twitter hate speech classifier&lt;/li&gt;
&lt;li&gt;Hot-dog not hot-dog&lt;/li&gt;
&lt;li&gt;Book/Movie recommendation system&lt;/li&gt;
&lt;li&gt;&lt;a href="https://hackernoon.com/top-5-machine-learning-projects-for-beginners-47b184e7837f"&gt;More projects&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  More Questions?
&lt;/h2&gt;

&lt;p&gt;Write to us &lt;a href="//twitter.com/thelearningdev"&gt;@thelearningdev&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
