<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pranay Gore on Medium]]></title>
        <description><![CDATA[Stories by Pranay Gore on Medium]]></description>
        <link>https://medium.com/@pranaygore?source=rss-5e207747432d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oY_hWoyJWDKbWPOLgRy9DQ@2x.jpeg</url>
            <title>Stories by Pranay Gore on Medium</title>
            <link>https://medium.com/@pranaygore?source=rss-5e207747432d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:59:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranaygore/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Quick on profiling Python code]]></title>
            <link>https://medium.com/@pranaygore/quick-on-profiling-python-code-fa10002534ff?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa10002534ff</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Thu, 14 May 2020 14:32:07 GMT</pubDate>
            <atom:updated>2020-05-14T14:32:07.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6mIY_jM1mq4vW1sY0D06w.jpeg" /></figure><p>I am sure you know what is profiling the code mean. If not, then <a href="https://en.wikipedia.org/wiki/Profiling_(computer_programming)">wiki</a> says <strong>profiling</strong> is a form of dynamic program analysis that measures the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls. Profiling information serves to aid program optimisation.</p><p>I personally use it to find the stats of a program, so that I know which part of my code needs attention or optimisation to increase the efficiency.</p><p>So when we want to find a bottleneck or the resources your code consumes, we look at 3 things- CPU, MEMORY and NETWORK.</p><p>Here, we will mainly focusing on cpu usage.</p><p>Let me start something with very basic, which I used to (I still do it) write as a speed test and I guess most of us do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*YS3MMSuueqh-Kvqi09aiRQ.png" /></figure><h3>CPU usage:</h3><p>It can be further divided into two parts-</p><h4>Macro-profiling:</h4><p>This profiles the whole program and stats are collected when executed. We have tools for this which is a part python standard library.</p><p><strong>cProfile</strong> (C implenentation) and <strong>profile</strong>(Python implementation)</p><p>Let us try some code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jjtWFHBC5XVh2mrKYwb4w.png" /></figure><p>We get the following output if use <strong>cProfile</strong></p><p><strong>(</strong>Syntax<strong>: <em>python3 -m cProfile testcode.py</em>)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHfmNxL_dlOz13r-mVS7ow.png" /></figure><p>and below if we use <strong>profile.</strong></p><p><strong>(</strong>Syntax<strong>:<em>python3 -m profile testcode.py</em></strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ze0FX_P5Uf6W71x8UwjWg.png" /></figure><p><strong>Note</strong>: These syntaxes works well with python 2.7 version too.</p><p>We can also read the stats in a Python program. We just need to import the profiler module which will profile the code and another module called <strong>pstats</strong> which will analyze the data collected by the Python profiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*q8SrwxhSgQ4bJ9LFbKhRmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osDdQ6wFc9DMzmiDJ89d2A.png" /></figure><p>We can also retrieve data specific to any function using pstats module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJfr_XJI8zFVRDqueJF_4A.png" /></figure><p>We can also visualise this profiled data into a dot graph. I tried visualising it using <strong>gprof2dot</strong> and <strong>qcachegrind</strong> but I faced issue with installation of these modules on Mac. If you are using linux, things should be fine with you guys.</p><p>I am using <strong>snakeviz</strong> for visualisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*-KYWdHXe18TqEHKEVnbVGA.png" /></figure><p>When we run snakeviz , a new browser window is launched with the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*ietLTzMXTJxFcOIv944OJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hw0Vgybn6d5vJeVKDjCdQg.png" /></figure><p>In the <strong>icicle</strong> visualization style,</p><ul><li>Functions are represented by rectangles. A root function is the top-most rectangle, with functions it calls below it, then the functions those call below them, and so on.</li><li>The amount of time spent inside a function is represented by the width of the rectangle. A rectangle that stretches across most of the visualization represents a function that is taking up most of the time of its calling function, while a skinny rectangle represents a function that is using hardly any time at all.</li></ul><p>From the above findings, we can say that:</p><ul><li>When the number of calls is really high and takes up most of the global time, the function or method is probably in a loop. Possible optimization may be done by moving this call to different scope in order to reduce number of operations.</li><li>When one function is taking very long time, a cache might be a good option, if possible.</li></ul><h4>Micro-profiling:</h4><p>This profiles a part of a program. When we are done with macro-profiling, we should try speed testing part of the programs.</p><p><strong>timeit</strong>: is used to test the execution time or compare small code snippets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tc4gi9zJAsHUh3LGphnsqA.png" /></figure><p><strong>LineProfiler: </strong>One of the profilers to profile single line of a code or functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*lO9sVk5a-1McI-Lc_KQ8Tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*87pvFgITVojXC0yKaDsWBA.png" /></figure><p>You can get the code used above @ <a href="https://github.com/gorepranay/object_oriented_programming_in_python/blob/master/profiling_in_python.ipynb">profiling_in_python.ipynb</a> . If you wish to profile memory and network too, you can take a look at some tools like-</p><p><strong>Memprof, Pympler </strong>and<strong> objgraph </strong>(for memory profiling)</p><p><strong>ntop </strong>and<strong> pathrate </strong>(for Network profiling)</p><p><strong>Note</strong>: To perform memory profiling, you should understand how memory is managed in Python first. You can refer to my <a href="https://medium.com/@pranaygore/memory-management-in-python-3ef7e90ee2bf?source=friends_link&amp;sk=98787e9487c8bef5f7536bd74e4b3659">article</a> for this.</p><p>Thanks for reading and enjoy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa10002534ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jupyter notebook: Interfacing AWS RDS engine & converting into Python object.]]></title>
            <link>https://medium.com/@pranaygore/jupyter-notebook-interfacing-aws-rds-engine-converting-into-python-object-279db1d57f7c?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/279db1d57f7c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 22:03:09 GMT</pubDate>
            <atom:updated>2020-04-24T22:03:09.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGguJEHnU-CLa178bcU1-g.jpeg" /></figure><p>Jupyter notebook (<a href="https://jupyter.org/">https://jupyter.org</a>) is developed and used for interactive computing across various programming languages. It supports over 40 different programming languages, integrated with wide variety of tools such as Apache Spark, TensorFlow, Python, R, Scala etc. These notebooks can be shared with others too.</p><p>I personally use it for prototyping in Python and interfacing SQL engines for ad hoc queries.</p><p>In this short article, I shall try to interface a couple of SQL engines like <strong>Sqlite, MySQL server </strong>and<strong> RDS from AWS</strong>. We will try running a query and then read it into a Python Dataframe object.</p><p>First, we need to install <em>ipython-sql</em>. This extension introduces a %sql (or %%sql) magic to your notebook allowing you to connect to a database using SQLAlchemy connect strings, then issue SQL commands.</p><p>Now, what are <strong>Magic commands</strong>?</p><p>Magics are specific to and provided by the IPython kernel. Magics must use a syntax element which is not valid in the underlying language(Python, in this case). ‘ <strong>%</strong> ‘ is not a valid unary operator(A unary operator has only one operand) in Python but can have meaning in some other language.<br> So Kernel uses this (<strong>%</strong>) syntax for Magics. For example,</p><p><strong>%alias -</strong>To name a customised cmd and use it as a shortcut(%alias alias_name cmd)</p><p><strong>%cd</strong> -To change the directory (%cd &lt;path&gt;)</p><p>I am using Anaconda distribution for Python. If you are using the same, run the below command on Linux/macOS terminal.</p><blockquote>conda install -c conda-forge ipython-sql</blockquote><p>You can also install it using pip.</p><blockquote>pip install ipython-sql</blockquote><p>Let us start with <strong>Sqlite</strong>. We do not need to install any client on our machine to connect the Sqlite database through Jupyter notebook. We will load the library (%load_ext sql) and connect to the database.</p><p>Let us launch the Jupyter notebook and get to work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6EAoQh4lnZmOQ6FWl3VjQ.png" /></figure><p>We will load the sql magic, connect to the database, create a table, insert some values and read them in Jupyter notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98W1vHdEpcCMePjVUfZEsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*cnGT7k4vJ9F8mPI3cfiTtQ.png" /></figure><p><strong>%sql sqlite:///&lt;path_of_the_database_file&gt;/newDB.db</strong></p><p>You can find the above code @ <a href="https://github.com/gorepranay/aws_codes/blob/master/interfacing_with_jupyter/interfacing_sqlite.ipynb">interfacing_sqlite.ipynb</a></p><p>Let us do the same for <strong>MySQL. </strong>We need a client to be installed on our machine and we need hostname, username, password &amp; database name as well.</p><p>To install the client for MySQL, run the command on your terminal.</p><blockquote>conda install -c bioconda mysqlclient <em>[ For Anaconda distribution ]</em></blockquote><blockquote><em>Or, </em>pip install mysqlclient</blockquote><p>Syntax for connection <strong>mysql://&lt;username&gt;:&lt;password&gt;@&lt;hostname&gt;/&lt;database_name&gt;</strong></p><p>Before connecting via notebook, I created a database(menagerie), table(pet) and have put some rows via terminal as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*Z70uBS_CJow5CHM3MjjC4g.png" /></figure><p>Now, lets connect the same mysql database through Jupyter and follow the same sequence as we did in Sqlite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*mJSZoUuYxeFoEBYwIp_yVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*16100NblbSRZ3Quxsy3_rA.png" /></figure><p>You can find the above code @ <a href="https://github.com/gorepranay/aws_codes/blob/master/interfacing_with_jupyter/interfacing_mysql.ipynb">interfacing_mysql.ipynb</a></p><p>Time for <strong>AWS RDS(Postgres). </strong>To connect to the database, we need a client similar to mysql. Go to the terminal and run,</p><blockquote>conda install -c anaconda psycopg2</blockquote><p>Go to the AWS management console -&gt; RDS -&gt; Create Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19TKTPACqOhEqOU7TnEVIg.png" /></figure><p>Once the database is created and is up to connect, make sure you go to the MODIFY option and make the database publicly available. Set the correct <strong>inbound rules</strong> in the security group( You can find it in the details of the database you created in AWS), so that only you can access the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYD_Su4sdkHl-c37ND86kw.png" /></figure><p>AWS will provide you the endpoint through which we can connect the database. <strong>NOTE</strong>: Make sure you mention database as ‘postgres’ in the below connection. I gave a different database name while creating it in AWS RDS, but it does not connect and throws an error saying: “ <em>Database does not exist</em>”.</p><p>Syntax to connect <strong>postgresql://&lt;username&gt;:&lt;password&gt;@&lt;endpoint_from_aws&gt;:5432/&lt;database_name&gt;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UaYLpM2Ccr-rJUjqN3kk4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLP5aHrzRWXTWlVkcd-LYw.png" /></figure><p>Code used above can be found @ <a href="https://github.com/gorepranay/aws_codes/blob/master/interfacing_with_jupyter/interfacing_rds_postgres.ipynb">interfacing_rds_postgres.ipynb</a></p><p>Hope this document helps you working on Python code and sql simulataneously to reduce the development and testing time. You can try interfacing other languages like R, Javascript etc and systems which interests you.</p><p>Enjoy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=279db1d57f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding AWS Glue]]></title>
            <link>https://medium.com/@pranaygore/understanding-aws-glue-a0cc30a59485?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0cc30a59485</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[etl-on-cloud]]></category>
            <category><![CDATA[aws-glue]]></category>
            <category><![CDATA[etl-on-aws]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 11:08:04 GMT</pubDate>
            <atom:updated>2020-04-13T16:20:12.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r26jGsgzEVVEaPGvSiwHVA.jpeg" /></figure><p>I presume that the readers of this article know what ETL is. As the short form suggests, it is <strong>Extract-Transform-Load</strong>.</p><p>We pull data from a system/storage , transform based on our business logic and store it in a much organised way which can be further used by downstream applications.</p><p>There have been numerous ETL tools in the market. Few of them are: <em>Informatica power center, Talend, Oracle data integrator , IBM datastage etc</em>. To use them we need to install these applications on a bunch of servers ( at enterprise level ). Many of them are available in cloud too. Let us talk about a similar service from AWS.</p><p><strong>AWS Glue</strong> is fully managed and pay-as-you go ETL service which runs on a scale-out Apache spark (<a href="https://spark.apache.org/">https://spark.apache.org</a>) environment.</p><p>This service can be used when we need to clean, organise and format data for storage in Data warehouse , Data lakes , Object store or make it available to other applications.</p><p>AWS Glue is also designed to work with semi-structured data using a component called <em>dynamic frame</em>(will soon discuss it in another article).</p><p><strong>Benefits</strong></p><ul><li>Since it is serverless, it handles the provisioning and scaling of the resources to execute the commands or queries on Apache Spark environment.</li><li>Glue has crawlers which identifies your data , suggest schemas and stores into a central catalog table. These crawlers also detect changes in the schemas(the way we schedule it).</li><li>Glue ETL engine automatically generates Python/Scala code and has a scheduler which is capable to handle dependencies too.Thus, we can build ETL pipelines using this.</li><li>With the support of Glue catalog, we can directly query S3 data using Athena and Redshift Spectrum. It is integrated with wide range of AWS services which helps us to build event-driven ETL pipelines.</li><li>API and AWS CLI support for all Glue operations.</li><li>Scales resources as needed to run your jobs. Retry tasks and handle errors automatically. Less hassle and cost effective.</li></ul><p><strong>Components involved</strong></p><ul><li>Crawlers: Crawler is mainly used to populate tables in Glue Catalog. Crawlers can be file-based or table-based. AWS Glue Console gives us option to select from <em>S3, DynaomoDB and JDBC connection. </em>JDBC will be used to access all the databases.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*SZD3lXaDzsGbYXsW3k9ymw.png" /></figure><ul><li>Classifier: Classifier checks if the given file is in pre-defined format or not. There are a couple of defined formats in Glue like: <em>CSV, JSON, XML, compressed formats, Apache logs etc</em>. We can also create or custom our own classifier.</li><li>Glue data catalog: As the name catalog suggests, this is the central repository of the metadata for our all data assets. It will store the table definition, location and many different attributes.</li><li>Job authoring: This generates the ETL code in Python and Scala. It is highly developer centric where a developer can edit, debug and share the code.</li><li>Job execution/Schedular: This is a schedular which handles dependency, monitoring and alerting of the jobs.</li></ul><p><strong>Working flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*7GzyllwIJbQdqJP_NDMzLQ.png" /><figcaption>Image from AWS</figcaption></figure><p>We start with pointing our crawlers to the datasource which is either in S3 , DynamoDB or Databases. We will take an example of a CSV file stored in a S3 bucket.</p><p>We name the crawler (‘crawl_test’ in this case) on the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7V04UvGZv4oRfbgPjD-gzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*b9SLgcyZ9MusKytfh_PoXw.png" /></figure><p>Once crawlers gets the source, it is time to set the IAM role. By default, AWS provides us a managed policy called <em>AWSGLueServiceRole</em> which is attached to the role(‘crawler_role’ in this case). This role has access to S3 object, Cloudwatch logs and Apache spark engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*RakfkraaQkkx-DZIavxLJA.png" /></figure><p>We select the schedule for the crawler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*3EFfTsTtriuXwXIb-PF8jg.png" /></figure><p>The information from the crawler and classifier goes into a databse table. We need to name the database(‘emea_catalog’ in this case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*CqEVNnshMQchSA9UjyQBMA.png" /></figure><p>Once this is done, a summary is provided by Glue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qFopUiYEF74xwL-ykly5Q.png" /></figure><p>Now, we are ready to design our ETL job and execute that.</p><p>We configure the job by providing the job name, engine. Glue provides us with script template and we can edit it too. Or we can place our own script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*ZhtnSidSUOkmoKknQ2-DaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBF1pbOh3s0JhBsMJTkFUQ.png" /><figcaption>Script editor in Glue</figcaption></figure><p>After editing or placing our code, we can run the job. In my code, I have just printed the result in the logs, to check if it is working as expected.</p><p>Code can be found at: <a href="https://github.com/gorepranay/aws_codes/tree/master/aws_glue">https://github.com/gorepranay/aws_codes/tree/master/aws_glue</a></p><p>This code is filtering out a couple of columns and it can be understood from the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ftxNo13XH_rv26kW1OsD0g.png" /><figcaption>Screenshot from cloudwatch log</figcaption></figure><p><strong>Limitations</strong></p><p>Challenges I practically see right now are:</p><ul><li>Glue cannot read or load data from any file storage other than S3. We need to stage the file to S3.</li><li>No direct support for real-time data processing. However, AWS is working on this feature and it will be out soon.</li><li>Transformation code needs to be in Python or Scala.</li><li>Debugging and testing is not possible.We need to execute the job and check the cloudwatch logs.</li></ul><p><strong>Pricing</strong></p><p>It differs by region.</p><ul><li>Crawlers: There is an hourly rate for the crawlers to discover the data. You are billed for every second and charged every hour. You are charged based on DPU(Data processing units). Each DPU consumes 4 vCPU and 16 GB memory. To save this charge ,you can populate table in Glue catalog manually.</li><li>Catalog: We can store upto a million of objects free. Object here refers to a table, database, version and other attributes. If more than a million, you will be charged with $1.00 / 100,000 objects.</li><li>Same pricing strategy goes for requests made to Glue catalog.</li><li>ETL Jobs: Wee have two kind of jobs in AWS Glue -Apache Spark and Python shell. By default, AWS Glue allocates 10 DPUs to each Apache Spark job. You are billed $0.44 per DPU-Hour. Allocation of 0.0625 DPU is provisioned to each Python shell job. You are billed $0.44 per DPU-Hour.</li></ul><p>For more information, you can visit: <a href="https://aws.amazon.com/glue/pricing/">https://aws.amazon.com/glue/pricing/</a></p><p>I have tried to keep the article crisp and short as there is already a lot of stuff available online. You all can try your own code.</p><p>Enjoy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0cc30a59485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[namedTuple (collections) in Python]]></title>
            <link>https://medium.com/@pranaygore/namedtuple-collections-in-python-60b0b574e1bb?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b0b574e1bb</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Sat, 23 Mar 2019 10:51:00 GMT</pubDate>
            <atom:updated>2019-03-23T10:51:00.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zSnX6kov191SMRm8Ef2Wg.jpeg" /></figure><p>A tuple is a lightweight object type where we can store sequence of python objects andthewse are immutable.</p><p>We cannot change value in a tuple like in List.</p><p><strong>tup=(23,45,54,’abc’.20.3)</strong></p><p><strong>print(type(tup)) </strong># It will return <strong>&lt;class ‘tuple’&gt;</strong></p><p>We use indexing to access items from a tuple object. For ex: <em>tup[0], tup[2] </em>will return 23 and 54 respectively.</p><p><strong>NamedTuples</strong> are simple containers of tuple for certain kind of tasks and have dictionary like structure. Like tuples, namedtuples are immutable too.</p><p>Lets see the syntax and couple of ways of accessing the items of namedTuple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cp88AlzK9JoNO2ax1MZraA.png" /></figure><p>Remembering index positions of the required key in a program can lead to errors, especially when they are long.</p><p>As per example above, namedtuple fields can be accessed by name using ( . ) notation and positional indexes.</p><p>We can also convert a namedtuple to a dictionary. Let’s see the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsVPE5BoXHvq3G-boAmfFQ.png" /></figure><p>There are also times when we accidentally use python reserved names ( ex: <em>class, in</em> .. ) and also when we try to access non-existent fields or supply duplicate field names. In such cases, we do get exceptions.</p><p>Let’ see an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS7xSkNbpZExgPAsNQ1aAw.png" /></figure><p>To mitigate this, we can pass an option as a parameter called ( r<strong>ename=True</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMMR_FBUCtw51a830fC9SQ.png" /></figure><p>Now, the questions is, which one to use- <strong>Tuple or NamedTuple</strong>?</p><p>Namedtuple makes your tuples self-sufficient and self-explanatory. We are not confined to use only indexes to access members.</p><p>Moreover, as namedtuple are lightweight objects and require no more memory than regular tuples. This makes them faster than dictionaries.</p><p>Hope, this article was helpful in understanding namedTuple object.</p><p>You can access the above code at: <a href="https://github.com/gorepranay/collections-in-python">collections-in-python</a>/namedtuple.ipynb</p><p>Thank you for reading.Cheers:-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b0b574e1bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[deque(collections) in Python]]></title>
            <link>https://medium.com/@pranaygore/deque-collections-in-python-8d9050297881?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d9050297881</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Sat, 23 Mar 2019 00:31:00 GMT</pubDate>
            <atom:updated>2019-03-23T00:31:00.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Kye5h2dxzvyTdrt9EoABw.jpeg" /></figure><p><strong>Deque</strong> is a double-ended abstract data type object which supports appending and poping items in an efficient way. It is a double ended queue.</p><p>We can look at it as a standard queue service. Most of the commands used for operations on list can be used with Deque too.</p><p>Items in deque can be populated and removed from both the ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72C2AYBVFF6WXH_XhyHrFA.png" /></figure><p>As mentioned earlier, items can be added from either side. Let’s see few examples how to do that. These examples are self explanatory on how the commands make changes to the deque object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulrDmzvIv-aWYi0JWjzj4Q.png" /></figure><p>Same way, items can also be poped out from either ends of the deque. Lets see some examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vicktjDqcFfG1J9hynZE_g.png" /></figure><p>There are operations that can be performed on deque. Let’s see them through an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyKKsnwZmN-tgyxxargoZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNxfTw66HbVhDDKajmWWQA.png" /></figure><p>I hope this article helps you understand this abstract type and the different types of operations to be performed over it.</p><p>You can find the code used here at:<a href="https://github.com/gorepranay/collections-in-python">collections-in-python</a>/deque.ipynb</p><p>Thanks for reading. Cheers:-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d9050297881" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counter (collections) in Python]]></title>
            <link>https://medium.com/@pranaygore/counter-collections-in-python-ac9d1024c497?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac9d1024c497</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 23:31:01 GMT</pubDate>
            <atom:updated>2019-03-21T23:31:01.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MWp_jlv9RSri6QmdbcgKbw.png" /></figure><p>A <strong>Counter</strong> is a subclass of dict. It is an unordered collection container in python which stores items keys and it’s count as values in a dictionary object.</p><p>It keeps the track of values if added multiple times. We can create an empty counter container by,</p><p><strong>c=Counter()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*F6xSfBHwVp2nOrj1eGCHpA.png" /></figure><p>There are different ways we can initialize Counter.</p><p><em>By sequence of items.</em></p><p><em>By keys and counts in a dictionary.</em></p><p><em>Using name:value mapping</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elRgS3clKGhrL5uprid1NQ.png" /></figure><p>We have many ways by which we can access counts from Counter object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxu3VIMrid7VQqIegFM_lA.png" /></figure><p>Counter does not raise any exception for unknown or non-existent key. If key is not present, ‘0’ is returned as it’s value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vs3sqymJKt-OzpMf-gMMA.png" /></figure><p><strong>Update()</strong> method is used to update the Counter object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMD0QxygLkCK8ZW1yxdeBQ.png" /></figure><p>There are few more methods used to get some insights from Counter object.</p><ol><li><strong>elements() </strong>: This method produces all of the items in the Counter sorted by the number of occurrences of the item.</li><li><strong>most_common() </strong>: Returns a sequence of the n most frequently encountered input values.</li></ol><p>We can use these functions as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQDuC4kq9l2oCh601OTQiw.png" /></figure><p>We can also perform couple of arithmetic and set operations on Counter object in Python. Some examples are as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFcgElLNqVhtJ9FC8prWXQ.png" /></figure><p>I hope you have learnt many things about Counter object and various operations on it.</p><p>Above shown code can be accessed from :<a href="https://github.com/gorepranay/collections-in-python">collections-in-python</a>/counter.ipynb</p><p>Thanks for reading. cheers :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac9d1024c497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory management in Python]]></title>
            <link>https://medium.com/@pranaygore/memory-management-in-python-3ef7e90ee2bf?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ef7e90ee2bf</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 23:31:03 GMT</pubDate>
            <atom:updated>2020-04-21T11:14:22.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*uHOLJ_56m6cL5O8S1NKRNQ.png" /></figure><p>Why do we need to know well about memory management of any programming language that we use to develop a system?</p><p>It helps you write an efficient code and solve lot of issues related to extra memory that your program pulls. We should also know the ways in which memory is allocated to store new objects, how chunks of memory are deallocated, when no longer needed, and the way the interpreter uses memory for it’s tasks.</p><p>Here, I am going to talk about memory management specifically in Python, many of it applies to other languages too.</p><p>Let us start from some basics. In order to use any data structure on a computer, we need to use memory on a computer system. Each memory has a sequence of <strong>words</strong> and each word can be of varying / fixed length.</p><p>Each memory word has a<strong> Memory address. </strong>Memory words are available from <strong>0 to n -1</strong>, where ’n’ is the number of words that can be fit into that computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*xIJgwPGI-6yjKCMogU152w.png" /></figure><p>Every process requires some memory and resources. Memory management in Python involves a private heap containing all Python objects and data structures. To run programs and store information, memory needs to be managed(to determine what and where-abouts of stored data).</p><p>The management of this private heap (like segmentation, preallocation or caching) is ensured internally by the <strong><em>Python memory manager</em></strong>.</p><p>How much memory is allocated ? Is all depends on <em>Python version, platform, environment settings</em>. Normally, we don’t have to look into it much. Management of the Python heap is performed by the interpreter itself and user has no control over it.</p><p>This memory is further divided into <em>HEAP</em> memory and <em>STACK</em> memory.</p><p><em>Methods</em> and <em>variables</em> are kept and executed from stack memory. By default, programs begins execution at main method stack. Consider the below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Q-pW5bR_-hSLj_2zL1hjTg.png" /></figure><p>Main method, functions, variables and their corresponding values of the code can be picturized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*aj7wuuq_KYMxOS4m2HNlfg.png" /></figure><p>Objects are created in heap memory. References (variables) are kept in the stack. Let us say,<strong> </strong>we have an <em>Employee</em> class and we create an object of it.</p><p><strong>e=Employee()</strong></p><p>When this is executed, new instance called ‘e’ is created and stored somewhere in the heap memory. Python interpreter is the one who negotiates for the space with OS and for managing the the use of memory heap while executing python program.</p><p>Python does memory optimisation by assigning same object containing same values to different variables.</p><p>Let’s take an example where I am assigning value of 100 to three different variables( <em>var1, var2 </em>and<em> var3</em> ). All point to same memory address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uOmBT5PiboMOYFc1pAa25A.png" /></figure><p>We can say Python is a dynamic language. There are three different types of objects.</p><ol><li><strong>Simple objects </strong>( Numbers, strings .. etc )</li><li><strong>Container objects</strong> ( Lists, Dictionaries ..etc )</li><li><strong>User defined custom classes</strong> ( <em>Employee</em> class.. )</li></ol><p><strong>Reference</strong> is a name or a container object which points to another object. <strong>Reference count</strong> is the number of references.</p><p>In the above example, three variables( <em>var1, var2 </em>and<em> var3 </em>) point to value 100, which means reference count is 3. If I add one more variable which equals to 100, reference count will increment by 1 ( <em>totalling to 4 </em>).</p><p>Similarly, if I remove a variable ( <strong>del var3 </strong>), it will decrement the reference count by 1. As it decreases and eventually becomes 0 , that object goes out of scope. Objects are immediately removed.</p><p><strong>Garbage Collection</strong>(GC) is a way for a program to automatically release memory when the object taking the space is no longer in use.</p><p>There are two ways “stale” objects memory is reclaimed — <em>Reference counting </em>and<em> Tracing.</em></p><p>In Reference counting, when ref count reaches 0, objects are immediately deleted. However, this method is not thread safe ( When we have multiple threads increasing and decreasing reference counts of the same object ). When there are <strong><em>Cyclical references</em></strong><em> </em>( Ex: doubly linked list ), reference counting GC cannot work.</p><p>Basically, in Cyclic references two objects reference each other. This type of reference can be extremely problematic if two functions or values depend on one another for definition. This is also one of the causes for Memory leaks, where memory no longer needed is not released and programs end up using more memory than required.</p><p>To counter and detect this problem, we have <em>tracing</em>. There are many algorithms for tracing but the classic one is <strong><em>Mark-Sweep algorithm</em></strong>.</p><p>In this algorithm, we associate a “mark” bit with each object that identifies whether that object is live. When we determine at some point that garbage collection is needed, we suspend all other activity and clear the mark bits of all the objects currently allocated in the memory heap.</p><p>We then trace through the active namespaces and mark all the objects reachable from the root objects. To do this, we can perform a <strong>depth-first search</strong>, where each object in the memory heap is viewed as a <em>vertex</em> in a directed graph, and the reference from one object to another is viewed as a <em>directed</em> <em>edge</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*sPzzsZ6DgqmubNEl13EnQg.png" /></figure><p>By performing a directed DFS from each root object, we can correctly identify and mark each live object. This process is known as the “mark” phase.</p><p>Once this process has completed, we then scan through the memory heap and reclaim any space that is being used for an object that has not been marked known as the “sweep” phase, and when it completes, we resume running the suspended program.</p><p>We can use <em>System library </em>from Python to get the reference count and size of the object, which can help you efficiently code and choose between different data-types and data-structures in terms of memory usage.</p><p><strong>getrefcount(&lt;object&gt;)</strong> and <strong>getsizeof(&lt;object&gt;)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YabPBHsQKupTRQubvcZw6A.png" /></figure><p>Optionally, you can use <em>gc</em> library too.</p><p><strong>import gc<br>gc.get_objects() # NOTE:</strong> This will get you all the objects</p><p><strong>NOTE</strong>: Since we reclaim memory space at a time when available memory is scarce, we must take care not to use extra space during the garbage collection itself. We should find a way to perform DFS in-place rather than recursively, that is, we must perform DFS using only a constant amount of additional storage.</p><p><strong>Additional memory used by Python interpreter</strong></p><ol><li><em>Run-time call stack </em>: A running Python program has a private stack, known as the <em>call stack </em>or <em>Python interpreter stack</em>, which keeps track of the nested sequence of currently active (non-terminated) invocations of functions. Each entry of the stack is a structure known as a <em>frame</em>, storing information about an invocation of a function. Each frame includes a dictionary representing the local namespace for the function call which includes identifiers, parameters and local variables, object values and they reside in the memory heap.</li><li><em>Operand stack</em>: Arithmetic expressions, such as ((<em>a </em>+ <em>b</em>) ∗ (<em>c </em>+ <em>d</em>))/<em>e</em>, are evaluated by the interpreter using an <em>operand stack</em>. Interpreter evaluates an arithmetic expression using a postorder traversal of an explicit expression tree. Similarly, instructions for writing and reading elements to and from memory involve the use of <em>pop</em> and <em>push</em> methods for the operand stack.</li></ol><p>Thank you very much reading.</p><p>You can find the code used as an example @ <a href="https://github.com/gorepranay/object_oriented_programming_in_python/blob/master/memory_management_in_python.ipynb">memory_management_in_python.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ef7e90ee2bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[defaultdict module ( collections ) in Python]]></title>
            <link>https://medium.com/@pranaygore/defaultdict-module-collections-in-python-40b77e7a5d1c?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b77e7a5d1c</guid>
            <category><![CDATA[dictionary]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 00:06:00 GMT</pubDate>
            <atom:updated>2019-03-20T22:28:58.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0m0Cr5Dsg-o0gsfClOLPkQ.jpeg" /></figure><h3><strong>defaultdict module (collections) in Python</strong></h3><p>A Python dictionary is a mapping of unique keys to values. Dictionary keys must be unique , immutable objects in dictionary . The values in a dictionary can be anything.</p><p>Also, values of dictionaries can be another objects like - list, dictionary, integer ..etc.</p><p>In normal dictionary, if try to access a key which is not present in the dictionary, we will get an error. In defaultdict, we give a default value initially to a key. Thus, <strong>DefaultDict</strong> is initialized with a function.</p><p>Method setdefault() can be used for retrieving a value and establishing a key if the value does not exist.</p><p>However, defaultdict() is faster than setdefault() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDXnCLJaXDRL0m-CqYcSrA.png" /></figure><p>To use defautdict, we have first create a default functions to pass as an parameter to it. In the below example, I have created two default functions (<em>defaultmethod </em>and<em> defaultval2</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rIXgzOPNt3RxHRonyJ0NA.png" /></figure><p>Similarly, we can also pass another python objects ( such as int, list, float ..etc ) as a paramter to defaultdict instead of a default function. defaultdict will take default values of these object types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GFAXET1ZKSrjhQJOFDzHQ.png" /></figure><p>Likewise, string object has default value as ‘’, List as [ ], dictionary as { }.</p><p>We can use any default factory to create default dictionary value type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeVNoeUfzQ7qnthDBjhpjg.png" /></figure><p>I hope, defaultdict module of Python collection is much more clear to you.</p><p>You can get the above used code at: <a href="https://github.com/gorepranay/collections-in-python">collections-in-python</a>/defaultdict.ipynb</p><p>Thanks for reading. Cheers :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b77e7a5d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OrderedDict module (collections) in Python]]></title>
            <link>https://medium.com/@pranaygore/ordereddict-module-collections-in-python-6a31a8a986dc?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a31a8a986dc</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 20:28:27 GMT</pubDate>
            <atom:updated>2019-03-19T20:28:27.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mMjbpInb9vdE3Y5ZFQ93w.jpeg" /></figure><p>OrderedDict is an important container type and is a dictionary subclass in Python.</p><p>Normal or an ordinary dictionary does not keep track of the order contents added but OrderedDict does.</p><p>While iterating over ordinary dictionary, it returns the keys based on how they are stored on hash table, whereas in OrderedDict iterator return the items in the order they were inserted.</p><p>Lets see an example-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yi9fHJ4C5MbnZSslPTfveg.png" /></figure><p>Also, while comparing two dictionaries, normal dictionary will only check for key and value match but not the order they were placed in the dictionary container.</p><p>However, in OrderedDict it checks the contents equality and order.</p><p>Below example shows two dictionaries(normal), where the contents are same but sequence is different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xayd-iE9njJgJY7cO95whw.png" /></figure><p>Now, if we perform the same example using OrderDict, they do not match and returns false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnPSBJSDJpxIGwODm4qQBg.png" /></figure><p>This is it.</p><p>I hope you guys have learned and understood OrderDict module which is an important part of Python collection.</p><p>You can find the above used code at: <a href="https://github.com/gorepranay/collections-in-python">collections-in-python</a>/OrderDict.ipynb</p><p>Thanks for reading. Cheers :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a31a8a986dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using getattr, setattr, delattr, hasattr in Python]]></title>
            <link>https://medium.com/@pranaygore/using-getattr-setattr-delattr-hasattr-in-python-6d79c6f9fda3?source=rss-5e207747432d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d79c6f9fda3</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[getter]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[setter]]></category>
            <dc:creator><![CDATA[Pranay Gore]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 18:46:57 GMT</pubDate>
            <atom:updated>2020-04-21T11:19:16.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmPmKT2dJTz8tknBZyY8uQ.jpeg" /></figure><p>The only use of Python <strong>getattr()</strong> function is to get the value of an object’s attribute and if no attribute of that object is found, default value is returned.</p><p>Basically, returning the default value is the main reason you you should use getattr() function. getattr() function accepts multiple parameters.</p><p>syntax : <strong>getattr(object, attribute_name [, default]) </strong>where,</p><p><em>object — object of the class whose attribute value is to be returned.</em></p><p><em>attribute_name — attribute’s name.</em></p><p><em>default (Optional) — value that is returned when the attribute is not found.</em></p><p>If attribute_name passed to getattr() is not found or available in the class, default value comes into picture.</p><p>This enables us to complete some of our incomplete data and finish the program execution without any errors. Let us see an example-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gNb80nkwr7gc1kFKplKsw.png" /></figure><p>Similarly, we have something to set the attribute values of an object, <strong>setattr().</strong></p><p>Syntax: <strong>setattr(object, name, value) </strong>where,</p><p><em>object — object whose attribute has to be set.</em></p><p><em>attribute_name — attribute name for which we need to set the value.</em></p><p><em>attribute_value — value of the attribute to be set.</em></p><p>Let us see an example-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cK-fonWj1wc0HLMa5bj1A.png" /></figure><p>You can also set an attribute and its value using setattr() function , even if it is not in the class currently, however it is object specific. In the below example, we are trying to set a new attribute for the object ‘<em>emp_name</em>’ from outside the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laYL5ANgqxaaHw2Hbnli4w.png" /></figure><p>There is a inbuilt function to check if the object has the atrribute present or not. It returns true if an object has the given attribute and false if it does not.</p><p>Syntax: <strong>hasattr(object, name) </strong>where,</p><p><em>object — object name of the class</em></p><p><em>name — attribute name to be checked.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32sZCjvzdVn_7numgA7R8w.png" /></figure><p>The <strong>delattr()</strong> deletes an attribute from the object (if allowed).</p><p>Syntax: <strong>delattr(class_name, name) </strong>where,</p><p><em>class_name — name of the class</em></p><p><em>name — attribute name to be deleted.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd07XxT8-aebMyoIr_kLng.png" /></figure><p>Hope this article explains the use of the getattr, setattr, hasattr, delattr well.</p><p>You can get the code used in the above example at: <a href="https://github.com/gorepranay/object_oriented_programming_in_python/blob/master/getattr_setattr_hasattr_delattr.ipynb">getattr_setattr_hasattr_delattr.ipynb</a></p><p>Thanks for reading, cheers :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d79c6f9fda3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>