<?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 Tushar on Medium]]></title>
        <description><![CDATA[Stories by Tushar on Medium]]></description>
        <link>https://medium.com/@mailmeastushar?source=rss-8e18ee382c74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hDrs8qCy4YCIaORxLNR_gQ.jpeg</url>
            <title>Stories by Tushar on Medium</title>
            <link>https://medium.com/@mailmeastushar?source=rss-8e18ee382c74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:51:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mailmeastushar/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[Making Threads Work Together — Synchronization]]></title>
            <link>https://blog.stackademic.com/making-threads-work-together-synchronization-8c5e0c6fbfee?source=rss-8e18ee382c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c5e0c6fbfee</guid>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[threading-in-python]]></category>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[python-thread]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 07:23:05 GMT</pubDate>
            <atom:updated>2023-12-12T01:15:29.752Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making Threads Work Together — Synchronization</h3><p>Picture a kitchen in India with two cooks, Gautam and Badal. They’re both preparing delicious dishes, but there’s a unique spice box they both want to use. However, only one cook can use it at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UauZvccnUwzH3b9e41NQyw.jpeg" /></figure><p>Here’s how they ensure a flavorful collaboration:</p><p><strong>Diverse Tasks:</strong></p><ul><li>Gautam is making biryani, and Badal is crafting curry. Both tasks require a special spice box.</li></ul><p><strong>Single Spice Box:</strong></p><ul><li>There’s only one spice box, and they need to share it.</li></ul><p><strong>Alternating Turns:</strong></p><ul><li>They decide to take turns. If Gautam is using the spice box, Badal patiently waits, and vice versa.</li></ul><p><strong>Effective Communication:</strong></p><ul><li>Gautam and Badal communicate well. When one finishes, they inform the other, preventing any spice-related chaos.</li></ul><p><strong>Harmonious Cooking:</strong></p><ul><li>This synchronized approach creates a feast without overwhelming the spice box. It’s like a coordinated dance in the lively kitchen of flavors.</li></ul><blockquote>In the world of programming, particularly with threads, this scenario mirrors thread synchronization. <a href="https://medium.com/stackademic/speed-boost-how-multi-threading-makes-your-programs-faster-fc663e27d98c">Threads</a>, like Gautam and Badal, work together, taking turns to access shared resources and ensuring a harmonious process.</blockquote><p>Let’s talk about how threads can play nicely together in Python. It’s like teaching them to take turns to work together without causing a mess.</p><blockquote>Basic knowledge of <a href="https://medium.com/p/fc663e27d98c">multi-threading</a> will make you quick learner.</blockquote><blockquote>In Python, there’s a cool module called threading. It’s like a teamwork kit for your code, making things work together smoothly.</blockquote><p><strong>Let&#39;s talk about taking turns first.</strong></p><p>The threading module in Python has four special classes that help your threads play fair and take turns. It’s like having rules to ensure everyone gets a chance to do their job without any chaos.</p><p><strong>Lock</strong></p><p>It is like a key that threads use to access a shared resource one at a time. It prevents conflicts by allowing only one Thread to hold the lock, ensuring the orderly execution of critical code sections.</p><blockquote>Let’s say Gautam is using a knife to chop something so Badal has to wait till Gautam releases the knife.</blockquote><pre>import threading<br>from time import sleep<br><br>class Kitchen:<br>    spice_rack = {&quot;salt&quot;: 100, &quot;pepper&quot;: 50}<br>    lock = threading.Lock()<br><br>    def use_spice(self, chef_name, spice, quantity):<br>        # lock acquire and release using context manager<br>        with self.lock: # aquired the lock so other thread have to wait till lock gets released<br>            current_quantity = self.spice_rack.get(spice, 0)<br>            <br>            if current_quantity &gt;= quantity:<br>                new_quantity = current_quantity - quantity<br>                # Simulate some time-consuming process<br>                sleep(1)<br>                self.spice_rack[spice] = new_quantity<br>                print(f&quot;{chef_name} used {quantity} {spice}. Remaining {spice}: {new_quantity}&quot;)<br>            else:<br>                print(f&quot;Sorry, {chef_name}. Not enough {spice} in the spice rack.&quot;)<br>        # the lock is release by the thread and other thread can aquire the lock and proceed to execute.<br>        <br>        # aquire and release of lock can also be performed without context managers<br>        # using the lock.acquire() method to acquire the lock and lock.release() to release the lock.<br><br><br><br><br># Creating a kitchen<br>kitchen = Kitchen()<br><br># Function for using spices<br>def use_spices(chef_name, spice, quantity):<br>    for _ in range(3):<br>        kitchen.use_spice(chef_name, spice, quantity)<br><br># Creating two chefs<br>gautam = threading.Thread(target=use_spices, args=(&quot;Gautam&quot;, &quot;salt&quot;, 20))<br>badal = threading.Thread(target=use_spices, args=(&quot;Badal&quot;, &quot;pepper&quot;, 10))<br><br># Starting the chefs<br>gautam.start()<br>badal.start()<br><br># Waiting for both chefs to finish<br>gautam.join() # MainThread will get in waiting state till execution of gautam finishes<br>badal.join()<br><br># Displaying the final spice rack<br>print(f&quot;Final spice rack: {kitchen.spice_rack}&quot;)</pre><blockquote>“Lock” allows only one thread to acquire the lock at a time.</blockquote><blockquote>If a thread holds the lock and tries to acquire it again (nested acquisition), it will deadlock. In other words, it doesn’t allow the same thread to acquire the lock multiple times.</blockquote><blockquote>It’s simple and suitable for basic synchronization needs.</blockquote><p>spice_rack = {“salt”: 100, “pepper”: 50}</p><p><strong>RLock (Re-entrant/Recursive Lock)</strong></p><p>It is much like Lock and works like a key for thread to access a resource at a time. The only difference between the same Lock and RLock is It can be acquired <em>n </em>times and released <em>n</em> times by the same thread but to get it acquired by another thread the the acquire and release count should be the same.</p><p>The following code will create DeadLock Since the same lock is getting acquired multiple times by the same thread.</p><pre>from threading import Thread, Lock<br>from time import sleep<br><br>use_multiple_spices = True<br>spice_rack = {&quot;salt&quot;: 100, &quot;pepper&quot;: 50}<br>lock = Lock()<br><br>def use_spices(chef_name, spice, quantity):<br>    &quot;&quot;&quot;<br>    Simulate some time-consuming process<br>   <br>    :param:<br>        * chef_name - name of the chef<br>        * spice - spice to be used<br>        * quantity - quantity of spice to be used<br>  <br>    :return:<br>        None - prints the result<br><br>    &quot;&quot;&quot;<br>    global use_multiple_spices<br><br>    lock.acquire() <br>    # Acquire the lock | If the lock is already acquired by another thread, the calling thread will block until the lock is released by the other thread.<br><br>    current_quantity = spice_rack.get(spice, 0)<br>    <br>    if current_quantity &gt;= quantity:<br>        new_quantity = current_quantity - quantity<br>        # Simulate some time-consuming process<br>        sleep(1)<br>        spice_rack[spice] = new_quantity<br><br>        if use_multiple_spices:<br>            use_multiple_spices = False<br>            <br>            use_spices(chef_name, &quot;pepper&quot;, quantity) # Recursive call<br>            print(f&quot;{chef_name} used {quantity} pepper. Remaining {spice}: {new_quantity}&quot;)<br>        else:<br>            print(f&quot;{chef_name} used {quantity} {spice}. Remaining {spice}: {new_quantity}&quot;)<br>    else:<br>        print(f&quot;Sorry, {chef_name}. Not enough {spice} in the spice rack.&quot;)<br>    <br>    lock.release()<br><br>gautam = Thread(target=use_spices, args=(&quot;Gautam&quot;, &quot;salt&quot;, 10))<br>badal = Thread(target=use_spices, args=(&quot;Badal&quot;, &quot;salt&quot;, 10))<br><br>gautam.start()<br>badal.start()<br></pre><p>To overcome this DeadLock situation we can go for RLock</p><pre>from threading import Thread, RLock<br>from time import sleep<br><br>use_multiple_spices = True<br>spice_rack = {&quot;salt&quot;: 100, &quot;pepper&quot;: 50}<br>lock = RLock()<br><br><br>def use_spices(chef_name, spice, quantity):<br>    &quot;&quot;&quot;<br>    Simulate some time-consuming process<br>   <br>    :param:<br>        * chef_name - name of the chef<br>        * spice - spice to be used<br>        * quantity - quantity of spice to be used<br>  <br>    :return:<br>        None - prints the result<br><br>    &quot;&quot;&quot;<br>    global use_multiple_spices<br><br>    lock.acquire() <br>    # Acquire the lock | If the lock is already acquired by another thread, the calling thread will block until the lock is released by the other thread.<br><br>    current_quantity = spice_rack.get(spice, 0)<br>    <br>    if current_quantity &gt;= quantity:<br>        new_quantity = current_quantity - quantity<br>        # Simulate some time-consuming process<br>        sleep(1)<br>        spice_rack[spice] = new_quantity<br><br>        if use_multiple_spices:<br>            use_multiple_spices = False<br>            <br>            use_spices(chef_name, &quot;pepper&quot;, quantity) # Recursive call<br>            print(f&quot;{chef_name} used {quantity} pepper. Remaining {spice}: {new_quantity}&quot;)<br>        else:<br>            print(f&quot;{chef_name} used {quantity} {spice}. Remaining {spice}: {new_quantity}&quot;)<br>    else:<br>        print(f&quot;Sorry, {chef_name}. Not enough {spice} in the spice rack.&quot;)<br>    <br>    lock.release()<br><br>gautam = Thread(target=use_spices, args=(&quot;Gautam&quot;, &quot;salt&quot;, 10))<br>badal = Thread(target=use_spices, args=(&quot;Badal&quot;, &quot;salt&quot;, 10))<br><br>gautam.start()<br>badal.start()<br></pre><p>The RLock will allow the same lock to be acquired by the same thread and DeadLock the situation will be ignored.</p><p><strong>Semaphore</strong></p><p>Semaphore is used to limit the number of threads that can access a resource at the same time. Works same as Lock</p><pre>from threading import Thread, Semaphore<br>from time import sleep<br><br>spice_rack = {&quot;salt&quot;: 100, &quot;pepper&quot;: 50}<br>lock = Semaphore(2)<br><br>def use_spices(chef_name, spice, quantity):<br>    &quot;&quot;&quot;<br>    Simulate some time-consuming process<br>    2 threads can access this function at the same time<br>   <br>    :param:<br>        * chef_name - name of the chef<br>        * spice - spice to be used<br>        * quantity - quantity of spice to be used<br>  <br>    :return:<br>        None - prints the result<br><br>    &quot;&quot;&quot;<br>    <br>    lock.acquire()<br><br>    current_quantity = spice_rack.get(spice, 0)<br><br>    if current_quantity &gt;= quantity:<br>        new_quantity = current_quantity - quantity<br>        # Simulate some time-consuming process<br>        sleep(1)<br>        spice_rack[spice] = new_quantity<br>        print(f&quot;{chef_name} used {quantity} {spice}. Remaining {spice}: {new_quantity}&quot;)<br>    else:<br>        print(f&quot;Sorry, {chef_name}. Not enough {spice} in the spice rack.&quot;)<br><br>    lock.release()<br><br>badal = Thread(target=use_spices, args=(&quot;Badal&quot;, &quot;salt&quot;, 10))<br>gautam = Thread(target=use_spices, args=(&quot;Gautam&quot;, &quot;pepper&quot;, 10))<br>akansha = Thread(target=use_spices, args=(&quot;Akansha&quot;, &quot;salt&quot;, 10))<br>shreya = Thread(target=use_spices, args=(&quot;Shreya&quot;, &quot;pepper&quot;, 10))<br><br>badal.start()<br>gautam.start()<br>akansha.start()<br>shreya.start()</pre><p>Summary</p><p>The Lock, RLock and Semaphore classes enable you to make multiple threads operate on the same resource more efficiently. All three classes control the behavior of a thread over resources and can save you from inconsistency.</p><p><strong>Official Website</strong> <a href="https://pythonbricks.pythonanywhere.com/">https://pythonbricks.pythonanywhere.com/</a></p><p><strong>Youtube Channel</strong> <a href="https://www.youtube.com/@PythonBricks">https://www.youtube.com/@PythonBricks</a></p><p><strong>Telegram</strong> <a href="https://t.me/pythonbricks">https://t.me/pythonbricks</a></p><p><strong>Watch and Learn</strong></p><p><a href="https://www.youtube.com/watch?v=Ke8gBPq9ems">https://www.youtube.chttps://www.youtube.com/watch?v=Ke8gBPq9emsom</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c5e0c6fbfee" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/making-threads-work-together-synchronization-8c5e0c6fbfee">Making Threads Work Together — Synchronization</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed Boost: How Multi-Threading Makes Your Programs Faster]]></title>
            <link>https://blog.stackademic.com/speed-boost-how-multi-threading-makes-your-programs-faster-fc663e27d98c?source=rss-8e18ee382c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc663e27d98c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[multithreading-in-python]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[multitasking]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 09:05:03 GMT</pubDate>
            <atom:updated>2023-11-29T01:17:47.253Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re at a grocery store, and you need to buy a bunch of items. Now, you have two options:</p><p><strong>Option 1:</strong> You’re the only person shopping, and you have to go through each aisle one by one, picking up items and waiting in line at the checkout each time. It’s like a slow-motion shopping marathon, and you end up spending a lot of time.</p><p><strong>Option 2:</strong> You bring a friend (or a few friends) with you. Each person takes a separate aisle, grabs items simultaneously, and you all meet up at the checkout. It’s like a synchronized shopping dance, and you finish much faster!</p><p>Now, replace “you” with a computer program, “aisles” with tasks, and “friends” with threads. That’s essentially multi-threading! In the computer world, programs have different tasks to perform, and multi-threading allows them to tackle those tasks simultaneously, making the whole process faster and more efficient.</p><p><strong>In super easy language, what exactly is a thread?</strong></p><p>Think of a thread as a helper inside your computer that can do one thing at a time. If your computer is like a kitchen, a thread is like a little chef handling one task, and when you have many chefs (threads), the kitchen gets things done quicker!</p><p><strong>The thread has to go through various stages of its life.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4zhyqwTTiTPqFfYZi-rjg.jpeg" /><figcaption>Life-Cycle of a Thread</figcaption></figure><p><strong>Getting Ready (New)</strong></p><p>The thread is created but hasn’t started yet.</p><p><strong>Time to Work (Runnable/Ready)</strong></p><p>Now the Task is assigned , the thread is all set to start the job.</p><p><strong>Working Hard (Running/Active)</strong></p><p>The thread is actively doing its task, just like a worker doing their job.</p><p><strong>Taking a Break (Waiting/Blocked)</strong></p><p>Sometimes, the thread needs to wait a bit, like taking a short break until things are ready.</p><p><strong>Job Done (Dead/Terminiated)</strong></p><p>Finally, the thread finishes its job and is done for the day, just like a worker going home after work.</p><p><strong>How things can be implemented using Python.</strong></p><p>Python makes things easier with the a built in module threading which takes care of everything.</p><pre>from threading import Thread</pre><p>The thread class is all you need for creating and using multiple threads in your Python program</p><p>There are various ways by which we can create threads</p><p><strong>Firstly let&#39;s create a thread by </strong><strong>Thread class object</strong></p><pre>from threading import Thread, current_thread<br>from time import sleep<br><br>def task(f_name:str, l_name:str) -&gt; None:<br>  &quot;&quot;&quot;<br>     This is a simple function which greets the provided name<br>     :param:<br>        f_name -&gt; a string of any length<br>        l_name -&gt; a string of any length<br>     :return:<br>        None -&gt; Simply nothing<br>  &quot;&quot;&quot;<br>  <br>  executing_thread = current_thread() # return the current thread object<br>  <br>  print(f&quot;Execution of task is started by {executing_thread.name}&quot;)<br><br>  sleep(5) # puts the thread in waiting/blocked state for 5 secs.<br>  <br>  print(f&quot;Hello {f_name} {l_name} by {executing_thread.name}&quot;)<br><br><br><br>thread = Thread(<br>  name = &quot;CustomThread&quot;, # optional param if not provided name will be Thread-x<br>  target = task, # A Callable (function) which is gonna be executed by Thread<br>  args = (&quot;Uncle John&quot;,), # positional arguments to be passed to target function<br>  kwargs = {&quot;l_name&quot;:&quot;Uncle John&quot;} # positional arguments to be passed to target function<br>)<br><br># The thread is created and task is also assigned but hasn&#39;t start working yet<br><br>thread.start() # this will start the `CustomThread` <br><br>print(&quot;Here main thread continues its execution.&quot;)<br><br>executing_thread = current_thread()<br><br>print(f&quot;Message by {executing_thread.name}&quot;)<br><br>  </pre><p>Another way of creating the thread is using Inheritance, Let&#39;s see how</p><pre>from threading import Thread, current_thread<br>from time import sleep<br><br>class MyClass(Thread): # inherited the Thread class<br>  def __init__(self, thread_name:str) -&gt; None:<br>    super().__init__(name = thread_name) # invoking Thread class constructor<br>  <br>  @staticmethod<br>  def task(f_name:str, l_name:str) -&gt; None:<br>    &quot;&quot;&quot;<br>       This is a simple function which greets the provided name<br>       :param:<br>          f_name -&gt; a string of any length<br>          l_name -&gt; a string of any length<br>       :return:<br>          None -&gt; Simply nothing<br>    &quot;&quot;&quot;<br>  <br>    executing_thread = current_thread() # return the current thread object<br>  <br>    print(f&quot;Execution of task is started by {executing_thread.name}&quot;)<br><br>    sleep(5) # puts the thread in waiting/blocked state for 5 secs.<br>  <br>    print(f&quot;Hello {f_name} {l_name} by {executing_thread.name}&quot;)<br><br># overriding the run method is equal to assigning the target<br>def run(self) -&gt; None:<br>  &quot;&quot;&quot;<br>    whatever method or function you invoke in this method will be executed by<br>    a new thread.<br>    <br>    By this way you may assign multiple tasks to a single thread<br>  &quot;&quot;&quot;<br>  self.task(&quot;Uncle&quot;,&quot;John&quot;)<br>  self.task(&quot;Uncle&quot;,&quot;Bob&quot;)<br><br><br>my_object = MyClass(&quot;CustomThread&quot;) # The Thread is created, isn&#39;t it so simple<br><br>my_object.start() # this start execution of your task using a new Thread</pre><p><strong>Summary</strong></p><p>To sum it up, in Python, threading is like having multiple workers (threads) doing different jobs at the same time. The program creates a custom thread to perform a specific task concurrently with the main thread. Each thread works independently, allowing the main thread to continue its own tasks. Threading is a handy tool to make programs faster by multitasking effectively.</p><p>Related Video <a href="https://www.youtube.com/watch?v=GCsCnBnXly8">https://www.youtube.com/watch?v=GCsCnBnXly8</a></p><p><strong>Official Website</strong> <a href="https://pythonbricks.pythonanywhere.com/">https://pythonbricks.pythonanywhere.com/</a></p><p><strong>Youtube Channel</strong> <a href="https://www.youtube.com/@PythonBricks">https://www.youtube.com/@PythonBricks</a></p><p><strong>Telegram</strong> <a href="https://t.me/pythonbricks">https://t.me/pythonbricks</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc663e27d98c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/speed-boost-how-multi-threading-makes-your-programs-faster-fc663e27d98c">Speed Boost: How Multi-Threading Makes Your Programs Faster</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Exploration of Argument Types in Python]]></title>
            <link>https://blog.stackademic.com/a-comprehensive-exploration-of-argument-types-in-python-d16db31e33be?source=rss-8e18ee382c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16db31e33be</guid>
            <category><![CDATA[basic-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[arguments-in-python]]></category>
            <category><![CDATA[python-functions]]></category>
            <category><![CDATA[learn-basic-python]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 10:11:18 GMT</pubDate>
            <atom:updated>2023-11-28T06:57:51.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gmnyb-vtqJJwn0rB" /><figcaption>Photo by <a href="https://unsplash.com/@ralexnder?utm_source=medium&amp;utm_medium=referral">Alex Chumak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Python programming, knowing about function arguments is crucial for writing effective code. There are seven types of arguments, each with its own purpose, making Python functions flexible. In this article, we’ll explore these argument types, highlighting their unique features and the best ways to use them.</p><p><strong>Positional/Regular Arguments</strong></p><ul><li>These are the most common type of arguments, defined by their position in the function call.</li><li>The order in which arguments are provided during the function call must match the order in which they are declared in the function definition.</li></ul><pre>def add_numbers(x,y):<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       x -&gt; a number type value which can be passed as positional or keyword<br>       y -&gt; a number type value which can be passed as positional or keyword<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return x+y<br><br>result = add_numbers(10,20) # 10 will be assigned to x and 20 to y</pre><p><strong>Keyword Arguments</strong></p><ul><li>Identified by the use of explicit keywords, these arguments allow for the specification of values based on parameter names.</li><li>This provides clarity and flexibility in function calls, as the order of the arguments becomes irrelevant.</li></ul><blockquote>When using a keyword argument in Python, make sure you don’t have any regular (positional) arguments coming after it. If you do, it will lead to a syntax error.</blockquote><blockquote>Ensure that each argument receives only one value to avoid confusion and errors.</blockquote><pre>def add_numbers(x:int|float, y:int|float) -&gt; int|float:<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       x -&gt; a number type value which can be passed as positional or keyword<br>       y -&gt; a number type value which can be passed as positional or keyword<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return x+y<br><br>result = add_numbers(y = 10, x = 20) # 10 will be assigned to &quot;y&quot; and 20 to &quot;x&quot;<br><br># error will be raised since 10 is already assigned to &quot;y&quot; and using keyword<br># argument we are again attempting to assign value to &quot;y&quot;<br>result = add_numbers(10 , y = 20)<br><br><br># error will be raised since the positional argument is following the keyword argument<br>result = add_numbers(y = 10, 20) <br><br># will work fine<br>result = add_numbers(y = 10, 20)<br></pre><p><strong>Default Arguments</strong></p><ul><li>Default values are assigned to parameters, allowing the function to be called without explicitly providing a value for those parameters.</li><li>This enhances the usability of the function by offering a default behaviour when specific values are not supplied.</li></ul><blockquote>If you set a default value for an argument in Python, be careful not to have any other regular (positional) arguments coming after it. If you do, it will cause a syntax error.</blockquote><pre># here both x and y are having default values<br>def add_numbers(x:int|float = 0, y:int|float = 0) -&gt; int|float:<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       x -&gt; a number type value which can be passed as positional or keyword<br>       y -&gt; a number type value which can be passed as positional or keyword<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return x+y<br><br>result = add_numbers() # &quot;x&quot; will have 0 and &quot;y&quot; will have 0<br>result = add_numbers(10) # &quot;x&quot; will have 10 and &quot;y&quot; will have 0<br>result = add_numbers(y = 10) # &quot;x&quot; will have 0 and &quot;y&quot; will have 10<br>result = add_numbers(10, 20) # &quot;x&quot; will have 10 and &quot;y&quot; will have 20</pre><p><strong>Args (Arbitrary Positional Arguments)</strong></p><ul><li>Denoted by the * symbol before the parameter name, args allow the function to accept a variable number of positional arguments.</li><li>This enables the handling of an arbitrary number of arguments within the function.</li></ul><blockquote>Args stores all given arguments in a tuple</blockquote><pre>def add_numbers(*args) -&gt; int|float:<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       any number of positional arguments can be accepted<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return sum(args)<br><br>result = add_numbers() # will work fine<br>result = add_numbers(10,20,30) # will work fine<br></pre><p><strong>Kwargs (Arbitrary Keyword Arguments)</strong></p><ul><li>Marked by the ** symbol, kwargs enable the function to accept an arbitrary number of keyword arguments.</li><li>This provides a dynamic and adaptable approach to handling additional named parameters.</li></ul><blockquote>Kwargs stores all given arugments in a dictionary</blockquote><pre>def add_numbers(**kwargs) -&gt; int|float:<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       any number of keyword arguments can be accepted<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return sum(kwargs.values())<br><br>result = add_numbers(10,20,30) # will raise an error<br>result = add_numbers(a=10,b=20,c=30) # will work fine</pre><p><strong>Positional-Only or Forced Positional Arguments:</strong></p><ul><li>Introduced in Python 3.8, this argument type restricts the usage of parameters to positional arguments only.</li><li>This ensures that the function is called with positional arguments exclusively, enhancing code clarity.</li><li>Marked by / symbol, Every argument before / will be considered as positional only.</li></ul><blockquote>You can not assign default value to any argument which is declared positional only</blockquote><pre>def add_numbers(x,y,/,z) -&gt; int|float:<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       x -&gt; a number type value which can be passed as positional only<br>       y -&gt; a number type value which can be passed as positional only<br>       z-&gt; a number type value which can be passed as positional or keyword<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return x + y + z<br><br>result = add_numbers(10,20,30) # will fine<br>result = add_numbers(a=10,b=20,c=30) # will raise error<br>result = add_numbers(10,20,c=30) # will work fine<br></pre><p><strong>Keyword-Only or Forced Keyword Arguments</strong></p><ul><li>This argument type mandates that parameters must be specified using keywords during the function call.</li><li>It offers control over how arguments are passed, preventing ambiguity and enhancing code readability.</li><li>Marked by *symbol, Every argument before *will be considered as keyword only.</li></ul><pre>def add_numbers(x,y,*,z) -&gt; int|float:<br>  &quot;&quot;&quot;  <br>    This function adds the given numbers<br>    :params:<br>       x -&gt; a number type value which can be passed as positional or keyword<br>       y -&gt; a number type value which can be passed as positional or keyword<br>       z-&gt; a number type value which can be passed as keyword only<br>    :return:<br>       A number type value<br>  &quot;&quot;&quot;<br>  return x + y + z<br><br>result = add_numbers(10,20,30) # will raise error<br>result = add_numbers(a=10,b=20,c=30) # will work fine<br>result = add_numbers(10,20,c=30) # will work fine</pre><p><strong>Lambda Arguments</strong></p><p>Above studied all types of arguments can be used with lambda functions also.</p><pre># Positional Arguments<br>add_numbers = lambda x,y:x+y<br>result = add_numbers(10,20)<br><br># Keyword Arguments<br>add_numbers = lambda x,y:x+y<br>result = add_numbers(x=10,y=20)<br><br># Default Arguments<br>add_numbers = lambda x=0,y=0:x+y<br>result = add_numbers()<br><br># Args<br>add_numbers = lambda *args:sum(args)<br>result = add_numbers(1,2,3,4,5)<br><br># Kwargs<br>add_numbers = lambda **kwargs:sum(kwargs.values())<br>result = add_numbers(a=1,b=2,c=3)<br><br># Positional Only<br>add_numbers = lambda x,y,/,z:x+y+z<br>result = add_numbers(1,2,3)<br><br># Keywords Only<br>add_numbers = lambda x,y,*,z:x+y+z<br>result = add_numbers(1,2,z=3)<br></pre><p><strong>Conclusion</strong></p><p>In wrapping up, understanding these seven types of arguments in Python empowers developers to write clear, flexible, and neat code. By using each type thoughtfully based on what’s needed, programmers can make their Python functions strong and easy to understand.</p><p><strong>Related Video Tutorial </strong><a href="https://www.youtube.com/watch?v=A3DVHnFOKFY">https://www.youtube.com/watch?v=A3DVHnFOKFY</a></p><p><strong>Official Website</strong> <a href="https://pythonbricks.pythonanywhere.com/">https://pythonbricks.pythonanywhere.com/</a></p><p><strong>Youtube Channel</strong> <a href="https://www.youtube.com/@PythonBricks">https://www.youtube.com/@PythonBricks</a></p><p><strong>Telegram</strong> <a href="https://t.me/pythonbricks">https://t.me/pythonbricks</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16db31e33be" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/a-comprehensive-exploration-of-argument-types-in-python-d16db31e33be">A Comprehensive Exploration of Argument Types in Python</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocols in Python]]></title>
            <link>https://medium.com/@mailmeastushar/protocols-in-python-de64dc8ba2db?source=rss-8e18ee382c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/de64dc8ba2db</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 18:28:28 GMT</pubDate>
            <atom:updated>2022-11-30T18:31:26.056Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have heard about the <a href="https://docs.python.org/3/library/abc.html"><strong>Abstract classes</strong></a><strong>, </strong>you will be a quick grabber.</p><p>Protocols are the best way to make the methods, functions, or classes follow a set of rules (introduced in the <strong>3.8 </strong>version of python).</p><p>In other words, Protocols are used to structure the sub-types/annotates/derives</p><p>Protocol class can be imported from python’s standard module named <a href="https://docs.python.org/3/library/typing.html"><strong>typing</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*fRNkher9keNdL3r_grza3A.png" /></figure><p>Let’s define a basic <a href="https://andrewbrookins.com/technology/building-implicit-interfaces-in-python-with-protocol-classes/">Protocol</a> to be used for structuring a sub-type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*rwZsR8oV5BvFJW8WcGciYg.png" /></figure><p>Tools is an enumerate class to hold the possible constants that can be provided as an argument to <strong>burn or smash</strong> method</p><p><strong>Kill </strong>is a Protocol class that will tell its annotated/derived function/class to provide an object which should have <strong>smash and burn.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*7vsIV2TDnTUrzR4ozaIIGA.png" /></figure><p>Now every call to the <strong>kill_mosquito</strong> function suggests providing an object which follows the Protocol defined rules.</p><p><strong>Conclusion</strong></p><p>Protocols help in writing scalable and understandable code, as the code becomes lengthy it becomes challenging to understand.</p><p>Protocols will be proved as heroes in those kinds of situations.</p><p><strong>Further related articles</strong></p><p><a href="https://opensource.com/article/19/9/zopeinterface-python-package">Interface using zope</a>, <a href="https://www.scaler.com/topics/abstract-class-in-python/">Abstract Classes</a></p><p><strong>Official Website</strong> <a href="https://pythonbricks.pythonanywhere.com/">https://pythonbricks.pythonanywhere.com/</a></p><p><strong>Youtube Channel</strong> <a href="https://www.youtube.com/@PythonBricks">https://www.youtube.com/@PythonBricks</a></p><p><strong>Telegram</strong> https://t.me/pythonbricks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de64dc8ba2db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>