<?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 Subhanshu goel on Medium]]></title>
        <description><![CDATA[Stories by Subhanshu goel on Medium]]></description>
        <link>https://medium.com/@sanshugoel?source=rss-b871f08a3401------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jjMhlTrsO02qzmCyYMz2hA.png</url>
            <title>Stories by Subhanshu goel on Medium</title>
            <link>https://medium.com/@sanshugoel?source=rss-b871f08a3401------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:57:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanshugoel/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[Debunking Meditation]]></title>
            <link>https://medium.com/@sanshugoel/debunking-meditation-e44a4f11c8af?source=rss-b871f08a3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44a4f11c8af</guid>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[meditation]]></category>
            <dc:creator><![CDATA[Subhanshu goel]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 12:05:33 GMT</pubDate>
            <atom:updated>2023-04-16T12:05:33.954Z</atom:updated>
            <content:encoded><![CDATA[<p>I have heard people saying, Meditation is where you stop all thoughts and focus on breathing. And then complain about how tough it is to do meditation.</p><blockquote>Whenever I close my eyes. My mind just wanders away.</blockquote><blockquote>Meditation is so frustrating. I simply cannot focus on my breath. There are plenty of things on my mind that I have to cater to.</blockquote><p>Well, you simply cannot stop yourself from thinking¹. Meditation doesn’t ask you to do to this, neither you should expect it from yourself. Before moving on to meditation. I want to clear a couple of things.</p><ol><li>Consciously, you cannot focus on one thing constantly. All you can do is redirect your attention from one object to the other.</li><li>The breathing in “Focus on breathing” is breath at a natural rhythm. Don’t try to force it.</li></ol><p>Now, back to meditation.<strong> Meditation</strong> is a practice where you <strong>train your mind</strong> to focus on an object instead of making it jump from thought to thought or worry to worry.</p><p>How do you do it? Simply, sit down and “try” to focus on breath. Make an attempt to discern the time when you inhale and when you exhale. The sensation of breath can be observed any place, from nose to stomach. Of course, as you try to do that, your mind will wander off. In that case, <strong>when you realize your mind has wandered off, simply acknowledge it and move your attention back to the breath.</strong></p><p>That’s it, you don’t have to punish yourself because your mind wandered off, but instead commend when you awake from mind wandering. This will lead to a positive feedback loop that will further motivate your subconscious to quickly discern when your mind wanders away.</p><p>After repeatedly doing this for 10–15 minutes for some weeks. You will observe noticeable differences in your attention span and your worries will reduce.</p><p>References</p><p>[1] <a href="https://www.utwente.nl/en/ces/sacc/well-being/downloads/the-pink-elephant.pdf">https://www.utwente.nl/en/ces/sacc/well-being/downloads/the-pink-elephant.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e44a4f11c8af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python slice indices and their derivatives]]></title>
            <link>https://medium.com/@sanshugoel/python-slice-indices-and-their-derivatives-a3bde886c5c5?source=rss-b871f08a3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3bde886c5c5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bisect]]></category>
            <category><![CDATA[slicing]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Subhanshu goel]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 17:08:52 GMT</pubDate>
            <atom:updated>2023-03-04T17:08:52.136Z</atom:updated>
            <content:encoded><![CDATA[<p>I was surprised to see the result when I ran</p><pre>from bisect import bisect_left<br><br>arr = [1,2,3,4]<br><br>ind = bisect_left(arr,3)<br><br>print(ind) #2</pre><p>The documentation for the function reads¹ :</p><blockquote>If x is already present in a, the insertion point will be before (to the left of) any existing entries.</blockquote><p>According to that logic, the value of ind should be 1 not 2! But <strong>slices</strong> and <strong>insertion points</strong> in Python don’t work the way one might think.</p><pre> +---+---+---+---+---+---+<br> | P | y | t | h | o | n |<br>   +   +   +   +   +   +<br>   0   1   2   3   4   5</pre><p>Use them like this ^ and you are in for a surprise.</p><p>Instead, what slices do is they cut between characters and create indices there.</p><p>Like this²</p><pre> +---+---+---+---+---+---+<br> | P | y | t | h | o | n |<br> +---+---+---+---+---+---+<br> 0   1   2   3   4   5   6<br>-6  -5  -4  -3  -2  -1</pre><p>Hence, what bisect_left([1,2,3,4],3) does it</p><pre> +---+---+---+---+<br> | 1 | 2 | 3 | 4 |<br> +---+---+---+---+<br> 0   1   2   3   4</pre><p>And then return 2. (3 with bisect_right).</p><p>Conclusion? Next time you do arr[2:10], string[4:] or bisect_left(arr,99). Remember that you are cutting space between elements, not using the element’s index.</p><p>[1] <a href="https://docs.python.org/3/library/bisect.html#bisect.bisect_left">https://docs.python.org/3/library/bisect.html#bisect.bisect_left</a></p><p>[2] <a href="https://docs.python.org/3/tutorial/introduction.html">https://docs.python.org/3/tutorial/introduction.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3bde886c5c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I wish JS error handling were better]]></title>
            <link>https://medium.com/@sanshugoel/i-wish-js-error-handling-were-better-acb7ce68ebac?source=rss-b871f08a3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb7ce68ebac</guid>
            <dc:creator><![CDATA[Subhanshu goel]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 11:59:46 GMT</pubDate>
            <atom:updated>2022-12-27T15:05:27.445Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been working with JS for quite some time, and recurrently I have found myself feeling uneasy while dealing with exceptions in JavaScript. There isn’t an ergonomic solution in my sight.</p><p>Example:</p><pre>function speaker():<br>	try {<br>		const voice = new Voice()<br>		voice.say(“Hello”)<br>	} catch(error) {<br>		console.error(error)<br>}</pre><p>In case, any exception raised cannot catch by its type. Unless I do some Kung-fu, i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uzwgt_UvRlXW7DIPgSS2HQ.png" /></figure><p>Even though this may look fine, I would say it’s not good enough. A modern language should offer better ways to handle errors.</p><p>But things don’t end there. Given the state of JS libraries, there might or might not be well-defined <strong>error classes, </strong>and if we go around and check the error objects attribute. The convention is to look at message attribute of the error.</p><pre>function speaker():<br> try {<br>  const voice = new Voice()<br>  voice.say(&quot;Hello&quot;)<br> } catch(error) {<br>  console.error(error)<br>  if (error.message === &#39;specific message&#39;) {<br>   // Do stuff<br>  }<br>}</pre><p>Inability to catch specific errors easily and repetitively finding myself clueless about how to handle a specific error case makes me miss error handling in Rust or even Python.</p><p>In <strong>Python</strong>, we create a class that is inherited from a standard class Exception and build moreover. Catching an error for any specific issue is as simple as it can be.</p><pre>try:<br>  x = int(input(&quot;Please enter a number: &quot;))<br>except ValueError:<br>  print(&quot;Oops!  That was no valid number.  Try again...&quot;)</pre><p>[1] <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">https://docs.python.org/3/tutorial/errors.html#handling-exceptions</a></p><p>Furthermore, if we want to segregate the error handling logic, or collectively handle it. We add another except and list all the error within.</p><pre>try:<br>  x = int(input(&quot;Please enter a number: &quot;))<br>except ValueError:<br>  print(&quot;Oops!  That was no valid number.  Try again...&quot;)<br>except except (RuntimeError, TypeError, NameError):<br>  pass</pre><p>Rust goes one step ahead — yeah I know Rust belongs to a different spectrum but please — and has the concept of <strong>recoverable errors</strong> and <em>unrecoverable errors</em>.</p><p>The way of handling <strong>Recoverable Error</strong> is quite similar to <strong>JavaScript, </strong>but since it is a <em>statically typed language</em>, we can reason with the return type. Furthermore, using pattern matching, it is possible to narrow down the error.</p><pre>use std::fs::File;<br>use std::io::ErrorKind;<br><br>fn main() {<br>    let greeting_file_result = File::open(&quot;hello.txt&quot;);<br><br>    let greeting_file = match greeting_file_result {<br>        Ok(file) =&gt; file,<br>        Err(error) =&gt; match error.kind() {<br>            ErrorKind::NotFound =&gt; match File::create(&quot;hello.txt&quot;) {<br>                Ok(fc) =&gt; fc,<br>                Err(e) =&gt; panic!(&quot;Problem creating the file: {:?}&quot;, e),<br>            },<br>            other_error =&gt; {<br>                panic!(&quot;Problem opening the file: {:?}&quot;, other_error);<br>            }<br>        },<br>    };<br>}</pre><p>[2] <a href="https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#matching-on-different-errors">https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#matching-on-different-errors</a></p><p>Here, using match we catch the error and then use ErrorKind enum to further narrow down the type of error. This gives us specificity.</p><p>Different libraries might describe error differently, but looking at the signature of the function or method. We can reason with error.</p><p>Another example but from Vector module of <strong>Rust</strong>.</p><pre>let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];<br><br>let r = s.binary_search_by(|probe| probe.cmp(&amp;seek));<br>assert!(match r { <br>  Ok(1..=4) =&gt; true, <br>  Err(indx)=&gt; false, <br>});<br></pre><p>[3] <a href="https://doc.rust-lang.org/std/vec/struct.Vec.html#method.binary_search_by">https://doc.rust-lang.org/std/vec/struct.Vec.html#method.binary_search_by</a></p><p>The core problem might be attached to the lack of explicit typing support of <strong>JavaScript. </strong>Then all I can do it to make an appeal to <strong>TypeScript </strong>developers to somehow come up with a better approach for handling errors in JS.</p><p>You are welcome to share criticism or feedback @<a href="/service/mailto:medium.1ccpe@simplelogin.com">medium.1ccpe@simplelogin.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb7ce68ebac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String matching Algorithm Notes — Part 2]]></title>
            <link>https://medium.com/@sanshugoel/string-matching-algorithm-notes-part-2-5b4578eacd31?source=rss-b871f08a3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b4578eacd31</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Subhanshu goel]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 16:12:48 GMT</pubDate>
            <atom:updated>2022-11-29T16:12:48.754Z</atom:updated>
            <content:encoded><![CDATA[<h3>String matching Algorithm Notes — Part 2</h3><h3>Extended Bad Character Algorithm</h3><h3>Useful when Bad Character Rule fails.</h3><ul><li>That happens when the character from T that mismatched exists to the right of mismatched position of P.</li><li>This is common when either the <em>alphabet</em> is small or T contains many small but not exact substrings. Ex: DNA – Alphabet – |4| or Protein where there are too many similar compounds.</li></ul><h3>Logic</h3><ol><li>Store all occurrences of characters occurring in P in an array.</li><li>Whenever pattern P mismatches at its index i against character x of T . Find the rightmost j that is left to the i and so that P[j] = x . Shift the pattern to the right so it aligns with <strong>T’s</strong> x.</li></ol><h3>Benefit</h3><ol><li>Gives larger shift than Bad Character Rule.</li></ol><h3>Pre-processing</h3><h3>1. Time complexity — O(|N|)</h3><h3>2. Space Complexity — O(|N|)</h3><h3>Implementation</h3><h3>Preprocessing</h3><h4>Approach one (Excessive space and time complexity)</h4><ol><li>Take a two-dimensional array with<strong> X </strong>axis equal to size of the alphabet (say 26 for English) and <strong>Y</strong> axis being index of the string <strong>P</strong>.</li><li>Iterate over each element of the pattern and for any position attach it to its location corresponding location on the map of <strong>Alphabet vs Index</strong> .</li></ol><h4>Approach two</h4><ol><li>Create a 2D matrix or a Hashmap consisting of an array of integers.</li><li>Scan the pattern from right to left while keeping track of index, too.</li><li>Map all characters to the column and push the index to the array.</li></ol><pre>cache = {}<br>for char, index in enumerate(P):<br> cache.get(char,[]).push(index)</pre><ul><li>This approach will store indices in <em>descending</em> order.</li><li>Time complexity — O(|P|)</li><li>Space complexity — O(|P|)</li></ul><h3>String Matching</h3><ol><li>Start matching from the right.</li><li>On mismatch with character <strong>x</strong> from T</li><li>Map the char from T and iterate over the inner array to find an index j lower than the current one from P.</li><li>Move P so that P[j] falls under character <strong>x</strong>.</li><li>Restart the matching from right.</li><li>If no occurrence is found, then move the entire pattern P past <strong>x</strong> ‘s position.</li></ol><p>Note: To further optimise binary search can be used to find index in inner array.</p><p>References:</p><p>[1] Gusfield, D., 1997. Algorithms on stings, trees, and sequences: Computer science and computational biology.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b4578eacd31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String matching Algorithm Notes— Part 1]]></title>
            <link>https://medium.com/@sanshugoel/string-matching-algorithm-notes-part-1-e5280f668b8e?source=rss-b871f08a3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5280f668b8e</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Subhanshu goel]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 16:10:32 GMT</pubDate>
            <atom:updated>2022-11-29T16:12:13.129Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bad Character Rule</h3><h3>The aim is to move more than one character when one mismatch occurs.</h3><p>Let’s define the terms,</p><ol><li><strong>P</strong> → Pattern of length <strong>n.</strong></li><li><strong>T → </strong>Text of length <strong>m</strong>. m &gt;= n.</li></ol><p>Assume, that</p><pre>P[k] = x;<br>T[j] = y;<br>P[k] != T[j];</pre><p>Now we will find some i such that P[i] = x; then restart the comparison from left. If we cannot find any i with the condition that P[i] = x then shift whole P pass T[j].</p><p>Let’s define some more terms.</p><ol><li>For any x in the alphabet(Σ), R(x) = j where P[j] equals right most x.</li></ol><p>Note: It collects index for right most x only. We will collect all occurrences in another algorithm called Extended Bad Character Algorithm.</p><h3>Algorithm</h3><ol><li>From right, Collect all alphabets, their position, and store into an array.</li><li>For any alignment of P against T.</li></ol><p>2.1. Scan from right until a mismatch is found as position k in T and i in P as shown in the below diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAH0Jr27v4qLrVNvuCruTw.png" /></figure><p>2.2. At that time, check if move P by distance d = i - R(T(k)) or d = i - R(s). Where T(k) is the mismatched character in T and d &lt; i (d &gt;= 0).</p><p>2.3. Otherwise, move the pattern P by 1 index to the right.</p><h3>Time complexity — O(|P|); |P| being size of Pattern</h3><h3>Space complexity — O(|Σ|); |Σ| being size of alphabet</h3><p>Reference:</p><p>[1] Gusfield, D., 1997. Algorithms on stings, trees, and sequences: Computer science and computational biology.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5280f668b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Decorators : a brief intro with usage examples]]></title>
            <link>https://medium.com/@sanshugoel/python-decorators-a-brief-intro-with-usage-examples-4fcccab67e79?source=rss-b871f08a3401------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fcccab67e79</guid>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[hacker]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[news]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Subhanshu goel]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 10:58:35 GMT</pubDate>
            <atom:updated>2022-09-14T09:12:52.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is a decorator?</h4><p>A decorator is the name used for a software design pattern that allows <strong>behaviour</strong> to be added to a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blKkG4Ga-9ptMsmAXaY3bg.png" /></figure><h4>How decorators works?</h4><p>Decorators wraps the original object which consists of business logic and returns a new object that may or may not be related to the original object. I will clarify this statement in a bit when I explain how we wrap the object.</p><p>They have the similar interface as the wrapped object, i.e., same arguments as that of the wrapped object.</p><p>In python, functions, and classes are first class objects. Meaning, they can be used like variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37059aaf1886c9ace09c299068ae9c76/href">https://medium.com/media/37059aaf1886c9ace09c299068ae9c76/href</a></iframe><p>By the help of this we implement decorator pattern in Python.</p><p>We will write a normal function multiply and wrap it in another function that will print the wrapped function name. This wrapping is what we call decoration. We then return that wrapped function.</p><p><em>Don’t get confused. Look at the code example.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b07e231941ee022c440a0a00f6590d/href">https://medium.com/media/84b07e231941ee022c440a0a00f6590d/href</a></iframe><p>The function named decorator takes any function as the input; Print its name and return backs the function. We apply this function at line 8 where we re-assign the return value of decorator to variable multiply.</p><p>This decoration leads to multiply possessing additional behaviour of printing the function’s name. All of this without changing any code in the function multiply</p><p>Nothing fancy happened, but the idea is clear.</p><p>Remember what I said earlier.</p><blockquote>…returns a new object … may not be related to the original object…</blockquote><p>To demonstrate this, I will create a decorator that substitutes an input function with another function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00c351384575d8bb722d4858b1b1adc1/href">https://medium.com/media/00c351384575d8bb722d4858b1b1adc1/href</a></iframe><p>Here, the input function is totally ignored, and instead we return the add function that operates totally differently from the original logic. This might be helpful in some cases.</p><p>There might be some confusion about when the decorators actually triggers and when the function is called. Moreover, can we access the function parameters?</p><p>Read on to get the answers (Heed carefully to comments)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f858331b8bab2652f898c57848c0334a/href">https://medium.com/media/f858331b8bab2652f898c57848c0334a/href</a></iframe><p>Here at line 5 we create a new function <em>print_args</em> that takes the same number of arguments as the decorated function and internally calls it. Instead of returning the decorated function back, we return the new function.</p><p>So on the line 13 when the function add is invoked. print_args is the one that runs thus voilà! We get access to the <strong>arguments.</strong></p><p><em>Note: There can be times when we don’t know about the number, and/or name of arguments. At that time, we can use </em><em>*args, **kwargs as parameters¹.</em></p><p>We can do some exciting stuff using decorator pattern.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/786422e1bc39d1192d2ac6afd51c1ba1/href">https://medium.com/media/786422e1bc39d1192d2ac6afd51c1ba1/href</a></iframe><p>This will deploy runtime type checking for annotated functions. It is not perfect, but it shows how versatile the decorator pattern is.</p><p>Owing to prevalence of the pattern usage in Python. A syntactic sugar was proposed aiming to ease the usage of decorator pattern².</p><blockquote><strong>@</strong></blockquote><p>Using it is simple</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b977a9e58ad72e3fa328b766d67d7021/href">https://medium.com/media/b977a9e58ad72e3fa328b766d67d7021/href</a></iframe><p>Instead of reassigning the function name with result of decorator. We decorate function definition with name of decorator function preceded by syntactic sugar @.</p><p>Comparing it with older snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5765f4425d95655fb089fe4c5bf05d/href">https://medium.com/media/ab5765f4425d95655fb089fe4c5bf05d/href</a></iframe><p>Essentially, decoration of function is communicated during the definition.</p><p>Some doubts may occur about when the decorator executes and replaces the original function.</p><ol><li>When the code is compiled? No, Python is an interpreted language.</li><li>When we call the function? No, we already have the new function returned by the decorator.</li><li>When we import the function/module? Yes, During import time, Python decorates the function and assigns back the evaluation result to the function name itself.</li></ol><p>Moving forward it will be demonstrated how new syntax will increase conciseness, and readability.</p><p>Due to how decorator pattern deals with the decorated object. It doesn’t matter what is being decorated; Be it a function, class, or another decorator. Thus, layers of decorators can be created where each decorator supply distinguished behaviour.</p><p>Assume there are three decorators decorator_1, decorator_2, decorator_3. A function has to be decorated by each.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b21d16d9b0eed30a44181afc34a4884d/href">https://medium.com/media/b21d16d9b0eed30a44181afc34a4884d/href</a></iframe><p>Application order of decorator is from <strong>bottom to top</strong>. Result of decorator_1 is passed to decorator_2, result of decorator_2 to decorator_3 and finally assigned back to the identifier func.</p><p>If compared with 2nd half of the code, temporary reassignments are avoided, thus leading to more concise code. And comparing with 3rd part, I’d say new syntax increases readability.</p><p>Usually, decoration order should not matter as decorator cares less about the function and more about its environment. But since decorators influence input, and output thus cases may occur where a specification should be followed. For example, ordering of middlewares in Django³.</p><p>The way a decorator is implemented, it is just a callable. Owing to that property, decorators can accept parameters too. This can further influence their behaviour.</p><p><em>Note: I am talking about </em><strong><em>decorator</em></strong><em> accepting arguments not the decorated functions. It’s a handy add on.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f894ddd7ed0d194634272f591864dd2c/href">https://medium.com/media/f894ddd7ed0d194634272f591864dd2c/href</a></iframe><p>While creating unit tests, certain tests might need to be skipped based on some condition. unittest module gives a couple of decorators that based on the condition passed will work differently.</p><p>skipIf and skipUnless accept a boolean argument, and a string stating the reason for the corresponding operation. skipif skips the decorated test if expression is True and skipUnless always skips the decorated test unless condition evaluates to True.⁴ Both decorator accept arguments that alter their behaviour.</p><p>Implementing a decorator with parameters requires another function wrapping the decorator with a function that accepts arguments. Sample implementation of skipIf decorator will look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05fabb1019e55a52581dda72e982ff72/href">https://medium.com/media/05fabb1019e55a52581dda72e982ff72/href</a></iframe><p>This just about sums the decorator pattern in Python. Now to real-world applications.</p><h3><strong>Applications of decorators in Python</strong></h3><p>Decorator pattern is ubiquitous in Python. A few applications are stated below.</p><ol><li>Unittests⁴</li><li>Routing in flask⁵</li><li>Django middlewares⁶</li></ol><p>An extra emphasis should be given to Django middlewares. Reason being, the usage of decorator pattern isn’t profound. Developers come across it repetitively, but may not recognize it.</p><p><em>That’s it for today. If you have any feedback, questions, or just want to talk. Mail me at </em><a href="/service/mailto:fones_macgillivray@simplelogin.com">fones_macgillivray@simplelogin.com</a><em>.</em></p><p>[1]<a href="https://book.pythontips.com/en/latest/args_and_kwargs.html">https://book.pythontips.com/en/latest/args_and_kwargs.html</a></p><p>[2] <a href="https://www.python.org/dev/peps/pep-0318/">https://www.python.org/dev/peps/pep-0318/</a></p><p>[3] <a href="https://docs.djangoproject.com/en/3.1/ref/middleware/#middleware-ordering">https://docs.djangoproject.com/en/3.1/ref/middleware/#middleware-ordering</a></p><p>[4] <a href="https://docs.python.org/3/library/unittest.html?highlight=unittest#unittest.skipIf">https://docs.python.org/3/library/unittest.html?highlight=unittest#unittest.skipIf</a></p><p>[5] <a href="https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.route">https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.route</a></p><p>[6] <a href="https://docs.djangoproject.com/en/3.1/topics/http/middleware/">https://docs.djangoproject.com/en/3.1/topics/http/middleware/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fcccab67e79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>