<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pradhvan Bisht </title>
    <description>The latest articles on DEV Community by Pradhvan Bisht  (@pradhvan).</description>
    <link>https://dev.to/pradhvan</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%2F57002%2F0b6de5a0-002b-4eaf-93f7-1071b49cec0e.jpg</url>
      <title>DEV Community: Pradhvan Bisht </title>
      <link>https://dev.to/pradhvan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pradhvan"/>
    <language>en</language>
    <item>
      <title>Context Managers in Python</title>
      <dc:creator>Pradhvan Bisht </dc:creator>
      <pubDate>Sat, 20 Jul 2019 17:59:00 +0000</pubDate>
      <link>https://dev.to/pradhvan/context-managers-in-python-26ng</link>
      <guid>https://dev.to/pradhvan/context-managers-in-python-26ng</guid>
      <description>&lt;h1&gt;
  
  
  Context Managers in Python
&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;Context Managers&lt;/strong&gt; in Python helps the user to manage the resources efficiently in a program i.e opening or closing a resource or locking or unlocking a resource. Context Managers come handy when we have to manage resource before and after an event. &lt;/p&gt;

&lt;p&gt;The most common context manager that every python programmer uses very frequently for managing files is a &lt;em&gt;With as&lt;/em&gt; statement. &lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('MyContextManager.txt') as f:
    f.write('Using Context Manager is FUN !')
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above code snippet has mainly two advantage:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Helps to close resources automatically and effectively. This might be a small code block, so it might a bit obvious that the file was open and closed properly but what if when the scope of the function increases? This is why context managers really come into the picture. &lt;/li&gt;
&lt;li&gt;Makes the code readable and complex logic simple. The above code can also be written as: &lt;/li&gt;
&lt;/ul&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;file = open('MyContextManager.txt','W')
try:
    file.write('Not using a Context Manager.')
finally:
    file.close()    
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Here we manage the opening and closing of a file manually with a &lt;em&gt;try-finally&lt;/em&gt; statement.&lt;/p&gt;

&lt;p&gt;Python's standard library comes with a module, &lt;em&gt;contextlib&lt;/em&gt;. This contains utilities for working with context managers and the &lt;em&gt;with&lt;/em&gt; statement. &lt;/p&gt;

&lt;h4&gt;
  
  
  Writing Your Own Context Manager
&lt;/h4&gt;

&lt;p&gt;So why would someone want to write there own Context Managers? &lt;/p&gt;

&lt;p&gt;Because, Context Managers are the best at managing resources before and after an event. Thus you don't have to worry about the allocation/de-allocation or Locking/Unlocking or Opening/Closing.&lt;/p&gt;

&lt;p&gt;Also, they make the code simple and more readable.&lt;/p&gt;

&lt;p&gt;Writing your context manager can be done in two ways either create your own class or use the &lt;em&gt;Contextlib&lt;/em&gt; module to create a Context Manager decorator. &lt;/p&gt;

&lt;p&gt;Let's first look at how we can create a simple &lt;strong&gt;Context Manager class&lt;/strong&gt;. A Context Manager class consists of two main methods &lt;em&gt;enter&lt;/em&gt; and &lt;em&gt;exit&lt;/em&gt;. If you're familiar with testing you can compare these two methods with the setup and teardown.&lt;/p&gt;

&lt;p&gt;Just like in every class in Python, the &lt;em&gt;init&lt;/em&gt; method is optional. But in the case of Context Managers,we use &lt;em&gt;init&lt;/em&gt; only if we're using a &lt;em&gt;with as&lt;/em&gt; statement. &lt;em&gt;init&lt;/em&gt; has to be passed the name which you want to associate with as in the &lt;em&gt;with as&lt;/em&gt; statement.&lt;/p&gt;

&lt;p&gt;Now let's take a look at a simple Game of Thrones inspired ContextManager which creates a &lt;em&gt;dict&lt;/em&gt; of the house symbols.  &lt;/p&gt;

&lt;p&gt;&lt;br&gt;
```PythonJust like every classJust like every class in Python, the &lt;em&gt;init&lt;/em&gt; method is optional only if you're using a &lt;em&gt;with * statement. If you're using *with as&lt;/em&gt; statement it has to be passed the name which you want to associate with as in the &lt;em&gt;with as&lt;/em&gt; statement. in Python, the &lt;em&gt;init&lt;/em&gt; method is optional only if you're using a &lt;em&gt;with * statement. If you're using *with as&lt;/em&gt; statement it has to be passed the name which you want to associate with as in the &lt;em&gt;with as&lt;/em&gt; statement.&lt;br&gt;
class ThronesContextManager:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, HouseSymbol):&lt;br&gt;
        self.HouseSymbol = HouseSymbol&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __enter__(self):
    print("Enter: {}".format(self.HouseSymbol)")
    return self.HouseSymbol

def __exit__(self, *exc):
    print("Exit: {}".format(self.HouseSymbol))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;with ThronesContextManager({"House Stark": "Wolf"}) as HouseSymbol:&lt;br&gt;
    HouseSymbol["Targaryen"] = "Three Headed Dragon"&lt;/p&gt;

&lt;p&gt;"""&lt;br&gt;
---Output---&lt;br&gt;
Enter: {'House Stark': 'Wolf'}&lt;br&gt;
Exit: {'House Stark': 'Wolf', 'Targaryen': 'Three Headed Dragon'}&lt;br&gt;
"""&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;



* The init method takes in the dict associated with the *as* in the *with-as* statement. It creates an instance of the class and assigns it to the dict. Much similar to any normal Python Class.
* The *enter* method is called by the *with* and is passed the dict. It returns the value which is associated with the dict(HouseSymbol).
*  The *exit* takes in the exception(*exc) these are of mainly three types exc: exception, exc_type: exception type and exc_tb: exception_traceback. 
*  If for some reason you want the program to ignore the exception you can also return True to just ignore the exception.


Now taking a look at the above code example we can say that any Context Manager is one which as two methods an *enter* method and an *exit* method. 

Before moving forward to *contextmanager decorator* let's break down the code snippit we saw in the starting of the post and see how it works behind the hood. 

Since we know how context managers work it won't be difficult to the observer what's happening when we call *with as* statement while opening a file.




```Python
with open('MyContextManager.txt') as f:
    f.write('Using Context Manager is FUN !')
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;With&lt;/em&gt; calls the &lt;strong&gt;enter&lt;/strong&gt; method of the File class.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;enter&lt;/strong&gt; method opens the file and returns it.&lt;/li&gt;
&lt;li&gt;The opened file handle is passed to &lt;em&gt;f&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;We write to the file using &lt;em&gt;.write()&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;The with statement calls the &lt;strong&gt;exit&lt;/strong&gt; method.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;exit&lt;/strong&gt; checks for exceptions, if no exception is found it closes the file.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The easier way to write a context manager is by using the &lt;strong&gt;Contextlib&lt;/strong&gt; module and creating a &lt;strong&gt;context manager decorator&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The good thing about using the &lt;strong&gt;@contextmanager&lt;/strong&gt; is that it builds the enter and exit method for you so automatically.Thus we can transform a generator function into a contextmanager decorator.  &lt;/p&gt;

&lt;p&gt;Let's re-write the ThronesContextManager again but with a &lt;em&gt;@ThronesContextManager&lt;/em&gt;.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from contextlib import contextmanager

@contextmanager
def ThronesContextManager(data):
    print("Enter: {}".format(data))
    yield data 
    print("Exit: {}".format(data))

with ThronesContextManager({"House Stark": "Wolf"}) as HouseSymbol:
    HouseSymbol["Targaryen"] = "Three Headed Dragon"

"""
---Output---
Enter: {'House Stark': 'Wolf'}
Exit: {'House Stark': 'Wolf', 'Targaryen': 'Three Headed Dragon'}
"""
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h4&gt;
  
  
  PyRandom
&lt;/h4&gt;

&lt;p&gt;Here are some things interesting things I found about Contextmanagers. These were found when I was researching for this blog post thus I am adding this to the section &lt;em&gt;PyRandom&lt;/em&gt;. I would be constanly updating this section as I learn more about Contex Managers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Context Managers do not create a separate new scope in the program i.e variables defined inside the &lt;em&gt;withas&lt;/em&gt; block will be available after the block is executed.&lt;/li&gt;
&lt;/ul&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open('MyContextManager.txt') as f:
    # Variable defined inside the Context Manager
    VariableName = f.read()
print(VariableName)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;When using the multiple ContextManager in a &lt;em&gt;withas&lt;/em&gt; statement the flow of &lt;em&gt;enter&lt;/em&gt; and &lt;em&gt;exit&lt;/em&gt; statement becomes LIFO(Last In First Out) i.e the enter method that is called last will have it's exit method called first.&lt;/li&gt;
&lt;/ul&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import contextlib

@contextlib.contextmanager
def make_context(name):
    print ('entering:', name)
    yield name
    print ('exiting :', name)

with make_context('A') as A, make_context('B') as B, make_context('C') as C:
    print ('inside with statement:', A, B, C)

"""
---OUTPUT---
entering: A
entering: B
entering: C
inside with statement: A B C
exiting : C
exiting : B
exiting : A
"""
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h5&gt;
  
  
  What now ?
&lt;/h5&gt;

&lt;p&gt;Since we covered all the basic stuff on Context Managers, we can start digging deeper and learn to use Context Managers in a more real-life use case. So here are some things that I would like you to read more about it. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Learn how to handle exceptions in/with Context Managers.&lt;/li&gt;
&lt;li&gt;Try to find out real project use cases where using a Context Manager would be best suited. &lt;/li&gt;
&lt;li&gt;Find out the role of &lt;em&gt;init&lt;/em&gt; and &lt;em&gt;enter&lt;/em&gt; in the Context Manager.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Still can't get enough ?
&lt;/h5&gt;

&lt;p&gt;The reason behind the blog is that I recently picked a Python problem which goes something like this &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Write a Context Manager named Suppress which suppresses the exception of a given type/types i.e  if the given exception type is raised, that exception should be caught and muted in a sense.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Code Example:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; x = 0
&amp;gt;&amp;gt;&amp;gt; with suppress(ValueError):
...     x = int('hello')
...
&amp;gt;&amp;gt;&amp;gt; x
0
&amp;gt;&amp;gt;&amp;gt; with suppress(ValueError, TypeError):
...     x = int(None)
...
&amp;gt;&amp;gt;&amp;gt; x
0
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Since you read this far I am assuming you are also just starting to learn about this topic. Let's put to the put to the test what you have learned so far and get some hands-on experience of writing your Context Manager. Try to solve this problem.&lt;/p&gt;

&lt;p&gt;I am still solving the problem and once it's done I would link my solution here. &lt;/p&gt;

&lt;p&gt;Happy Coding 😄 &lt;/p&gt;

</description>
      <category>python</category>
      <category>contextmanagers</category>
      <category>decorators</category>
      <category>generators</category>
    </item>
    <item>
      <title>Memory Managment in Python – Part 2</title>
      <dc:creator>Pradhvan Bisht </dc:creator>
      <pubDate>Wed, 19 Dec 2018 12:28:42 +0000</pubDate>
      <link>https://dev.to/pradhvan/memory-managment-in-python--part-2-56dc</link>
      <guid>https://dev.to/pradhvan/memory-managment-in-python--part-2-56dc</guid>
      <description>&lt;p&gt;In the last part, we checked out how variables are stored in Python and how Python handles memory management with reference counts and garbage collector. If you haven't checked it out and want to here is the &lt;a href="https://dev.to/pradhvan/memory-managment-in-python--part-1-1c98"&gt;link&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;In this part, we will dig deep a little on how reference counting works and how it can increase or decrease taking in account the different cases. So let's start where we left off, every object in python has three things&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Type
Reference Count
Value  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Reference Count is a value showing how much an object has been referred(pointed) too by other names(variables). Reference counting helps the garbage collector in freeing up space so the program can run efficiently. Though we can increase or decrease the value of the reference count and can check the value with the inbuilt function called getrefcount().&lt;/p&gt;

&lt;p&gt;Let's take a small code snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

&lt;span class="c1"&gt;# Two reference one from the variable and one from the getrefcount() function
&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;

&lt;span class="mi"&gt;2&lt;/span&gt;

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



&lt;p&gt;Though the examples look great and everything seems to be working but I did kinda trick you, first thing is that not all reference count values start from 0 so if you do the same example with a different value of the output may be different. Reference count values are calculated on two factors number of times the object is used in the bytecode and the number of time it’s been referenced to this includes your previous programs too.&lt;/p&gt;

&lt;p&gt;Let’s look into another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight python"&gt;&lt;code&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;4&lt;/span&gt;

&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;5&lt;/span&gt;

&lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;6&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;When more variables reference to the same value the reference count increase. But this is not the case when we take into example the case of container objects like lists and constants.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="n"&gt;ex_list&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;8&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;9&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;10&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;11&lt;/span&gt;

&lt;span class="k"&gt;del&lt;/span&gt; &lt;span class="n"&gt;ex_list&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;7&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;8&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;9&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;10&lt;/span&gt;

&lt;span class="c1"&gt;# Same thing goes with constants
&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;12&lt;/span&gt;

&lt;span class="n"&gt;const&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;13&lt;/span&gt;

&lt;span class="n"&gt;const&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;const&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;12&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As we saw container objects here list refer to other objects referring to the value thus when we delete them the reference link is deleted thus objects inside the list decrease the reference count by one. The same happens with constants too, when the variable they get referenced to is incremented the reference count is decremented.&lt;/p&gt;

&lt;p&gt;By now you must have realized that del does not actually delete the object on the contrary it removes that variable(name) as a reference to that object and decrease the reference count by one.&lt;/p&gt;

&lt;p&gt;All the example we saw are kinda similar considering the fact that they are in the global namespace but what happens when there is function what happens to the reference count then, let’s find out through this code snippet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;sys&lt;/span&gt;

&lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;4&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ytf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="n"&gt;ytf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="mi"&gt;6&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;getrefcount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="mi"&gt;4&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We saw that when ytf() got into scope the reference count increased while the reference count decreased when the function got out of scope. Keeping this in mind that we should be careful of using large or complex objects in the global namespace because an object in a global namespace don’t go out of scope unless we decrease the value of the reference count thus a large object would consume more memory making the program less efficient.&lt;/p&gt;

&lt;p&gt;That’s all for this part, in the next part we would look closely into the garbage collector and how it functions inside a python program in freeing up memory.&lt;/p&gt;

</description>
      <category>python</category>
      <category>namespace</category>
      <category>variables</category>
      <category>functions</category>
    </item>
    <item>
      <title>Memory Managment in Python – Part 1</title>
      <dc:creator>Pradhvan Bisht </dc:creator>
      <pubDate>Sun, 16 Dec 2018 14:37:28 +0000</pubDate>
      <link>https://dev.to/pradhvan/memory-managment-in-python--part-1-1c98</link>
      <guid>https://dev.to/pradhvan/memory-managment-in-python--part-1-1c98</guid>
      <description>&lt;p&gt;Stumbling upon a Python code snippet from a GitHub &lt;a href="https://github.com/satwikkansal/wtfpython#-strings-can-be-tricky-sometimes-"&gt;repo&lt;/a&gt; I did come to realize that in Python variables don’t actually store values they are assigned too, variables actually store the location to the value. Unlike in C++/C which actually creates a space of a fixed size and assigns it to a variable created which we usually call a bucket/room while explaining variables to a beginner “what variables are?” in programming.&lt;/p&gt;

&lt;p&gt;Thought python variables are a bit different they work like keys which points to a particular room in the hotel(memory space) so whenever we make an assignment to available we are not creating rooms rather creating keys to that room which is freed/overwritten by the python’s garbage collector automatically. (More on the topic of garbage collector later). So the point is whenever we do something like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="mi"&gt;94268504788576&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="mi"&gt;94268504788576&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We are optimizing here and creating two same keys which points to the same room in the hotel (memory) thus they would have the same id but this kind of optimization works only with the range of integers from -5 to 256 if you exceed the range, variables would point to two different storages thus will have different id().&lt;/p&gt;

&lt;p&gt;Just don’t get confused why we did not use “==” instead used id(), == checks whether the value pointed by the variables are same or not inside the object and id() checks if it uses the same object or not because every object has a unique identity which can be checked by the id() function.&lt;/p&gt;

&lt;p&gt;Coming back to the code snippet from the GitHub repo given below and applying the same knowledge of integers to strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight python"&gt;&lt;code&gt;
&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"wtf"&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"wtf"&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;139942771029080&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;139942771029080&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"wtf!"&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"wtf!"&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;139942771029192&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;139942771029136&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"hello world this is a string"&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"hello world this is a string"&lt;/span&gt;

&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;139942770977328&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;139942770977408&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

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



&lt;p&gt;The same kind of optimization happens here too when the strings are small they refer to the same object in the memory rather creating a new one thus saving memory, this kind is called interning. But when the object becomes bigger or contains ASCII letters, digits or underscore they are not interned.&lt;/p&gt;

&lt;p&gt;This shows abstraction at it’s best and python is very good at it, it does all the heavy lifting job for you of allocating/deallocating memory for you and lets you focus on the other parts of the program. Until you really want to know what’s happening and I assume you do that’s why you are reading this blog 😛&lt;/p&gt;

&lt;p&gt;Though this explanation was already available on the repo. I wanted to know more about how memory management happens internally so I stumbled about a talk of “ &lt;a href="https://www.youtube.com/watch?v=URNdRl97q_0"&gt;Memory Managment in Python – The basics&lt;/a&gt;” by &lt;a href="https://www.nnja.io/"&gt;nnja&lt;/a&gt;. So yeah people with nicks like ninja are great with Python and Fortnite, hahaha! (I could not resist myself from posting this joke and just to clear things out ninja is one of the top Fortnite players)&lt;/p&gt;

&lt;p&gt;Thus if you see technically Python does not have variable but  ‘names’ which refers to other objects or names and Python likes to keep a count of all the references called as reference count of all the object’s references. So if the reference count of an object decreases to zero this means no reference is made to that object which as seen by the Garbage collector of python as free space thus the object is deleted and space is free to use.&lt;/p&gt;

&lt;p&gt;We as a programmer can increase or decrease the reference count of an object as a python object stores three things:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;* Type: int,string,float
* Reference Count
* Value
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Seeing the first code snippet of the blog where two names a and b in which both names points to the same object with the value 10 with the reference count of 1 and type as int.&lt;/p&gt;

&lt;p&gt;That’s all for this part, will cover the same topics in a bit detail in the next part. Still confused in some of the things so keeping this plain and simple for future me to look back when I am lost and can’t even notice the simple things 😛 and for someone who just wants to know this briefly.&lt;/p&gt;

</description>
      <category>python</category>
      <category>memorymanagment</category>
      <category>variables</category>
      <category>strings</category>
    </item>
  </channel>
</rss>
