<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Python &amp;mdash; sandeepk</title>
    <link>https://blogs.dgplug.org/sandeepk/tag:Python</link>
    <description></description>
    <pubDate>Sun, 19 Apr 2026 04:39:53 +0000</pubDate>
    <item>
      <title>Debugging maxlocksper_transaction: A Journey into Pytest Parallelism</title>
      <link>https://blogs.dgplug.org/sandeepk/debugging-max_locks_per_transaction-a-journey-into-pytest-parallelism</link>
      <description>&lt;![CDATA[So I was fixing some slow tests, and whenever I ran them through the pytest command, I was greeted with the dreaded maxlockspertransaction error.&#xA;&#xA;My first instinct? Just crank up the maxlockspertransaction from 64 to 1024.&#xA;&#xA;But... that didn’t feel right. I recreate my DB frequently, which means I’d have to set that value again and again. It felt like a hacky workaround rather than a proper solution.&#xA;&#xA;Then, like any developer, I started digging around — first checking the Confluence page for dev docs to see if anyone else had faced this issue. No luck. Then I moved to Slack, and that’s where I found this command someone had shared:&#xA;&#xA;pytest -n=0&#xA;&#xA;This was new to me. So, like any sane dev in 2025, I asked ChatGPT what this was about. That’s how I came across pytest-xdist.&#xA;&#xA;What is pytest-xdist?&#xA;&#xA;  The pytest-xdist plugin extends pytest with new test execution modes — the most common one is distributing tests across multiple CPUs to speed up test execution.&#xA;&#xA;What does pytest-xdist do?&#xA;&#xA;  Runs tests in parallel using numprocesses workers (Python processes), which is a game changer when:&#xA;  - You have a large test suite  &#xA;  - Each test takes a significant amount of time  &#xA;  - Your tests are independent (i.e., no shared global state)&#xA;&#xA;---&#xA;&#xA;That’s pretty much it — I plugged in pytest -n=0 and boom, no more transaction locks errors.  &#xA;&#xA;Cheers!&#xA;&#xA;References&#xA;https://pytest-xdist.readthedocs.io/en/stable/&#xA;https://docs.pytest.org/en/stable/reference/reference.html&#xA;&#xA;#pytest #Python #chatgpt #debugging&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>So I was fixing some slow tests, and whenever I ran them through the <code>pytest</code> command, I was greeted with the dreaded <code>max_locks_per_transaction</code> error.</p>

<p>My first instinct? Just crank up the <code>max_locks_per_transaction</code> from 64 to 1024.</p>

<p>But... that didn’t feel right. I recreate my DB frequently, which means I’d have to set that value again and again. It felt like a hacky workaround rather than a proper solution.</p>

<p>Then, like any developer, I started digging around — first checking the Confluence page for dev docs to see if anyone else had faced this issue. No luck. Then I moved to Slack, and that’s where I found this command someone had shared:</p>

<pre><code class="language-bash">pytest -n=0
</code></pre>

<p>This was new to me. So, like any sane dev in 2025, I asked ChatGPT what this was about. That’s how I came across <code>pytest-xdist</code>.</p>

<h2 id="what-is-pytest-xdist">What is <code>pytest-xdist</code>?</h2>

<blockquote><p>The <code>pytest-xdist</code> plugin extends pytest with new test execution modes — the most common one is distributing tests across multiple CPUs to <strong>speed up test execution</strong>.</p></blockquote>

<h2 id="what-does-pytest-xdist-do">What does <code>pytest-xdist</code> do?</h2>

<blockquote><p>Runs tests in <strong>parallel</strong> using <code>&lt;numprocesses&gt;</code> workers (Python processes), which is a game changer when:
– You have a large test suite<br>
– Each test takes a significant amount of time<br>
– Your tests are independent (i.e., no shared global state)</p></blockquote>

<hr>

<p>That’s pretty much it — I plugged in <code>pytest -n=0</code> and boom, no more transaction locks errors.</p>

<p>Cheers!</p>

<p>References
– <a href="https://pytest-xdist.readthedocs.io/en/stable/" rel="nofollow">https://pytest-xdist.readthedocs.io/en/stable/</a>
– <a href="https://docs.pytest.org/en/stable/reference/reference.html" rel="nofollow">https://docs.pytest.org/en/stable/reference/reference.html</a></p>

<p><a href="/sandeepk/tag:pytest" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">pytest</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a> <a href="/sandeepk/tag:chatgpt" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">chatgpt</span></a> <a href="/sandeepk/tag:debugging" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">debugging</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/debugging-max_locks_per_transaction-a-journey-into-pytest-parallelism</guid>
      <pubDate>Wed, 16 Jul 2025 17:07:59 +0000</pubDate>
    </item>
    <item>
      <title>Django: How to acquire a lock on the database rows? </title>
      <link>https://blogs.dgplug.org/sandeepk/django-how-to-acquire-a-lock-on-the-database-rows</link>
      <description>&lt;![CDATA[selectforupdate is the answer if you want to acquire a lock on the row. The lock is only released after the transaction is completed. This is similar to the Select for update statement in the SQL query.&#xA;&#xA;      Dealership.objects.selectforupdate().get(pk=&#39;iamid&#39;)&#xA;      # Here lock is only required on Dealership object&#xA;      Dealership.objects.selectrelated(&#39;oem&#39;).selectforupdate(of=(&#39;self&#39;,))&#xA;selectforupdate have these four arguments with these default value&#xA;nowait=False&#xA;skiplocked=False&#xA;of=()&#xA;nokey=False&#xA;&#xA;Let&#39;s see what these all arguments mean&#xA;&#xA;nowait&#xA;Think of the scenario where the lock is already acquired by another query, in this case, you want your query to wait or raise an error, This behavior can be controlled by nowait, If nowait=True we will raise the DatabaseError otherwise it will wait for the lock to be released.&#xA;skiplocked&#xA;As somewhat name implies, it helps to decide whether to consider a locked row in the evaluated query. If the skiplocked=true locked rows will not be considered.&#xA;&#xA;  nowait and skiplocked are mutually exclusive using both together will raise ValueError&#xA;&#xA;of&#xA;In selectforupdate when the query is evaluated, the lock is also acquired on the select related rows as in the query. If one doesn&#39;t wish the same, they can use of where they can specify fields to acquire a lock on&#xA;      Dealership.objects.selectrelated(&#39;oem&#39;).selectforupdate(of=(&#39;self&#39;,))&#xA;Just be sure we don&#39;t have any nullable relation with OEM&#xA;nokey&#xA;This helps you to create a weak lock. This means the other query can create new rows which refer to the locked rows (any reference relationship).&#xA;&#xA;Few more important points to keep in mind selectforupdate doesn&#39;t allow nullable relations, you have to explicitly exclude these nullable conditions. In auto-commit mode, selectforupdate fails with error TransactionManagementError you have to add code in a transaction explicitly. I have struggled around these points :).&#xA;&#xA;Here is all about selectforupdate which you require to know to use in your code and to do changes to your database.&#xA;&#xA;Cheers!&#xA;&#xA;Python&#xA;Django&#xA;ORM&#xA;Database&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p><code>select_for_update</code> is the answer if you want to acquire a lock on the row. The lock is only released after the transaction is completed. This is similar to the <code>Select for update statement</code> in the SQL query.</p>

<pre><code class="language-python">&gt;&gt;&gt; Dealership.objects.select_for_update().get(pk=&#39;iamid&#39;)
&gt;&gt;&gt; # Here lock is only required on Dealership object
&gt;&gt;&gt; Dealership.objects.select_related(&#39;oem&#39;).select_for_update(of=(&#39;self&#39;,))
</code></pre>

<p><code>select_for_update</code> have these four arguments with these default value
– nowait=False
– skip<em>locked=False
– of=()
– no</em>key=False</p>

<p>Let&#39;s see what these all arguments mean</p>

<h2 id="nowait">nowait</h2>

<p>Think of the scenario where the lock is already acquired by another query, in this case, you want your query to wait or raise an error, This behavior can be controlled by <code>nowait</code>, If <code>nowait=True</code> we will raise the <code>DatabaseError</code> otherwise it will wait for the lock to be released.</p>

<h2 id="skip-locked">skip_locked</h2>

<p>As somewhat name implies, it helps to decide whether to consider a locked row in the evaluated query. If the <code>skip_locked=true</code> locked rows will not be considered.</p>

<blockquote><p>nowait and skip_locked are mutually exclusive using both together will raise ValueError</p></blockquote>

<h2 id="of">of</h2>

<p>In <code>select_for_update</code> when the query is evaluated, the lock is also acquired on the select related rows as in the query. If one doesn&#39;t wish the same, they can use <code>of</code> where they can specify fields to acquire a lock on</p>

<pre><code class="language-python">&gt;&gt;&gt; Dealership.objects.select_related(&#39;oem&#39;).select_for_update(of=(&#39;self&#39;,))
# Just be sure we don&#39;t have any nullable relation with OEM
</code></pre>

<h2 id="no-key">no_key</h2>

<p>This helps you to create a weak lock. This means the other query can create new rows which refer to the locked rows (any reference relationship).</p>

<p>Few more important points to keep in mind <code>select_for_update</code> doesn&#39;t allow nullable relations, you have to explicitly exclude these nullable conditions. In auto-commit mode, <code>select_for_update</code> fails with error <code>TransactionManagementError</code> you have to add code in a transaction explicitly. I have struggled around these points :).</p>

<p>Here is all about <code>select_for_update</code> which you require to know to use in your code and to do changes to your database.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a>
<a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a>
<a href="/sandeepk/tag:ORM" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">ORM</span></a>
<a href="/sandeepk/tag:Database" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Database</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-how-to-acquire-a-lock-on-the-database-rows</guid>
      <pubDate>Sat, 14 May 2022 14:06:03 +0000</pubDate>
    </item>
    <item>
      <title>sh like infix syntax using Pipes(|) in Python</title>
      <link>https://blogs.dgplug.org/sandeepk/sh-like-infix-syntax-using-pipes-in-python</link>
      <description>&lt;![CDATA[Today, we are going to see how we can use | operator in our python code to achieve clean code. &#xA;&#xA;Here is the code where we have used map and filter for a specific operation.&#xA;In [1]: arr = [11, 12, 14, 15, 18]&#xA;In [2]: list(map(lambda x: x  2, filter(lambda x: x%2 ==1, arr)))&#xA;Out[2]: [22, 30]&#xA;The same code with Pipes.&#xA;In [1]: from pipe import select, where&#xA;In [2]: arr = [11, 12, 14, 15, 18]&#xA;In [3]: list(arr | where (lambda x: x%2 ==1) | select(lambda x:x 2))&#xA;Out[3]: [22, 30]&#xA;Pipes passes the result of one function to another function, have inbuilt pipes method like select, where, tee, traverse. &#xA;&#xA;Install Pipe&#xA;    pip install pipe&#xA;traverse&#xA;Recursively unfold iterable:&#xA; In [12]: arr = [[1,2,3], [3,4,[56]]]&#xA;In [13]: list(arr | traverse)&#xA;Out[13]: [1, 2, 3, 3, 4, 56]&#xA;select()&#xA; An alias for map().&#xA;In [1]: arr = [11, 12, 14, 15, 18]&#xA;In [2]: list(filter(lambda x: x%2 ==1, arr))&#xA;Out[2]: [11, 15]&#xA;where()&#xA;Only yields the matching items of the given iterable:&#xA;In [1]: arr = [11, 12, 14, 15, 18]&#xA;In [2]: list(arr | where(lambda x: x % 2 == 0))&#xA;Out[2]: [12, 14, 18]&#xA;sort()&#xA;Like Python&#39;s built-in &#34;sorted&#34; primitive. Allows cmp (Python 2.x&#xA;only), key, and reverse arguments. By default, sorts using the&#xA;identity function as the key.&#xA;In [1]:  &#39;&#39;.join(&#34;python&#34; | sort)&#xA;Out[1]:  &#39;hnopty&#39;&#xA;reverse&#xA;Like Python&#39;s built-in &#34;reversed&#34; primitive.&#xA;In [1]:  list([1, 2, 3] | reverse)&#xA;Out[1]:   [3, 2, 1]&#xA;strip&#xA;Like Python&#39;s strip-method for str.&#xA;In [1]:  &#39;  abc   &#39; | strip&#xA;Out[1]:  &#39;abc&#39;&#xA;&#xA;That&#39;s all for today, In this blog you have seen how to install the Pipe and use the Pipe to write clean and short code using inbuilt pipes, you can check more over here&#xA;&#xA;Cheers!&#xA;&#xA;100DaysToOffload&#xA;Python&#xA;DGPLUG]]&gt;</description>
      <content:encoded><![CDATA[<p>Today, we are going to see how we can use <em>|</em> operator in our python code to achieve clean code.</p>

<p>Here is the code where we have used map and filter for a specific operation.</p>

<pre><code class="language-python">In [1]: arr = [11, 12, 14, 15, 18]
In [2]: list(map(lambda x: x * 2, filter(lambda x: x%2 ==1, arr)))
Out[2]: [22, 30]
</code></pre>

<p>The same code with Pipes.</p>

<pre><code>In [1]: from pipe import select, where
In [2]: arr = [11, 12, 14, 15, 18]
In [3]: list(arr | where (lambda x: x%2 ==1) | select(lambda x:x *2))
Out[3]: [22, 30]
</code></pre>

<p>Pipes passes the result of one function to another function, have inbuilt pipes method like <strong>select</strong>, <strong>where</strong>, <strong>tee</strong>, <strong>traverse</strong>.</p>

<h3 id="install-pipe">Install Pipe</h3>

<pre><code class="language-shell">&gt;&gt; pip install pipe
</code></pre>

<h3 id="traverse">traverse</h3>

<p>Recursively unfold iterable:</p>

<pre><code class="language-python">In [12]: arr = [[1,2,3], [3,4,[56]]]
In [13]: list(arr | traverse)
Out[13]: [1, 2, 3, 3, 4, 56]
</code></pre>

<h3 id="select">select()</h3>

<p> An alias for map().</p>

<pre><code class="language-python">In [1]: arr = [11, 12, 14, 15, 18]
In [2]: list(filter(lambda x: x%2 ==1, arr))
Out[2]: [11, 15]
</code></pre>

<h3 id="where">where()</h3>

<p>Only yields the matching items of the given iterable:</p>

<pre><code class="language-python">In [1]: arr = [11, 12, 14, 15, 18]
In [2]: list(arr | where(lambda x: x % 2 == 0))
Out[2]: [12, 14, 18]
</code></pre>

<h3 id="sort">sort()</h3>

<p>Like Python&#39;s built-in “sorted” primitive. Allows cmp (Python 2.x
only), key, and reverse arguments. By default, sorts using the
identity function as the key.</p>

<pre><code class="language-python">In [1]:  &#39;&#39;.join(&#34;python&#34; | sort)
Out[1]:  &#39;hnopty&#39;
</code></pre>

<h3 id="reverse">reverse</h3>

<p>Like Python&#39;s built-in “reversed” primitive.</p>

<pre><code class="language-python">In [1]:  list([1, 2, 3] | reverse)
Out[1]:   [3, 2, 1]
</code></pre>

<h3 id="strip">strip</h3>

<p>Like Python&#39;s strip-method for str.</p>

<pre><code class="language-python">In [1]:  &#39;  abc   &#39; | strip
Out[1]:  &#39;abc&#39;
</code></pre>

<p>That&#39;s all for today, In this blog you have seen how to install the Pipe and use the Pipe to write clean and short code using inbuilt pipes, you can check more over <a href="https://github.com/JulienPalard/Pipe#existing-pipes-in-this-module" rel="nofollow">here</a></p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a>
<a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a>
<a href="/sandeepk/tag:DGPLUG" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">DGPLUG</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/sh-like-infix-syntax-using-pipes-in-python</guid>
      <pubDate>Mon, 29 Nov 2021 14:18:04 +0000</pubDate>
    </item>
    <item>
      <title>Profiling Django Application</title>
      <link>https://blogs.dgplug.org/sandeepk/profiling-django-application</link>
      <description>&lt;![CDATA[My work required me to profile one of our Django applications, to help identify the point in the application which we can improve to reach our North Star. So, I thought it will be great to share my learning and tools, that I have used to get the job done.&#xA;&#xA;What is Profiling?&#xA;Profiling) is a measure of the time or memory consumption of the running program. This data further can be used for program optimization.&#xA;&#xA;They are many tools/libraries out there which can be used to do the job. I have found these helpful.&#xA;&#xA;Apache JMeter&#xA;It is open-source software, which is great to load and performance test web applications. It&#39;s easy to set up and can be configured for what we want in the result report.&#xA;&#xA;Pyinstrument&#xA;Pyinstrument is a Python profiler that offers a Django middleware to record the profiling. The profiler generates profile data for every request. The PYINSTRUMENTPROFILEDIR contains a directory that stores the profile data, which is in HTML format. You can check how it works over here&#xA;&#xA;Django Query Count&#xA;Django Query Count is a middleware that prints the number of database queries made during the request processing. There are two possible settings for this, which can be found here&#xA;&#xA;Django Silk&#xA;Django Silk is middleware for intercepting Requests/Responses. We can profile a block of code or functions, either manually or dynamically. It also has a user interface for inspection and visualization &#xA;&#xA;So, here are some of the tools which can be of great help in profiling your code and putting your effort in the right direction of optimization applications.&#xA;&#xA;Cheers!&#xA;&#xA;100DaysToOffload&#xA;Python&#xA;DGPLUG&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>My work required me to profile one of our Django applications, to help identify the point in the application which we can improve to reach our North Star. So, I thought it will be great to share my learning and tools, that I have used to get the job done.</p>

<h2 id="what-is-profiling">What is Profiling?</h2>

<p><a href="https://en.wikipedia.org/wiki/Profiling_(computer_programming)" rel="nofollow">Profiling</a> is a measure of the time or memory consumption of the running program. This data further can be used for program optimization.</p>

<p>They are many tools/libraries out there which can be used to do the job. I have found these helpful.</p>

<h2 id="apache-jmeter-https-jmeter-apache-org"><a href="https://jmeter.apache.org/" rel="nofollow">Apache JMeter</a></h2>

<p>It is open-source software, which is great to load and performance test web applications. It&#39;s easy to set up and can be configured for what we want in the result report.</p>

<h2 id="pyinstrument-https-pyinstrument-readthedocs-io-en-latest-home-html"><a href="https://pyinstrument.readthedocs.io/en/latest/home.html" rel="nofollow">Pyinstrument</a></h2>

<p>Pyinstrument is a Python profiler that offers a Django middleware to record the profiling. The profiler generates profile data for every request. The PYINSTRUMENT<em>PROFILE</em>DIR contains a directory that stores the profile data, which is in HTML format. You can check how it works over <a href="https://pyinstrument.readthedocs.io/en/latest/how-it-works.html" rel="nofollow">here</a></p>

<h2 id="django-query-count-https-github-com-bradmontgomery-django-querycount"><a href="https://github.com/bradmontgomery/django-querycount" rel="nofollow">Django Query Count</a></h2>

<p>Django Query Count is a middleware that prints the number of database queries made during the request processing. There are two possible settings for this, which can be found <a href="https://github.com/bradmontgomery/django-querycount#settings" rel="nofollow">here</a></p>

<h2 id="django-silk-https-github-com-jazzband-django-silk"><a href="https://github.com/jazzband/django-silk" rel="nofollow">Django Silk</a></h2>

<p>Django Silk is middleware for intercepting Requests/Responses. We can profile a block of code or functions, either manually or dynamically. It also has a user interface for inspection and visualization</p>

<p>So, here are some of the tools which can be of great help in profiling your code and putting your effort in the right direction of optimization applications.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a>
<a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a>
<a href="/sandeepk/tag:DGPLUG" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">DGPLUG</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/profiling-django-application</guid>
      <pubDate>Sun, 28 Nov 2021 12:00:31 +0000</pubDate>
    </item>
    <item>
      <title>Image Modes</title>
      <link>https://blogs.dgplug.org/sandeepk/image-modes</link>
      <description>&lt;![CDATA[Today we are going to talk about the modes of image. The mode of image defines the depth and type of the pixel. These string values help you understand different information about the image. As of this writing, we have 11 standard modes.&#xA;&#xA;1 (1-bit pixels, black and white, stored with one pixel per byte)&#xA;&#xA;L (8-bit pixels, black and white)&#xA;&#xA;P (8-bit pixels, mapped to any other mode using a color palette)&#xA;&#xA;RGB (3x8-bit pixels, true color)&#xA;&#xA;RGBA (4x8-bit pixels, true color with transparency mask)&#xA;&#xA;CMYK (4x8-bit pixels, color separation)&#xA;&#xA;YCbCr (3x8-bit pixels, color video format)&#xA;&#xA;LAB (3x8-bit pixels, the Lab color space)&#xA;&#xA;HSV (3x8-bit pixels, Hue, Saturation, Value color space)&#xA;&#xA;I (32-bit signed integer pixels)&#xA;&#xA;F (32-bit floating point pixels)&#xA;&#xA;So, 1-bit pixel range from 0-1 and 8-bit pixel range from 0-255. The common modes are RGB, RGBA, P mode. Image also consist of band, common band like RGB for red, green, blue also have an Alpha(A) transparency, mainly for PNG image.&#xA;&#xA;We can also change these modes with the help of convert or creating new image with the help of pillow library. Let see the code for example&#xA;&#xA;here we convert RGBA image to RGB image and painting the Alpha &#xA;trasparency band to white color&#xA;image = Image.open(&#34;path/to/image&#34;)&#xA;image.mode # this will tell image mode&#xA;newimage = Image.new(&#34;RGB&#34;, image.size, (255, 255, 255))&#xA;newimage.paste(image, mask=image.split()[3])&#xA;That&#39;s all about the modes. There is also raw modes where you can create even your modes, but will save that for another blog post :)&#xA;&#xA;Cheers!&#xA;&#xA;100DaysToOffload&#xA;Python&#xA;Pillow&#xA;&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>Today we are going to talk about the modes of image. The mode of image defines the depth and type of the pixel. These string values help you understand different information about the image. As of this writing, we have <strong>11 standard</strong> modes.</p>
<ul><li><p>1 (1-bit pixels, black and white, stored with one pixel per byte)</p></li>

<li><p>L (8-bit pixels, black and white)</p></li>

<li><p>P (8-bit pixels, mapped to any other mode using a color palette)</p></li>

<li><p>RGB (3x8-bit pixels, true color)</p></li>

<li><p>RGBA (4x8-bit pixels, true color with transparency mask)</p></li>

<li><p>CMYK (4x8-bit pixels, color separation)</p></li>

<li><p>YCbCr (3x8-bit pixels, color video format)</p></li>

<li><p>LAB (3x8-bit pixels, the L<em>a</em>b color space)</p></li>

<li><p>HSV (3x8-bit pixels, Hue, Saturation, Value color space)</p></li>

<li><p>I (32-bit signed integer pixels)</p></li>

<li><p>F (32-bit floating point pixels)</p></li></ul>

<p>So, 1-bit pixel range from 0-1 and 8-bit pixel range from 0-255. The common modes are RGB, RGBA, P mode. Image also consist of band, common band like RGB for red, green, blue also have an Alpha(A) transparency, mainly for PNG image.</p>

<p>We can also change these modes with the help of <a href="https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert" rel="nofollow">convert</a> or creating new image with the help of pillow library. Let see the code for example</p>

<pre><code class="language-python"># here we convert RGBA image to RGB image and painting the Alpha 
# trasparency band to white color
image = Image.open(&#34;path/to/image&#34;)
image.mode # this will tell image mode
new_image = Image.new(&#34;RGB&#34;, image.size, (255, 255, 255))
new_image.paste(image, mask=image.split()[3])
</code></pre>

<p>That&#39;s all about the modes. There is also raw modes where you can create even your modes, but will save that for another blog post :)</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a>
<a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a>
<a href="/sandeepk/tag:Pillow" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Pillow</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/image-modes</guid>
      <pubDate>Fri, 26 Nov 2021 08:08:52 +0000</pubDate>
    </item>
    <item>
      <title>Python : Data Class</title>
      <link>https://blogs.dgplug.org/sandeepk/python-data-class</link>
      <description>&lt;![CDATA[A data class is a class containing data only, from Python3.7 we can define a data class with the help of decorator @dataclass, which build the class with the basic functionality like init , repr, eq and more special methods.&#xA;&#xA;Let see how to define your data class with the decorator @dataclass&#xA;from dataclasses import dataclass&#xA;&#xA;@dataclass&#xA;class Batch:&#xA;    sku: int&#xA;    name: str&#xA;    qty: int&#xA;&#xA;      Batch(1, &#39;desk&#39;, 100)&#xA;Batch(sku=1, name=&#39;desk&#39;, qty=100)&#xA;We can also add the default value to the data class, which works exactly as if we do in the init  method of regular class. As you have noticed in the above we have defined the fields with type hints, which is kind of mandatory thing in the data class, if you do not do it will not take the field in your data class.&#xA;&#xA;@dataclass&#xA;class Batch:&#xA;    sku: int = 1&#xA;    name: str = &#39;desk&#39;&#xA;    qty: int = 100&#xA;&#xA;if you don&#39;t want to explicity type the fields you can use any&#xA;from typing import Any&#xA;class AnyBatch:&#xA;    sku: Any&#xA;    name: Any = &#39;desk&#39;&#xA;    qty: Any = 100&#xA;&#xA;If you want to define mutable default value in data class, it can be done with the help of defaultfactory and field. Field() is used to customize each field in data class, different parameter that can be passed to field are defaultfactory, compare, hash, init, you can check about them over here &#xA;from dataclasses import dataclass, field&#xA;from typing import List&#xA;&#xA;@dataclass()&#xA;class Batch:&#xA;    sku: int&#xA;    name: str&#xA;    qty: int = 0&#xA;    creator: List[str] = field(default_factory=function/mutable value)&#xA;&#xA;Immutable Data Class&#xA;we can also define our data class as immutable by setting frozen=True, which basically means we cannot assign value to the fields after creation&#xA;@dataclass(frozen=True)&#xA;class Batch:&#xA;    sku: int&#xA;    name: str&#xA;    qty: int = 0&#xA;&#xA;      b = Batch(12, &#39;desk&#39;, 100)&#xA;      b.qty &#xA;100&#xA;      b.qty = 90&#xA;dataclasses.FrozenInstanceError: cannot assign to field &#39;qty&#39;&#xA;Data class saves us from writing boilerplate code, help us to focus on logic, this new feature of Python3.7 is great, so what waiting for go and right some data classes.&#xA;&#xA;Cheers!&#xA;&#xA;100DaysToOffload&#xA;Python&#xA;DataClass&#xA;TIL&#xA;DGPLUG&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>A data class is a class containing data only, from Python3.7 we can define a data class with the help of decorator <code>@dataclass</code>, which build the class with the basic functionality like <code>__init__</code> , <code>__repr__</code>, <code>__eq__</code> and more special methods.</p>

<p>Let see how to define your data class with the decorator <code>@dataclass</code></p>

<pre><code class="language-python">from dataclasses import dataclass

@dataclass
class Batch:
    sku: int
    name: str
    qty: int

&gt;&gt;&gt; Batch(1, &#39;desk&#39;, 100)
Batch(sku=1, name=&#39;desk&#39;, qty=100)
</code></pre>

<p>We can also add the default value to the data class, which works exactly as if we do in the <code>__init__</code>  method of regular class. As you have noticed in the above we have defined the fields with type hints, which is kind of mandatory thing in the data class, if you do not do it will not take the field in your data class.</p>

<pre><code class="language-python">@dataclass
class Batch:
    sku: int = 1
    name: str = &#39;desk&#39;
    qty: int = 100

# if you don&#39;t want to explicity type the fields you can use any
from typing import Any
class AnyBatch:
    sku: Any
    name: Any = &#39;desk&#39;
    qty: Any = 100

</code></pre>

<p>If you want to define mutable default value in data class, it can be done with the help of <code>default_factory</code> and <code>field</code>. Field() is used to customize each field in data class, different parameter that can be passed to field are <code>default_factory</code>, <code>compare</code>, <code>hash</code>, <code>init</code>, you can check about them over <a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.field" rel="nofollow">here </a></p>

<pre><code class="language-python">from dataclasses import dataclass, field
from typing import List

@dataclass()
class Batch:
    sku: int
    name: str
    qty: int = 0
    creator: List[str] = field(default_factory=&lt;function/mutable value&gt;)
</code></pre>

<p><strong>Immutable Data Class</strong>
we can also define our data class as immutable by setting <code>frozen=True</code>, which basically means we cannot assign value to the fields after creation</p>

<pre><code class="language-python">@dataclass(frozen=True)
class Batch:
    sku: int
    name: str
    qty: int = 0

&gt;&gt;&gt; b = Batch(12, &#39;desk&#39;, 100)
&gt;&gt;&gt; b.qty 
100
&gt;&gt;&gt; b.qty = 90
dataclasses.FrozenInstanceError: cannot assign to field &#39;qty&#39;
</code></pre>

<p>Data class saves us from writing boilerplate code, help us to focus on logic, this new feature of Python3.7 is great, so what waiting for go and right some data classes.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a>
<a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a>
<a href="/sandeepk/tag:DataClass" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">DataClass</span></a>
<a href="/sandeepk/tag:TIL" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">TIL</span></a>
<a href="/sandeepk/tag:DGPLUG" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">DGPLUG</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/python-data-class</guid>
      <pubDate>Fri, 03 Sep 2021 12:54:52 +0000</pubDate>
    </item>
    <item>
      <title>Workshop on creating Python modules using Rust</title>
      <link>https://blogs.dgplug.org/sandeepk/workshop-on-creating-python-modules-using-rust</link>
      <description>&lt;![CDATA[This Sunday, I attended the workshop on Creating Python modules using Rust by Kushal Das. The workshop started at 0900 UTC 18th April on Twitch.&#xA;&#xA;The GitHub repo we follow along with the workshop can be found over here. Learned many new things in the workshop where we go through&#xA;&#xA;Hello World example&#xA;User passed arguments&#xA;Exception Handling&#xA;File I/O&#xA;System Interaction (Process, System Information)&#xA;&#xA;Enjoyed my time while going through these examples and like the way Kushal has arranged all the examples branch wise.&#xA;&#xA;Cheers!&#xA;&#xA;Useful Links&#xA;https://github.com/kushaldas/workshops/issues/2&#xA;https://kushaldas.in/&#xA;&#xA;#100DaysToOffload  #Python #Rust&#xA;&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>This Sunday, I attended the workshop on Creating Python modules using Rust by Kushal Das. The workshop started at 0900 UTC 18th April on <a href="https://twitch.com/whykushal" rel="nofollow">Twitch</a>.</p>

<p>The GitHub repo we follow along with the workshop can be found over <a href="https://github.com/kushaldas/randomos" rel="nofollow">here</a>. Learned many new things in the workshop where we go through</p>
<ul><li>Hello World example</li>
<li>User passed arguments</li>
<li>Exception Handling</li>
<li>File I/O</li>
<li>System Interaction (Process, System Information)</li></ul>

<p>Enjoyed my time while going through these examples and like the way Kushal has arranged all the examples <a href="https://github.com/kushaldas/randomos/branches/all" rel="nofollow">branch</a> wise.</p>

<p>Cheers!</p>

<p>Useful Links
– <a href="https://github.com/kushaldas/workshops/issues/2" rel="nofollow">https://github.com/kushaldas/workshops/issues/2</a>
– <a href="https://kushaldas.in/" rel="nofollow">https://kushaldas.in/</a></p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a>  <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a> <a href="/sandeepk/tag:Rust" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Rust</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/workshop-on-creating-python-modules-using-rust</guid>
      <pubDate>Sun, 18 Apr 2021 16:47:16 +0000</pubDate>
    </item>
    <item>
      <title>Django: Many-to-One Relationship</title>
      <link>https://blogs.dgplug.org/sandeepk/django-many-to-one-relationship</link>
      <description>&lt;![CDATA[Today we are gone to talk about the Foreign Key which is used to establish a many-to-one relationship and different args which can be passed.&#xA;&#xA;Syntax to define a Foreign key relationship&#xA;from django.db import models&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE)&#xA;&#xA;Different args for the Foreign Key&#xA;&#xA;ondelete&#xA;limitchoicesto&#xA;relatedname&#xA;relatedqueryname&#xA;tofield&#xA;dbconstraints&#xA;&#xA;ondelete&#xA;This args handle the process, of what to do if the reference keys are deleted, we have three options&#xA;CASCADE: It deletes the objects contains the Foreign key&#xA;PROTECT: It prevents the deletion of the referenced object by raising ProtectedError&#xA;RESTRICT: Introduced in Django 3.1, It only deletes the object, if another references object is being deleted in the same operation, but with CASCADE flow otherwise raise RestrictedError&#xA;&#xA;from django.db import models&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE)&#xA;&#xA;limit\choices\to&#xA;This is helpful in the form rendering to restrict the option for the reference field. The limited choice can either be a dict, Q object  or a callable that return dict or Q object &#xA;&#xA;from django.db import models&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, limitchoicesto={&#39;taxtype&#39;: &#39;gst&#39;},)&#xA;here we only show the tax of type GST only.&#xA;&#xA;relatedname&#xA;It&#39;s the name that can be used for the reverse or backward reference while querying. You can also stop the backward relation by assigning  + in relatedname.&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, relatedname=&#39;+&#39;,) # IN this case GSTRate cannot backward realte to the Purchase Order obejct.&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, relatedname=&#39;invoice&#39;)&#xA;&#xA;here you can refer to Invoice inside GSTRate query by the related name.&#xA;GSTRate.objects.filter(invoiceid=1232)&#xA;&#xA;related\query\name&#xA;It has the same value as the relatedname, unless not specified explicitly. If it is defined then you have to use that name while querying&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class OrderConfirmation(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, relatedname=&#39;orderconfirmation&#39;, relatedqueryname=&#39;oc&#39;)&#xA;&#xA;here you can refer to Invoice inside GSTRate query by the related name.&#xA;GSTRate.objects.filter(ocid=112)&#xA;tofield&#xA;This is helpful in the case where you want to refer other the primary key of the modal, but the condition whatever key you referred it should be unique=True&#xA;&#xA;db_constraints&#xA;This is used to create a constraint at the database level, by default value is true and if the user sets the value to False, then accessing a related object that doesn’t exist will raise its DoesNotExist exception.&#xA;&#xA;Conclusion&#xA;These args are handy which gives us the possibilities of implementing the additional constraint and functionality to query data in the Django ORM query language.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #Python#Django]]&gt;</description>
      <content:encoded><![CDATA[<p>Today we are gone to talk about the Foreign Key which is used to establish a many-to-one relationship and different args which can be passed.</p>

<p>Syntax to define a Foreign key relationship</p>

<pre><code class="language-python">from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)
</code></pre>

<p>Different args for the <em>Foreign Key</em></p>
<ul><li>on_delete</li>
<li>limit<em>choices</em>to</li>
<li>related_name</li>
<li>related<em>query</em>name</li>
<li>to_field</li>
<li>db_constraints</li></ul>

<p><strong>on_delete</strong>
This args handle the process, of what to do if the reference keys are deleted, we have three options
– CASCADE: It deletes the objects contains the Foreign key
– PROTECT: It prevents the deletion of the referenced object by raising <em>ProtectedError</em>
– RESTRICT: Introduced in <strong>Django 3.1</strong>, It only deletes the object, if another references object is being deleted in the same operation, but with <em>CASCADE</em> flow otherwise raise <em>RestrictedError</em></p>

<pre><code class="language-python">from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)
</code></pre>

<p><strong>limit_choices_to</strong>
This is helpful in the form rendering to restrict the option for the reference field. The limited choice can either be a <em>dict</em>, <em>Q object</em>  or a callable that return <em>dict</em> or <em>Q object</em></p>

<pre><code class="language-python">from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, limit_choices_to={&#39;tax_type&#39;: &#39;gst&#39;},)
# here we only show the tax of type GST only.
</code></pre>

<p><strong>related_name</strong>
It&#39;s the name that can be used for the reverse or backward reference while querying. You can also stop the backward relation by assigning  <em>+</em> in related_name.</p>

<pre><code class="language-python">
class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name=&#39;+&#39;,) # IN this case GSTRate cannot backward realte to the Purchase Order obejct.

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name=&#39;invoice&#39;)

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(invoice_id=1232)
</code></pre>

<p><strong>related_query_name</strong>
It has the same value as the <em>related_name</em>, unless not specified explicitly. If it is defined then you have to use that name while querying</p>

<pre><code class="language-python">
class GSTRate(models.Model):
    # ...
    pass

class OrderConfirmation(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name=&#39;order_confirmation&#39;, related_query_name=&#39;oc&#39;)

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(oc_id=112)
</code></pre>

<p><strong>to_field</strong>
This is helpful in the case where you want to refer other the primary key of the modal, but the condition whatever key you referred it should be <em>unique=True</em></p>

<p><strong>db_constraints</strong>
This is used to create a constraint at the database level, by default value is true and if the user sets the value to <em>False</em>, then accessing a related object that doesn’t exist will raise its <em>DoesNotExist</em> exception.</p>

<p><strong>Conclusion</strong>
These <em>args</em> are handy which gives us the possibilities of implementing the additional constraint and functionality to query data in the Django ORM query language.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a><a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-many-to-one-relationship</guid>
      <pubDate>Thu, 15 Apr 2021 16:21:50 +0000</pubDate>
    </item>
    <item>
      <title>Django: Template Tags and Filters</title>
      <link>https://blogs.dgplug.org/sandeepk/django-template-tags-and-filters</link>
      <description>&lt;![CDATA[Template is the one of powerful features of Django Framework, and we will discuss the tag and filter. If you do not have any idea about the template, please go read about that here, I will wait for you.&#xA;&#xA;Template tags which we are going to discuss today are&#xA;&#xA;URL&#xA;Now&#xA;Spaceless&#xA;&#xA;URL&#xA;The URL tag is the template equivalent of the reverse function. URL can accept args or kwargs for routes that expect other variables. &#xA;a href=&#34;{% url &#34;anamedview&#34; %}&#34;Go to a named view/a&#xA;Now&#xA;Now is a convenient method to display information about the current time. It was a problem solver for the copyright year update, which I first have to update every year manually.&#xA;&amp;copy; {% now &#34;Y&#34; %} sandeepk.dev.&#xA;Spaceless&#xA;It removes the whitespace, newline, tab from the HTML&#xA;{% spaceless %}&#xA;    div&#xA;        spanI am a good span./span&#xA;    /div&#xA;{% endspaceless %}&#xA;Now let&#39;s talk about the filter which we can use in the template.&#xA;&#xA;date&#xA;default&#xA;pluralize&#xA;yesno&#xA;&#xA;Date&#xA;This filter can be used to control the format of the datetime passed in the context of the response.&#xA;{{ birthdate|date:&#34;Y-m-d&#34; }}&#xA;Default&#xA;Have you ever been in a condition when you want to show a text for a falsy value, then default filter is the one thing you should use&#xA;{{ valuetocheck|default:&#34;Nothing to see here.&#34; }}&#xA;Pluralize&#xA;When your text considers counts of things. Pluralize can use to save you from if and else check&#xA;{ countitems }} item{{ countitems|pluralize }}&#xA;&#xA;0 items&#xA;1 item&#xA;2 items&#xA;3 items&#xA;(and so on)&#xA;YesNo&#xA;YesNo is good for converting True|False|None into a meaningful text message&#xA;{{ user.name }} has {{ useraccepted|yesno:&#34;accepted,declined,not RSVPed&#34; }} request.&#xA;These are the tags and filter which I use very often but there many more which you can check out here&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #Python #Django&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>Template is the one of powerful features of Django Framework, and we will discuss the tag and filter. If you do not have any idea about the template, please go read about that <a href="https://docs.djangoproject.com/en/3.1/topics/templates/" rel="nofollow">here</a>, I will wait for you.</p>

<p>Template tags which we are going to discuss today are</p>
<ul><li>URL</li>
<li>Now</li>
<li>Spaceless</li></ul>

<p><strong>URL</strong>
The URL tag is the template equivalent of the reverse function. URL can accept args or kwargs for routes that expect other variables.</p>

<pre><code class="language-python">&lt;a href=&#34;{% url &#34;a_named_view&#34; %}&#34;&gt;Go to a named view&lt;/a&gt;
</code></pre>

<p><strong>Now</strong>
Now is a convenient method to display information about the current time. It was a problem solver for the copyright year update, which I first have to update every year manually.</p>

<pre><code class="language-python">&amp;copy; {% now &#34;Y&#34; %} sandeepk.dev.
</code></pre>

<p><strong>Spaceless</strong>
It removes the whitespace, newline, tab from the HTML</p>

<pre><code class="language-html">{% spaceless %}
    &lt;div&gt;
        &lt;span&gt;I am a good span.&lt;/span&gt;
    &lt;/div&gt;
{% endspaceless %}
</code></pre>

<p>Now let&#39;s talk about the filter which we can use in the template.</p>
<ul><li>date</li>
<li>default</li>
<li>pluralize</li>
<li>yesno</li></ul>

<p><strong>Date</strong>
This filter can be used to control the format of the datetime passed in the context of the response.</p>

<pre><code class="language-python">{{ birth_date|date:&#34;Y-m-d&#34; }}
</code></pre>

<p><strong>Default</strong>
Have you ever been in a condition when you want to show a text for a falsy value, then default filter is the one thing you should use</p>

<pre><code class="language-python">{{ value_to_check|default:&#34;Nothing to see here.&#34; }}
</code></pre>

<p><strong>Pluralize</strong>
When your text considers counts of things. Pluralize can use to save you from if and else check</p>

<pre><code class="language-python">{ count_items }} item{{ count_items|pluralize }}

0 items
1 item
2 items
3 items
(and so on)
</code></pre>

<p><strong>YesNo</strong>
YesNo is good for converting True|False|None into a meaningful text message</p>

<pre><code class="language-python">{{ user.name }} has {{ user_accepted|yesno:&#34;accepted,declined,not RSVPed&#34; }} request.
</code></pre>

<p>These are the tags and filter which I use very often but there many more which you can check out <a href="https://docs.djangoproject.com/en/3.0/ref/templates/builtins/" rel="nofollow">here</a></p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a> <a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-template-tags-and-filters</guid>
      <pubDate>Mon, 05 Apr 2021 15:14:38 +0000</pubDate>
    </item>
    <item>
      <title>Python: Private Methods and Variables</title>
      <link>https://blogs.dgplug.org/sandeepk/python-private-methods-and-variables</link>
      <description>&lt;![CDATA[In Python, we can define private variables and methods. These variables and methods cannot be accessed out of the class or by the inherited class according to the Object-Oriented Paradigm. Things are a bit different in Python.&#xA;&#xA;In python, we can achieve this by using Name Mangling which means adding  before the variable or method name, let see how&#xA;class PPrint:&#xA;    def init(self):&#xA;        self.secretmsg = &#39;I am alive&#39; # This is a private variable&#xA;        self.check = False&#xA;&#xA;    def privatemethod(self): # This is a private method&#xA;        print(&#39;I am private method !&#39;)&#xA;                &#xA;    def publicmethod(self): # This public method, which can access the private method&#xA;        self.privatemethod()&#xA;        &#xA;    def publicprint(self):&#xA;        print(self.secretmsg)&#xA;        print(self.check)&#xA; &#xA;In the above class, we define the private methods and variables. Let see how to use them&#xA;&#xA;      p = PPrint()&#xA;      p.publicprint()&#xA;I am alive&#xA;False&#xA;      p.publicmethod()&#xA;I am private method !&#xA;so far so good, let see what happends when we try to access these private methods or variables.&#xA;      p._privatemsg&#xA;Traceback (most recent call last):&#xA;  File &#34;stdin&#34;, line 1, in module&#xA;AttributeError: &#39;PPrint&#39; object has no attribute &#39;_privatemsg&#39;&#xA;      p._privatemethod()&#xA;Traceback (most recent call last):&#xA;  File &#34;stdin&#34;, line 1, in module&#xA;AttributeError: &#39;PPrint&#39; object has no attribute &#39;_privatemethod&#39;&#xA;As you can see python does not allow access to these private variables and methods. But, If I say you can access these private variables and methods.&#xA;      dir(p)&#xA;[&#39;PPrintprivatemethod&#39;, &#39;PPrintsecretmsg&#39;, &#39;class&#39;, &#39;delattr&#39;, &#39;dict&#39;, &#39;dir&#39;, &#39;doc&#39;, &#39;eq&#39;, &#39;format&#39;, &#39;ge&#39;, &#39;getattribute&#39;, &#39;gt&#39;, &#39;hash&#39;, &#39;init&#39;, &#39;_initsubclass&#39;, &#39;le&#39;, &#39;lt&#39;, &#39;module&#39;, &#39;ne&#39;, &#39;new&#39;, &#39;reduce&#39;, &#39;reduceex&#39;, &#39;repr&#39;, &#39;setattr&#39;, &#39;sizeof&#39;, &#39;str&#39;, &#39;subclasshook&#39;, &#39;weakref&#39;, &#39;check&#39;, &#39;publicmethod&#39;, &#39;publicprint&#39;]&#xA;&#xA;You can see we have private method and variable &#39;PPrint_privatemethod&#39;, &#39;PPrintsecretmsg&#39;&#xA;&#xA;      p.PPrintprivatemethod()&#xA;I am private method !&#xA;&#xA;      p.PPrintsecretmsg&#xA;&#39;I am alive&#39;&#xA;So, that&#39;s what  Name Mangling do it add classname_method/variablename. &#xA;&#xA;Conclusion&#xA;In Python, we can use the name mangling to define the private method and variables, but it not as strict as in other OOP languages. It&#39;s almost like a convention which is followed by all python developer. You may also found _* added before the method and variable name, which is just another way to say don&#39;t access these methods directly.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #Python&#xA;&#xA; ]]&gt;</description>
      <content:encoded><![CDATA[<p>In Python, we can define private variables and methods. These variables and methods cannot be accessed out of the class or by the inherited class according to the Object-Oriented Paradigm. Things are a bit different in Python.</p>

<p>In python, we can achieve this by using Name Mangling which means adding <em>__</em> before the variable or method name, let see how</p>

<pre><code class="language-python">class PPrint:
    def __init__(self):
        self.__secret_msg = &#39;I am alive&#39; # This is a private variable
        self.check = False

    def __private_method(self): # This is a private method
        print(&#39;I am private method !&#39;)
                
    def public_method(self): # This public method, which can access the private method
        self.__private_method()
        
    def public_print(self):
        print(self.__secret_msg)
        print(self.check)
 
</code></pre>

<p>In the above class, we define the private methods and variables. Let see how to use them</p>

<pre><code class="language-python">
&gt;&gt;&gt; p = PPrint()
&gt;&gt;&gt; p.public_print()
I am alive
False
&gt;&gt;&gt; p.public_method()
I am private method !
# so far so good, let see what happends when we try to access these private methods or variables.
&gt;&gt;&gt; p.__private_msg
Traceback (most recent call last):
  File &#34;&lt;stdin&gt;&#34;, line 1, in &lt;module&gt;
AttributeError: &#39;PPrint&#39; object has no attribute &#39;__private_msg&#39;
&gt;&gt;&gt; p.__private_method()
Traceback (most recent call last):
  File &#34;&lt;stdin&gt;&#34;, line 1, in &lt;module&gt;
AttributeError: &#39;PPrint&#39; object has no attribute &#39;__private_method&#39;
</code></pre>

<p>As you can see python does not allow access to these private variables and methods. But, If I say you can access these private variables and methods.</p>

<pre><code class="language-python">&gt;&gt;&gt; dir(p)
[&#39;_PPrint__private_method&#39;, &#39;_PPrint__secret_msg&#39;, &#39;__class__&#39;, &#39;__delattr__&#39;, &#39;__dict__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__le__&#39;, &#39;__lt__&#39;, &#39;__module__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;__weakref__&#39;, &#39;check&#39;, &#39;public_method&#39;, &#39;public_print&#39;]

# You can see we have private method and variable &#39;_PPrint__private_method&#39;, &#39;_PPrint__secret_msg&#39;

&gt;&gt;&gt; p._PPrint__private_method()
I am private method !

&gt;&gt;&gt; p._PPrint__secret_msg
&#39;I am alive&#39;
</code></pre>

<p>So, that&#39;s what  <em>Name Mangling</em> do it add *<em>&lt;class</em>name&gt;_<em>&lt;method/variable</em>name&gt;.</p>

<p><strong>Conclusion</strong>
In Python, we can use the name mangling to define the private method and variables, but it not as strict as in other OOP languages. It&#39;s almost like a convention which is followed by all python developer. You may also found <em>_</em> added before the method and variable name, which is just another way to say don&#39;t access these methods directly.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/python-private-methods-and-variables</guid>
      <pubDate>Thu, 25 Mar 2021 16:55:03 +0000</pubDate>
    </item>
  </channel>
</rss>