<?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 Rbhanot on Medium]]></title>
        <description><![CDATA[Stories by Rbhanot on Medium]]></description>
        <link>https://medium.com/@rbhanot4739?source=rss-9228d6bf3e8a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mHiK57l8Ogz1a-0J.jpg</url>
            <title>Stories by Rbhanot on Medium</title>
            <link>https://medium.com/@rbhanot4739?source=rss-9228d6bf3e8a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:38:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rbhanot4739/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[Speed up your function and method calls with caching in Python]]></title>
            <link>https://python.plainenglish.io/speed-up-your-function-and-method-calls-with-caching-in-python-118841efc759?source=rss-9228d6bf3e8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/118841efc759</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Rbhanot]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 15:04:03 GMT</pubDate>
            <atom:updated>2024-06-10T10:13:22.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>Speed up function and method calls with caching in Python</h3><h4>Using lru_cache and cached_property to optimize function calls</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lKC6LjWc3RCoGdKVLDVAw.jpeg" /></figure><p>Caching is a technique where you store the results of an expensive operation, either compute or IO-heavy so that for any subsequent calls made for the same operation, you can send the result immediately without having to do the actual work again.</p><p>It is a popular strategy with its use cases spread across the breadth of products, from web browsers to web servers to databases, and can massively improve the overall system performance.</p><p>Comprehensive solutions like <a href="https://redis.io/">Redis</a>, <a href="https://www.memcached.org/">Memcached</a>, etc come with a long list of features where app caches are persistent, distributed fault-tolerant, and highly available.</p><p>However, if your application’s caching requirements are simple enough and do not warrant the additional infrastructure complexity that the above solutions provide, you may always rely on Python’s built-in caching primitives.</p><p>Python’s <a href="https://docs.python.org/3/library/functools.html">functools</a> module from the standard library provides a suite of useful tools for functional programming. Among these, <a href="https://docs.python.org/3/library/functools.html#functools.cached_property">Cached Property</a> and <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache">LRU cache</a> are the two that we will explore in this post.</p><p>Understanding how and when to use these tools can help optimize the performance of your code by caching the results of expensive function or method calls and improve the overall application experience.</p><h3>Cached Properties</h3><p>A Cached property behaves much like a regular property, with the benefit that the return value of the underlying method is cached, i.e. only the first call to the cached property will execute the underlying method code, all subsequent calls will return the cached result, which can save time if the method is doing some heavy computation or network/disk I/O.</p><p>However, before jumping onto cached properties, let’s see how regular properties work with the help of the following example:</p><p>We define a class Data that takes a list of integers as its argument and has a method normal_p that returns the sum of squares of the numbers passed to the class. Then we turn this method into a <em>property</em> by decorating it with an appropriately named decorator property .</p><pre>class Data:<br><br>    def __init__(self, nums: list[int]):<br>        self.nums = nums<br><br>    @property<br>    def normal_p(self):<br>        print(&quot;normal property&quot;)<br>        return sum((i*i for i in self.nums))<br><br><br><br>obj = Data(list(range(1, 10)))<br>print(vars(obj)) <br>obj.normal_p<br>obj.normal_p<br>print(vars(obj))</pre><p>And we get the following result when we run the above code</p><pre><br>{‘nums’: [1, 2, 3, 4, 5, 6, 7, 8, 9]}<br>normal property<br>normal property<br>{‘nums’: [1, 2, 3, 4, 5, 6, 7, 8, 9]}</pre><p>Let&#39;s quickly summarise a few things about properties</p><ul><li>A property is a way to transform a method of a class into what <em>looks like</em> a normal instance attribute.</li><li>The property runs the underlying method every time we access it.</li><li>Properties are internally implemented as <a href="https://docs.python.org/3/howto/descriptor.html">Descriptors</a> and that’s why I said it looks like an instance attribute because, under the hood, it&#39;s a descriptor instead. We can also confirm the same by looking at the instance dictionary (vars(object)) in the above example, that normal_p is not part of obj.__dict__ because it is not a regular instance attribute.</li><li>Every time you access the property, it calls the __get__ on a descriptor that in turn calls the method.</li><li>By default, properties are <em>read only</em> unless you specify a setter for them by using property.setter. So doing obj.normal_p = 100 in the above example would raise AttributeError: can’t set attribute ‘normal_p’ exception.</li></ul><p>With that basic understanding of properties, we can now start exploring the behavior of cached properties. For simplicity, I will use the same example from above with some changes, i.e. instead of decorating the method with `property` this time we will use functools.cached_property</p><pre>import functools  <br>  <br>  <br>class Data:  <br>  <br>    def __init__(self, nums: list[int]):  <br>        self.nums = nums  <br>  <br>    @functools.cached_property  <br>    def cached_p(self):  <br>        print(&quot;cached property&quot;)  <br>        return sum((i*i for i in self.nums))  <br>  <br>  <br>  <br>obj = Data(list(range(1, 10)))  <br>print(vars(obj))  <br>print(obj.cached_p)  <br>print(obj.cached_p)<br>print(vars(obj))  <br>obj.cached_p = 100  <br>print(vars(obj))</pre><p>And here is the output of the above code</p><pre>{&#39;nums&#39;: [1, 2, 3, 4, 5, 6, 7, 8, 9]}<br>cached property<br>285<br>285<br>{&#39;nums&#39;: [1, 2, 3, 4, 5, 6, 7, 8, 9], &#39;cached_p&#39;: 285}<br>{&#39;nums&#39;: [1, 2, 3, 4, 5, 6, 7, 8, 9], &#39;cached_p&#39;: 100}</pre><p>Few interesting things are happening here in contrast to regular properties, so let’s go over it one by one</p><ul><li>We don’t see cached_p in the obj.__dict__ which isn’t surprising (at least for now) because this is still a property (cached one) and not an instance attribute.</li><li>When we accessed the property for the first time using print(obj.cached_p) we saw its value printed but also the message cached property printed which means the underlying method was called.</li><li>When we accessed the property the second time, its value got printed but this time no message was printed, which might make us think that the property was cached (it is but not in the conventional sense, as we will see below).</li><li>When we inspect the contents of the object dictionary, we see it now has an attribute called cached_property and this in fact is the most interesting aspect of cached properties which makes the whole cache thing work( I will come to that in a few seconds).</li><li>Last we see we were able to override the value of cached_p which is unlike regular properties and should be surprising at first.</li></ul><p>Let’s see the above example once again with one change</p><pre>import functools  <br>  <br>  <br>class Data:  <br>  <br>    def __init__(self, nums: list[int]):  <br>        self.nums = nums  <br>        self.cached_p = &quot;hello&quot;    # we added an attribute with the same name <br>  <br>    @functools.cached_property  <br>    def cached_p(self):  <br>        print(&quot;cached property&quot;)  <br>        return sum((i*i for i in self.nums))  <br>  <br>  <br>  <br>obj = Data(list(range(1, 10)))  <br>print(vars(obj))  # {&#39;nums&#39;: [1, 2, 3, 4, 5, 6, 7, 8, 9], &#39;cached_p&#39;: &#39;hello&#39;}<br>print(obj.cached_p)    # hello</pre><p>This time we did not see the method cache_p invoked, does that mean cached_property did not work? The answer is yes but to understand <em>why</em> we need to understand what happens when we decorate a method with cached_property decorator</p><ul><li>The cached_property decorator is trigged on the first .(dot) access, i.e when you do obj.cached_p.</li><li>It checks to see if there exists an instance attribute with the same name as that of the decorated method and if there is the decorator simply returns its value (see <a href="https://github.com/python/cpython/blob/3.12/Lib/functools.py#L993">source</a>). This is the reason that in the second example when we defined self.cached_p = “hello” the cached property cached_p never ran which was evident from the fact that cached_p was already in the obj.__dict__ and there was no cached_property message printed.</li><li>If there is no instance attribute with the same name as that of the decorated method, the decorator calls the method (just like a regular property), gets its return value if any, and then adds an attribute with the same name to the instance dictionary (<em>this is the magical part</em>).</li><li>Next time you do the <em>dot</em> access to the cached_property, it is being fetched from obj.__dict__ and there is no descriptor lookup happening (since a cached_property is a non-data descriptor and instance dictionaries take priority over non-data descriptors).</li><li>Now since it is a normal instance attribute and no longer a descriptor, you can set it as well and there will be no errors !!</li></ul><p>As we have seen above, there is no magic sauce behind cached properties, and they are pretty easy to understand as well; however, you have to be careful about a few things to avoid surprises</p><ul><li>Since the cached_property descriptor is triggered on the <em>first dot access only</em>, if the underlying method is using some instance attributes that can change over the lifetime of the object, the cached property might be stale or incorrect.</li></ul><pre>print(obj.cached_p)    # prints 285<br>obj.nums = [100, 200]    # we changed the value of nums<br>print(obj.cached_p)    # still prints 285 which means property is now stale</pre><ul><li>A cached_property does not work with the methods that take arguments(<a href="https://github.com/python/cpython/blob/3.12/Lib/functools.py#L995)">source</a>).</li><li>The cached_property cannot work on the classes that do not expose __dict__ (for example classes with __slots__ attribute) or where __dict__ is not mutable (e.g., metaclasses where is __dict__ is a read-only proxy to hold the class data). The reason is pretty simple to understand because cached_property adds the attribute to the object dictionary, and if it’s not mutable, then cached_property can’t add the attribute.</li><li>Also important to note is that cached_property is <em>not</em> thread-safe so if multiple threads are trying to access the cached_property the update made by the last thread will persist.</li></ul><h3>What about LRU cache ?</h3><p>While the <a href="https://docs.python.org/3/library/functools.html#functools.cached_property">cached_property</a> decorator exposes a behavior that looks like a cache, the actual API isn’t a cache. To cover that, <a href="https://docs.python.org/3/library/functools.html#module-functools">functools</a> has another tool that behaves like a real cache.</p><p>A <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache">lru_cache</a>(Least Recently Used) can also be used to cache function and method calls and has a bunch of extra features, which makes it a more superior and flexible choice over cached_propertry.</p><p>A lru_cache decorator has the following properties:</p><ul><li>Unlike cached_property it caches the function/method call results along with the arguments with which the function was called.</li><li>Prevents the cache from growing indefinitely by setting a default upper bound of 128. Once the cache is full to its capacity, any new key insertion will result in the eviction of the least recently used. However, you can set the maxsize to None in which case it will grow without bounds (something<em> you should keep in mind</em>).</li><li>Can cache function calls with different argument types separately by setting the typed=True.</li><li>Creates handy instrumentation attributes like cached_parameters, cache_info, cache_clear and __wrapped__ to the original method for introspection purposes.</li><li>Requires the function arguments to be <em>hashable</em> (as the key is to be stored in the dict).</li><li>The lru_cache is size-bound and not time-bound, which means keys in lru_cache are evicted only when the cache reaches its maximum size. So caches with large sizes might have entries that can be old.</li></ul><p>Let’s see it in action by taking an example of one of the first things that comes to mind when we think of recursion: the factorial function</p><pre>def factorial(n):  <br>    return n * factorial(n-1) if n &gt; 0 else 1  <br>  <br>  <br>@functools.lru_cache  <br>def cached_factorial(n):  <br>    return n * factorial(n-1) if n &gt; 0 else 1  <br>  <br>timeit(lambda : factorial(900), number=1000)    # 0.3354 seconds<br>timeit(lambda : cached_factorial(900), number=1000)    #   0.0004 seconds<br><br>print(cached_factorial.cache_info())    # CacheInfo(hits=999, misses=1, maxsize=501, currsize=1)</pre><p>So we created two versions of the same function with just one difference; the second one was decorated with lru_cache and then we ran these functions 1000 times each and recorded their runtime.</p><p>As you can see, the difference between the runtime of cached and non-cached versions above is astonishing, and the reason for this is the lru_cache, the first call to cached_factorial had to do the computations to calculate the factorial of 900 (i.e. it had to make all the recursive calls till 0) but each of these recursive calls is being cached as well. The subsequent 999 calls wouldn’t have to do any computation because the result was already in the cache, and cached_factorial.cache_info() confirms that as well.</p><p>Similar to cached_property you can also use lru_cache to cache methods as well.</p><p>Here is a simplified version of a real-world use case where you might want to implement an LDAP-based authorization for your application where you want to check a user’s group membership.</p><p>Group information for a user is something that doesn’t change very frequently in most setups, so we don’t need to do a network call to fetch a user’s groups from LDAP on every request and cache this information for the next x hours.</p><p>We are setting the size of the cache to 256 to do two things here, have an upper bound so that the cache doesn’t grow indefinitely and second, cache the most frequent users only.</p><pre>class LDAPAuth:  <br>    def __init__(self, server: str):  <br>        self.ldap_server = LDAPServer(server)<br>        self.allowed_groups = {&#39;group1&#39;, &#39;group2&#39;}  <br>  <br>    @functools.lru_cache(maxsize=256)  <br>    def check_group_membership(self, user: str):  <br>        # assuming the below function call makes a network call internally  <br>        user_groups: set = set(self.ldap_server.get_user_groups(user))  <br>        return bool(user_groups.intersection(self.allowed_groups))</pre><h3>LRU Cache with hashable classes</h3><p>One of the major drawbacks of using a cache_property is that it can become invalid or stale if the underlying attributes change.</p><p>The lru_cache with a regular class would suffer from the same drawback as well !!</p><p>However, we can fix this issue by defining overriding __eq__ and __hash__ for the class. But before we dive into how we can fix this issue; let&#39;s first try to understand how__eq__ and __hash__ works in Python.</p><h4>Equality and Hashability in Python</h4><p>Equality in Python (and in general in programming) means whether two entities/objects compare equal to each other or not and the same goes for inverse equality, i.e., <em>not equal </em>operation as well. There are a few key points when talking about equality in Python.</p><ul><li>Equality in Python is implemented by the special __eq__ method.</li><li>The default implementation of __eq__ uses the identity (x is y) of the objects to determine if two objects are equal or not. So with default behavior, they can&#39;t be considered equal if two objects do not point to the same memory location.</li><li>For user-defined classes, objects only compare True to themselves, i.e. x != y will always be True with the default implementation.</li><li>The equality operation operation should only be performed on objects of the same type. If the types of operands do not match, the method should return the built-in singleton object NotImplemented</li></ul><p>Hashing in computer science is the technique of passing an input value of variable size through a <em>one-way </em>function (conveniently called a hash function) to produce fixed-size values.</p><p>One of the biggest and best-known use cases of hashing is the <a href="https://en.wikipedia.org/wiki/Hash_table">Hash tables</a> ; a data structure specially designed for faster lookups. One of the required properties of hash tables is that the keys must be hashable, meaning running the key through the hash function should always give the same value. So what this also implies is that a mutable object cannot be used as a key in hash tables.</p><p>Let’s come back to Python now and see how hashing works here.</p><ul><li>Implemented by __hash__defined in the class.</li><li>called by builtin hash() and containers like set, dict, frozenset when adding keys to them.</li><li>If two objects compare equal, they must have the same hash value, i.e., if x == y is True then hash(x) == hash(y) should also be True.</li></ul><p>Since lru_cache uses dictionaries under the hood to store function calls and since dictionaries are an implementation of hash tables in Python, the keys to the dictionaries must be hashable.</p><p>Let’s see a code example and unravel a few more things</p><pre>import functools  <br>  <br>  <br>class Data:  <br>  <br>    def __init__(self, nums: list[int]):  <br>        self.nums = nums  <br>  <br>    def __eq__(self, other):  <br>        if not isinstance(self, type(other)):  <br>            return NotImplemented  <br>        return self.nums == getattr(other, &quot;nums&quot;)  <br>  <br>    def __hash__(self):  <br>        return hash((tuple(self.nums), ))  <br>  <br>    @functools.cached_property  <br>    def cached_p(self):  <br>        print(&quot;cached property&quot;)  <br>        return sum((i*i for i in self.nums))  <br>  <br>    @functools.lru_cache  <br>    def cached_m(self):  <br>        print(&quot;lru_cached method&quot;)  <br>        return sum((i*i for i in self.nums))  <br>  <br>  <br>a = Data(list(range(1, 10)))  <br>print(a.cached_m())    # 285  <br>print(a.cached_p)    # 285  <br>a.nums = [100, 200, 300]  <br>print(a.cached_m())    # 140_000, its updated to reflect the change in underlying attribute<br>print(a.cached_p)    # still 285 i.e. property is stale</pre><p>We can see that the cache_p which is decorated with cached_property became stale and gave the old result after we changed the value of nums attribute of the class, and this can lead to bugs.</p><p>However, thanks to the __hash__ method defined in the class; the cache_m worked as expected and gave the correct result.</p><p>So every time we invoke cache_m, internally it has to create a key using the arguments with which the method was called (this also includes the object itself a in this case, which was used to make the method call).</p><p>This key creation part internally makes a call to the hash function defined for each of the element’s types, so when we change one of the attributes of our class, the hash will also change, which in turn results in a new key being created and added to the cache.</p><p>But why did it not work without overriding the__hash__ method, i.e. with the default __hash__ implementation. Please recall from above that since the default implementation of __eq__ uses identity to compare objects and the default __hash__ also uses the same id to get the hash value of the object.</p><p>So that means if you add/update an attribute to the object, with the default __eq__ and __hash__ the memory address will never change, so its hash will also not change, which means the new key will not be created, and hence we will keep on getting the old value from the cache.</p><h3>Closing thoughts</h3><p>Now to the final question, should you use cached_property over lru_cache or vice versa?</p><p>Here are a few things to keep in mind that can help you make the right decision based on the functional requirements.</p><ul><li>cached_property does not work with methods that require arguments (the internal descriptor directly calls the method and saves the return value to the instance dictionary). So choose cached_property if the underlying method does not take any arguments; otherwise, use lru_cache the cached methods with arguments.</li><li>The APIs for cached_property and lru_cache are different; if you have an expensive method that does not take any arguments and you want to expose it as an attribute for your user, use cache_property, whereas if you want to preserve the calling semantics just want to cache it use lru_cache.</li><li>A cached_property stores the method result on the class instance, so the lifetime of the cached value is until that object is in scope; as soon as the object goes out of scope, the cached method result will be deleted.</li><li>lru_cache on the other hand stores results at the class level (even though you can not view the actual cache contents as they are not exposed to the user for safety reasons), and it does maintain a reference to the object, so a lru_cache is shared among class objects.</li></ul><p>I am sure there is more to caching in Python, I have only scratched the surface. I hope you found this helpful in understanding how the native two Python caching techniques work and making you more equipped to use these tools in your next project.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=118841efc759" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/speed-up-your-function-and-method-calls-with-caching-in-python-118841efc759">Speed up your function and method calls with caching in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code transformations with Decorators in Python part 3]]></title>
            <link>https://python.plainenglish.io/code-transformations-with-decorators-in-python-part-3-fa71c2890539?source=rss-9228d6bf3e8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa71c2890539</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rbhanot]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 11:55:06 GMT</pubDate>
            <atom:updated>2024-06-08T13:45:13.996Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxjbysaQHi7-vJ5eQFbiJA.jpeg" /></figure><p>In the <a href="https://medium.com/@rbhanot4739/code-transformations-with-decorators-in-python-5d9ed3738115">part</a> 1 and <a href="https://medium.com/@rbhanot4739/code-transformations-with-decorators-in-python-part-2-f3b5666f3248#de01-f35bd4a6649c">part 2 </a>of this series we saw what decorations are, how you can write your own decorators, chaining decorators and a bunch of other things. While that is what you probably need and will meet your requirements most of the time, sometimes there are specific use cases where you need these decorators to be more flexible so that it can be used in multiple different ways.</p><p>In this post I will go through on how you can write decorators that take arguments supplied by the user and then behave accordingly. We will see different ways of constructing such decorators and in the last section I will also cover how you can do <strong><em>meta</em></strong> programming with decorators much more easily as an alternative to using meta classes.</p><h3>High order decorators</h3><p>Parameterized decorators sometimes are also referred to as High order decorators because as you will see shortly there is a layer of wrapping that is needed to transform a regular decorator into a parameterized one.</p><p>Here is an example of a parameterized decorator which repeats a function call x number of times after waiting for a defined time period if the first call to the function errors out or fails for some reason.</p><pre>def repeat(num=3, duration=5):<br>    &quot;&quot;&quot;parameterized decorator to repeat a function call after a certain interval<br><br>    Args:<br>        num: maximum number of retries(default=3)<br>        duration: time to wait in seconds before making next retry(default=5)<br>    &quot;&quot;&quot;<br><br>    def decorator(func):<br>        def inner(*a, **kw):<br>            count = 1<br><br>            while count &lt;= num:<br>                logging.info(f&quot;Attempt: {count} out of {num}&quot;)<br>                try:<br>                    res = func()<br>                    if res:<br>                        return res<br>                except Exception as e:<br>                    logging.info(f&quot;Exception: {e}&quot;)<br><br>                count += 1<br>                time.sleep(duration)<br><br>            raise Exception(&quot;Max attempts reached&quot;)<br><br>        return inner<br>    return decorator<br></pre><p>So you have an outer function (repeat in this case) which is a normal function and takes an arbitrary number of arguments depending on the use case and then inside it you have the actual decorator function. Here is how you use such a decorator</p><pre>@repeat(num=2, duration=3)<br>def do_something():<br> return 1 / random.randint(-6, 6)<br><br>try:<br> print(generate_random_num())<br>except Exception as e:<br> print(e)</pre><p>Again @repeat(num=2, duration=3) is just a syntactic sugar and the actual call under the hood translates to this do_something = repeat(num=2, duration=3)(do_something)</p><p>So basically you are calling the function with the proper arguments and since that function actually returns a decorator, that is what Python uses to decorate the function.</p><p>Now this is all good and works just fine but there is a problem which is everytime you have to use this decorator you need to provide the values for the arguments and can quickly become a nuisance, sometimes you might just want to use this decorator with its default values.</p><p>If you try to use the above repeat decorator in its bare form without providing any values, you will notice it fails and does not work as expected.</p><pre>@repeat<br>def do_something():<br>    return 1 / random.randint(-6, 6)<br><br><br>try:<br>    print(do_something())<br>except Exception as e:<br>    print(e)<br><br>#### Output ####<br>repeat.&lt;locals&gt;.decorator() missing 1 required positional argument: &#39;func&#39;</pre><p>Now this error can be confusing if you don’t understand the actual call behind the syntactic sugar that python is hiding from you. In this case the actual call behind @repeat is do_something = repeat(do_something) .</p><p>Confused ??</p><p>Well if you think Python does not know its a high order decorator or a regular one, as soon as it sees the @ mark it just treats it like a regular decorator.</p><p>Now if you try to understand the error above once again you will know what it means and why it happens. In order to fix this we have to talk a little more about the call translation that happens when we use a parameterized decorator vs non-parameterized.</p><p>@repeat -&gt; do_something = repeat(do_something)</p><p>@repeat(2, 4) -&gt; do_something = repeat(num=2, duration=4)(do_something)</p><p>So when we use a barerepeat i.e. without () python treats it as a decorator and passes the function being decorated to it. However when we use repaeat(2, 4)with args like; python first calls the the repeat function and then passes the function being decorated do_something in this case to the actual decorator. So with this understanding we can try to modify our code like below</p><pre>def repeat(kallable=None, /, *, num=3, duration=5):<br>    &quot;&quot;&quot;parameterized decorator to repeat a function call after a certain interval<br><br>    Args:<br>        num: maximum number of retries(default=3)<br>        duration: time to wait in seconds before making next retry(default=5)<br>    &quot;&quot;&quot;<br><br>    def decorator(func):<br>        def inner(*a, **kw):<br>            count = 1<br><br>            while count &lt;= num:<br>                logging.info(f&quot;Attempt: {count} out of {num}&quot;)<br>                try:<br>                    res = func()<br>                    if res:<br>                        return res<br>                except Exception as e:<br>                    logging.info(f&quot;Exception: {e}&quot;)<br><br>                count += 1<br>                time.sleep(duration)<br><br>            raise Exception(&quot;Max attempts reached&quot;)<br><br>        return inner<br><br>    if kallable:    # repeat was invoked bare like @repeat<br>        return decorator(kallable)<br>    # if we reach here it means repeat was invoked with args and hence function was not passed automatically<br>    return decorator</pre><p>And now if we try to use it without arguments like @repeat or with arguments like @repeat(num=2, duration=2) both the forms work.</p><p>With this change what we are trying to do is basically determine whether the function repeat was used without () and function do_something was passed automatically or repeat was invoked with () in which case python will first call it and then pass the function do_something to the underlying decorator.</p><p>You will also notice /, * in the function signatures of repeat and this intentional to ensure that the function name is always passed as a positional argument because that’s how the @ syntax does it.</p><p>You might be asking is this hassle even worth it or is this pattern even used somewhere ? Well yes here are two examples, <a href="https://github.com/pytest-dev/pytest/blob/main/src/_pytest/fixtures.py#L1259">fixture</a> decorator from <a href="https://docs.pytest.org/en/7.4.x/">pytest</a> and <a href="https://github.com/python/cpython/blob/main/Lib/dataclasses.py#L1243">dataclass</a> decorator from python standard library.</p><h3>Using functools.partial to write parameterized decorators</h3><p>One thing I don’t like about parameterized decorators is that you need to create this nested tree of functions which sometimes could make code less readable and you will see structures like this most of the time.</p><pre>def outer():<br>    def deco(func):<br>        def inner(*args, **kwargs):<br>            ...<br>        return inner<br>    return deco</pre><p>So is it possible to get rid of the deco function which is just a wrapper around the inner and somehow achieve the same behaviour using just the outer function ?</p><p>And the answer is Yes but it requires a little more work and some playing around with <a href="https://docs.python.org/3/library/functools.html#functools.partial">partial</a> function from <a href="https://docs.python.org/3/library/functools.html">functools</a> library.</p><pre>from functools import partial<br><br>def repeat(kallable=None, /, *, num=3, duration=5):<br>    &quot;&quot;&quot;parameterized decorator to repeat a function call after a certain interval<br><br>    Args:<br>        num: maximum number of retries(default=3)<br>        duration: time to wait in seconds before making next retry(default=5)<br>    &quot;&quot;&quot;<br><br>    def inner(*a, **kw):<br>        count = 1<br><br>        while count &lt;= num:<br>            logging.info(f&quot;Attempt: {count} out of {num}&quot;)<br>            try:<br>                res = kallable()<br>                if res:<br>                    return res<br>            except Exception as e:<br>                logging.info(f&quot;Exception: {e}&quot;)<br>  <br>            count += 1<br>            time.sleep(duration)<br><br>        raise Exception(&quot;Max attempts reached&quot;)<br>    # function was decorated with bare repeat which means callable was passed automatically and default values of arguments are to be used, so we simply need to return the inner function<br>    if kallable:   <br>        return inner<br><br>    return partial(repeat, num=num, duration=duration)</pre><p>The above version gets rid of the nested deco function and uses the functools.partial to generate a dynamic function at run time if the repeat was used without arguments. And this works exactly like previous versions.</p><h3>Using Decorators to achieve Metaclasses behaviour</h3><p><a href="https://docs.python.org/3/reference/datamodel.html#metaclasses">Metaclasses</a> are a fairly advanced topic and lot of people consider it some sort of black magic in python because of two reasons, first they are so obscure from a regular user that most of them don’t even know if something like this exists, second and more importantly you probably don’t need to write your own metaclasses or even work with them directly almost all the times, but in rarest of use cases when you need them, they will probably be your only solution.</p><p>Another reason a lot of users refrain from using metaclasses is that it requires a much deeper understanding of the python <a href="https://docs.python.org/3/reference/datamodel.html#data-model">data model</a>, classes and so called magic methods. Again my focus here today is not on metaclasses (maybe some other day we can talk about it too 🙂 ) but how you can leverage the knowledge of decorators to build tooling which typically requires working with metaclasses.</p><p>One of the more common use cases I have been for metaclasses is when building Singleton classes in python.</p><blockquote>A Singleton class is a class that can only be instantiated once, which means no matter how many times you call it you should always get the same object.</blockquote><p>Here is an example of such a class</p><pre>class Bar(metaclass=Singleton):<br>    pass<br><br><br>x = Bar()<br>y = Bar()<br><br>print(x is y)    # True</pre><p>I will not go into all the details of why you need a metaclass to enforce this run time behaviour but a very short answer would be that creation of an object of a class A happens as a result of calling the class A and what happens when you call a class A depends upon the implementation of __call__ of a class which controls the creation of class A. It might sounds confusing because it is and that’s what I meant when I said working with metaclasses requires you to know and understand a lot more on how classes/objects work in python.</p><p>With that out of the way this is how the Singleton metaclass looks like</p><pre>class Singleton(type):<br><br>    def __new__(mcs, name, bases, clsdict):<br>        # __new__ for the metalcass gets called when python sees the keyword<br>        # `class` i.e. when it is constructing the class, so we need to inject<br>        # an attribute into the class to store the object of this class<br>        clsdict[&#39;_obj&#39;] = None<br>        return super().__new__(mcs, name, bases, clsdict)<br><br>    def __call__(cls, *args, **kwargs):<br>        # this method is actually called when you try to instantiate this class<br>        # for example when class Bar below is called like Bar()<br>        if cls._obj:<br>            return cls._obj<br>        obj = super().__call__()<br>        cls._obj = obj<br>        return obj</pre><p>If you do not comprehend the above code completely it’s totally fine, in fact that is the sole motivation to use decorators to achieve the same thing. Here is the singleton decorator that does exact same thing</p><pre>def singleton(klass):<br>    # create a attribute _obj to store the instance of passed class `klass`<br>    # note you cannot use klass.__dict__[&#39;_obj&#39;] = None as `__dict__` for this<br>    # klass is a `mappingproxy`` and not a `dict` and it does not have<br>    # __setitem__ defined<br>    setattr(klass, &#39;_obj&#39;, None)<br>    def check_singleton(*args, **kwargs):<br>        # if the _obj attribute on the class is not None, then just return it<br>        if klass._obj:<br>            return klass._obj<br><br>        # if we reach here it means its the first instance of the class, so we<br>        # need to set the klass._obj = obj(actual object created after calling<br>        # the klass)<br>        obj = klass(*args, **kwargs)<br>        setattr(klass, &#39;_obj&#39;, obj)<br>        return obj<br><br>    return check_singleton<br><br><br>@singleton<br>class Foo:<br>    pass<br><br><br>a = Foo()<br>b = Foo()<br>print(a is b)    # True<br><br>class Baz:<br>    pass<br><br>p = Baz()<br>q = Baz()<br><br>print(p is q)    # False</pre><p>See how simple and readable the decorator version looks like.</p><p>That’s it for today, I hope you enjoyed these series of articles and learned something today.</p><p>Feel free to post any questions if you have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa71c2890539" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/code-transformations-with-decorators-in-python-part-3-fa71c2890539">Code transformations with Decorators in Python part 3</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code transformations with Decorators in Python part 2]]></title>
            <link>https://python.plainenglish.io/code-transformations-with-decorators-in-python-part-2-f3b5666f3248?source=rss-9228d6bf3e8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b5666f3248</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[decorators]]></category>
            <dc:creator><![CDATA[Rbhanot]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 10:44:45 GMT</pubDate>
            <atom:updated>2024-06-08T13:47:06.761Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python</h4><h4>Advanced decorator patterns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBK3AzGA9Wcz4mlYRWOkoA.jpeg" /></figure><p>In part 1 of this short series we discussed functions, closures and introduced the concept of decorators in Python. We saw some of the useful decorators from the standard library and also wrote our own spy decorator from scratch to track the time taken by the function to execute and count the number of times it was called.</p><p>In this post we will look at slightly more advanced patterns and use cases for decorators which will include</p><ol><li>How to chain multiple decorators ?</li><li>How to write decorators using classes ?</li><li>Decorating classes and methods</li></ol><h3>Chaining decorators</h3><p>If you remember the spy decorator that we had written in the last post, it was doing two things, counting the number of times the decorated function was called and also logging the time each call took. Let’s try to split that decorator into two separate decorators because</p><ul><li>Its always good to keep your functions atomic and not mix two different things in one place</li><li>It could be possible that you might extend say your logging stuff and not just limit it to log the time taken, in that case it would clutter the existing decorator and makes it hard to scale and manage</li></ul><p>Here is how the modified code looks like</p><pre>def logger(func):<br>   @wraps(func)<br>   def log_wrapper(*args):<br>       &quot;&quot;&quot;This is the docstring of the closure function&quot;&quot;&quot;<br>       t1 = time.time()<br>       res = func(*args)<br>       t2 = time.time() - t1<br>       print(f&quot;{func.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds&quot;)<br>       return res<br>   return log_wrapper<br><br><br>def counter(func):<br>   @wraps(func)<br>   def count_wrapper(*args):<br>       res = func(*args)<br>       count_wrapper.count += 1<br>       return res<br><br><br>   count_wrapper.count = 0<br>   return count_wrapper<br><br><br>@counter<br>@logger<br>def get_records():<br>   &quot;&quot;&quot;mimics making an actual http api call over the network&quot;&quot;&quot;<br>   time.sleep(random.randint(1, 2))<br><br><br>get_records()<br>get_records()<br>print(f&quot;No of calls: {get_records.count}&quot;)<br><br><br># Output<br># get_records() took 1.00057602 seconds<br># get_records() took 1.00022078 seconds<br># No of calls: 2</pre><p>Now we had to decorate our get_records function with counter and logger decorators and when we run this code we see that we got expected output.</p><p>One very important thing to keep in mind when chaining decorators is the order in which they are placed.</p><blockquote>The order of execution when a function is decorated with multiple decorators is bottom to top with the top most decorated executed last.</blockquote><p>You can see that in the above example as well, the logger decorator was executed first since it was placed below the counter.</p><p>While the order of placing the decorators matters, we should try to design decorators in such a way that they should not be impacted by the order in which they are applied, the above example is a carefully crafted one which shows what can happen if you change the order. In best case your code will break, in worst case you might introduce bugs in your system which could be hard to track.</p><pre>@logger<br>@counter<br>def get_records():<br>   &quot;&quot;&quot;mimics making an actual http api call over the network&quot;&quot;&quot;<br>   time.sleep(random.randint(1, 2))<br><br>get_records()<br>get_records()<br>print(f&quot;No of calls: {get_records.count}&quot;)<br><br># Output<br># get_records() took 1.00347972 seconds<br># get_records() took 1.00458694 seconds<br># No of calls: 0</pre><p>As you can see our code didn’t break but it says number of calls 0 which means we have introduced a bug and if some other tool is dependent on this data, all of a sudden we have an entire pipeline working with wrong/stale data.</p><p>Now let’s try to understand why this code is not working correctly with the change we made, first let me get rid of that syntactic sugar and see how the actual call looks like</p><pre>def get_records():<br>   &quot;&quot;&quot;mimics making an actual http api call over the network&quot;&quot;&quot;<br>   time.sleep(random.randint(1, 2))<br><br><br>get_records = logger(counter(get_records))</pre><p>When we passed our original function get_records to counter it returned count_wrapper , which then is passed to logger which returned log_wrapper that ultimately gets assigned to name get_records. So when we call get_records we are ultimately calling log_wrapper. And if we look at the log_wrapper again we see it does not have any count variable attached to it.</p><pre>def logger(func):<br>   @wraps(func)<br>   def log_wrapper(*args):<br>       &quot;&quot;&quot;This is the docstring of the closure function&quot;&quot;&quot;<br>       t1 = time.time()<br>       res = func(*args)<br>       t2 = time.time() - t1<br>       print(f&quot;{func.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds&quot;)<br>       return res<br>   return log_wrapper  </pre><p>This might create another question in your mind that if count was never attached to log_wrapper we should have got AttributeError when trying to access get_records.count right ?? But we didn’t, instead we got the value 0, so why is that? Okay let’s try to unravel that as well. I am going to modify the above code a little bit so that it becomes easier to see what really is happening here</p><pre>def logger(func):<br>   def log_wrapper(*args):<br>       &quot;&quot;&quot;This is the docstring of the closure function&quot;&quot;&quot;<br>       t1 = time.time()<br>       res = func(*args)<br>       t2 = time.time() - t1<br>       print(f&quot;{func.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds, Call count: {func.count}&quot;)<br>       return res<br><br><br>   log_wrapper.__name__ = func.__name__<br>   log_wrapper.__doc__ = func.__doc__<br>   return log_wrapper<br><br><br>def counter(func):<br>   def count_wrapper(*args):<br>       res = func(*args)<br>       count_wrapper.count += 1<br>       return res<br><br><br>   count_wrapper.count = 0<br>   count_wrapper.__name__ = func.__name__<br>   count_wrapper.__doc__ = func.__doc__<br>   return count_wrapper<br><br><br>@logger<br>@counter<br>def get_records():<br>   &quot;&quot;&quot;mimics making an actual http api call over the network&quot;&quot;&quot;<br>   time.sleep(1)<br><br><br>get_records()<br>get_records()<br>print(f&quot;Dict of get_records: {get_records.count}&quot;)<br># print(get_records.__dict__, get_records.__name__, get_records.count)<br><br><br># Output<br># count_wrapper() took 1.00470495 seconds, Call count: 1<br># count_wrapper() took 1.00251913 seconds, Call count: 2<br># Dict of get_records: {&#39;count&#39;: 0}</pre><p>I have made a small change in the above code by removing the @wraps(func) from log_wrapper and count_wrapper and adding couple of extra lines to add __doc__ and __name__ to both the functions. Now we see that the count variable from count_wrapper is definitely getting updated but that count variable is not part of __dict__ of log_wrapper which is obvious because we are not adding it. So if we uncomment the last line now we will get AttributeError due to get_records.count</p><p>Fixing this AttributeError is easy, all you have to do is simply add the line log_wrapper.count = func.count before return log_wrapper . However that adds another extra line of code, not forget we already have two lines of code to set the __name__ and __doc__ of the log_wrapper as well, or you can remove all 3 of these lines and simply decorate the log_wrapper and count_wrapper with with functools.wraps(f).</p><p>So @functools.wraps() not only sets the __name__ and __doc__ for the closure function with the wrapped function it also correctly copies the __dict__ of the wrapped function to the __dict__ of closure.</p><p>Now to fix the original issue which surfaced by changing the order of decorators on get_records all we have to do is to place log_wrapper.__dict__.update(func.__dict__) inside the log_wrapper before the return statement but I am going to leave it here because I wanted to highlight that things might go south if the order of decorators placed on a function is not correct.</p><h3>Writing decorators as classes</h3><h4>What is a callable ?</h4><p>Technically any object in python whose class defines a __call__ method is called a callable. Simply put, any statement after which you can put a pair of parenthesis () at the end is a callable.</p><p>Recall so how do we call a function, by putting () after it like() right, so functions are callable, what they return varies on its implementation.</p><p>Can you think of something else where we use this syntax of putting () at the end ?</p><p>How do we instantiate a <em>class</em> in Python, by calling it right ? So classes are another type of callable in Python and hence we can also use them to write decorators, but before that let’s look at function based decorators one more time just to understand what we might need to write a class based decorator.</p><p>We already know that there are 2 required things that makes any callable a decorator</p><ol><li>It needs to take a callable as its first argument.</li><li>It needs to return a callable.</li></ol><p>We can see below that a regular function based decorator meets the above two requirements easily.</p><pre>def deco(func):<br>   def wrapper(*args, **kwargs):<br>       # do something here<br>       func(*args, **kwargs)<br><br>   return wrapper</pre><p>For writing class based decorators our class needs to meet the above 2 requirements, the first requirement is pretty trivial since all we need is to accept the callable in the __init__ method of class, it’s the second requirement that needs some work. We basically need to make the instance of our class a callable, what that means is that when we instantiate the class by calling it, we should be able to call the object as well !!</p><pre>class RegularClass:<br>   def __init__(self, x):<br>       self.x = x<br><br><br>foo = RegularClass(10)<br><br><br>from collections.abc import Callable<br>isinstance(foo, Callable)    # False<br>foo()    # TypeError: &#39;RegularClass&#39; object is not callable</pre><p>As we can see in the above example, the object foo which was created after calling the class RegularClass is not a callable and if we try to call it we get TyperError, so we cannot use a <em>normal</em> class to write decorators. In order to make the object of a class callable we need to have __call__ magic method defined on the class, lets see this in action</p><pre>class CallableObjectClass:<br>   def __init__(self, x):<br>       self.x = x<br><br><br>   def __call__(self, *args, **kwargs):<br>       print(f&quot;The object {self} of class {self.__class__.__name__} was called&quot;)<br><br><br>bar = CallableObjectClass(20)<br>isinstance(bar, Callable)    # True<br>bar()    # The object &lt;__main__.CallableObjectClass object at 0x10cb64730&gt; of class CallableObjectClass was called</pre><p>Finally lets see how we can use such a class with __call__ method to turn it into a decorator. Here is the same logger decorator from previous examples rewritten as a class.</p><pre>class LoggerDecoClass():<br>   def __init__(self, f):<br>       self._f = f<br><br><br>   def __call__(self, *args, **kwargs):<br>       &quot;&quot;&quot;This is what makes the instance callable&quot;&quot;&quot;<br>       t1 = time.time()<br>       res = self._f(*args, **kwargs)<br>       t2 = time.time() - t1<br>       print(<br>           f&quot;{self._f.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds&quot;<br>       )<br><br><br>@LoggerDecoClass<br>def get_records():<br>   &quot;&quot;&quot;mimics making an actual http api call over the network&quot;&quot;&quot;<br>   time.sleep(1)<br><br><br>get_records()    # get_records() took 1.00257707 seconds</pre><p>While the above decorator works and behaves exactly like previous one written as function, it is preferred to write function based decorators, because of following differences</p><ul><li>When you call the decorated function(get_records), what you get back from the decorator and eventually gets called is <strong><em>not</em></strong> a function, instead it is a <strong><em>class object</em></strong>, so it can be semantically confusing sometimes.</li><li>It is less readable and requires some boilerplate code if you compare it with function based decorators. You can see in the above example as well that we needed to write __init__ to accept and store function being decorator and because of that everytime we have to refer to this function we have to use self.</li><li>Instead of defining a simple wrapper function we needed to override a magic method __call__ to make the object of the class callable.</li><li>Because the decorated function get_records is an object, it does not have attributes of a regular function like __name__, __doc__ so you will either have to add these explicitly in the object __dict__ in the __init__ or use functools.update_wrapper(self, f) as a replacement for functools.wraps(f) .</li></ul><p>So in short prefer writing your decorators as functions as it makes them easier to read, write and reason about.</p><h3>Decorating classes and methods</h3><p>Decorating classes and methods is pretty straight forward and work mostly like decorating functions. It&#39;s less common to see entire classes being decorated in your code as the use cases for that are pretty limited, however I will share couple of them here</p><p>One of the most frequent use cases for me for decorating an entire class is when turning a regular class into a <a href="https://docs.python.org/3/library/dataclasses.html">dataclass</a>. Here is a simple example from official python documentation</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Point:<br>     x: int<br>     y: int</pre><p>The second use case for me for decorating classes in writing unit tests, sometimes there are certain test classes which I either want to skip on bases certain condition and that’s when I use <a href="https://docs.pytest.org/en/6.2.x/skipping.html">pytest.mark.skip</a> decorator from pytest to tell <a href="https://docs.pytest.org/en/7.1.x/getting-started.html">pytest</a> to skip running tests in it.</p><pre>import pytest<br><br>class TestLinux:<br>    ....<br><br>@pytest.mark.skipif(sys.platform.startswith(&quot;win&quot;), reason=&quot;do not run on windows&quot;)<br>class TestWindows:<br>    ...</pre><p>Decorating methods of a class with custom decorators is even less common but there are examples in standard library that you would have seen quite often; few common ones are classmethod ,staticmethod and property decorators to turn regular instance bound methods into methods with special behaviour (well once decorated they arn’t method actually but a <a href="https://docs.python.org/3/howto/descriptor.html">descriptor</a>).</p><p>That’s it for now, I hope you find this post useful and learned something new. Please also checkout the <a href="https://medium.com/@rbhanot4739/code-transformations-with-decorators-in-python-part-3-fa71c2890539">part3</a> of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b5666f3248" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/code-transformations-with-decorators-in-python-part-2-f3b5666f3248">Code transformations with Decorators in Python part 2</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code transformations with Decorators in Python]]></title>
            <link>https://python.plainenglish.io/code-transformations-with-decorators-in-python-5d9ed3738115?source=rss-9228d6bf3e8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9ed3738115</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rbhanot]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 08:16:40 GMT</pubDate>
            <atom:updated>2024-06-08T13:45:12.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python</h4><h4>A gentle introduction to decorators</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-0jvMEar8SLyRPg884ezwg.jpeg" /></figure><p>Decorators are one of the powerful features in Python that can dynamically alter the behaviour of your programs by allowing you to transform functions and methods. Having sound understanding of them can enable you to do some really cool and complicated stuff in much simpler way. They let you abstract the secondary code pieces like logging, profiling etc away from your business logic thereby improving the readability of your code.</p><p>This will be a series of three posts where in the first part we will cover some basics and in the <a href="https://medium.com/@rbhanot4739/code-transformations-with-decorators-in-python-part-2-f3b5666f3248">part2</a> we will explore slightly intermediate patterns like decorator chaining, writing decorators using classes and decorating classes and methods and finally in <a href="https://medium.com/@rbhanot4739/code-transformations-with-decorators-in-python-part-3-fa71c2890539">part 3</a> I will try to introduce some advanced and less known patters with parameterised decorators and using decorators as an alternative to metaclasses.</p><blockquote>Familiarity with functions, positional &amp; keyword arguments, functions with return values is expected as a pre-requisite for this article.</blockquote><p>This is what we will be covering today</p><ul><li>Functions as first class objects or citizens</li><li>Closures</li><li>Decorators</li></ul><h4>Functions as First Class citizens</h4><p>You must have heard this line frequently that <strong>Everything is an Object in Python</strong> and that holds true for functions as well. Functions are considered as <a href="https://en.wikipedia.org/wiki/First-class_function">first class citizens</a> in python and are treated just like any other types like integers, strings, lists etc which means</p><ol><li>You can create nested functions inside a function</li><li>You can pass functions as an argument to other functions</li><li>You can return functions from other functions</li></ol><p>Functions which incorporate any of the above characteristics are called <a href="https://en.wikipedia.org/wiki/Higher-order_function"><strong>Higher Order functions</strong></a>. Let’s look at a simple example first</p><pre>def outer():<br>   def inner():<br>       print(&quot;Hello from inner&quot;)<br>   inner()<br> <br>outer()    # &quot;Hello from inner&quot;</pre><p>Here is another one</p><pre>def greet():<br>   print(&quot;Hello World !!&quot;)<br> <br>def outer(func):<br>   return func()   # passed funtion being invoked<br> <br>outer(greet)    # Hello World !!</pre><p>One thing to note in the above example is that we are <em>not</em> calling the function greet at last line, we are simply passing the function reference and the actual call is being made inside the outer function.</p><p>Now you might be asking that this greet function was very simple and did not require any arguments hence we were able to pass it as such, what if I want to pass a function which requires some input arguments, well that’s pretty easy to achieve as well.</p><pre>def calc(func, a, b):<br>   return func(a, b)<br><br>def add(*args):<br>   print(sum(args))<br><br>calc(add, 5, 8)<br><br># or a more generalised pattern<br>def outer(func, *args):<br>   return func(*args)<br><br>outer(add, *[1,2,3])</pre><h3>Closures</h3><p>A <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)">closure</a> is a function defined inside a function which captures the variables from the enclosing scope and uses these variables locally.<em> The peculiar thing about closures is that unlike a regular function it allows the function to access the captured variables even when the function is called outside of its enclosing scope which you cannot do with a regular function</em>. Now that might sound pretty confusing, so let’s look at code to understand what it really means.</p><pre>def multiplier(factor, *args):<br>    def inner():<br>        return [i * factor for i in args]<br> <br>    return inner</pre><p>At first it might look like a regular nested function but it has properties that make it special.</p><h3>__closure__</h3><p>Every function in python has this special attribute __closure__ which contains tuple of free variables or captured variables (variables which are defined in enclosing scope but being accessed locally), if the function forms a closure otherwise it is set to None.</p><p>We can verify that for above function from an ipython repl</p><pre>In [2]: doubler = multiplier(2, [1, 2, 3, 4])<br>In [3]: doubler<br>Out[3]: &lt;function __main__.multiplier.&lt;locals&gt;.inner()&gt;<br>In [4]: doubler.__closure__<br>Out[4]:<br>(&lt;cell at 0x104cee2c0: tuple object at 0x104e35580&gt;,<br>&lt;cell at 0x104ceff40: int object at 0x102ad4110&gt;)<br>In [5]: type(doubler.__closure__)<br>Out[5]: tuple<br>In [6]: doubler.__closure__[0].cell_contents<br>Out[6]: (1, 2, 3, 4)<br>In [7]: print([getattr(i, &#39;cell_contents&#39;) for i in doubler.__closure__])<br>[(1, 2, 3, 4), 2]</pre><p>When we called the multiplier function with those two arguments it returned us the function inner which captured the arguments passed to the enclosing function (multiplier) and hence these arguments were added to the __closure__.</p><p>We can also verify that for a regular nested function which does not capture any values from enclosing scope the value of __closure__ is set to None</p><pre>def outer(msg):<br>   def inner():<br>       print(&quot;hello&quot;)<br>   return inner<br> <br>x = outer(&quot;hello&quot;)<br>print(x.__closure__)    # None</pre><p>So a closure is only formed when the inner function actually uses variables from the enclosing scope.</p><p>Here is a slightly modified version of the multiplier function we defined above that illustrates the real power of closures.</p><pre>def multiplier(factor):<br>   def inner(*args):<br>       return [i * factor for i in args]<br> <br>   return inner<br> <br>doubler = multiplier(2)<br>tripler = multiplier(3)<br> <br>print(doubler(*[1, 2, 3, 4]))  # [2, 4, 6, 8]<br>print(tripler(*[1, 2, 3, 4]))  # [3, 6, 9, 12]</pre><p>Let’s analyse how this works</p><ul><li>We called multiplier by passing 2 and 3 as values for factor .</li><li>We got the function inner returned from multiplier which we stored in doubler and tripler.</li><li>Finally we call these functions with [2, 4, 6, 8] and got desired results.</li><li>Here is the interesting part which sometimes go unnoticed, the functions doubler and tripler were defined in global module scope, but the argument factor was in local scope of multiplier , so how did these functions were able to access it ? The reason is since the inner function formed a <em>closure</em> by capturing the factor from the enclosing scope (multiplier) and because the names doubler and tripler actually contain value of inner only, the are able to access the captured value from __closure__. This is what makes closures really special.</li></ul><h3>Decorators</h3><p>Finally after discussing higher order functions and closures we are ready to talk about decorators. A decorator in python in its simplistic form is a <em>callable</em> that takes a <em>callable</em> as its first argument and then returns a <em>callable</em> typically after doing something with the input callable.</p><p>I am intentionally using the term callable here instead of a function, because there is one more type of callable in Python and we can use them as well to write decorators, which we will cover in next article, for now assume callable refers to functions only as in this article we will only see function based decorators.</p><p>They are a type of dynamic code injections and allow you to alter the functionality of your functions at runtime.</p><p>Here is a decorator that just adds a static attribute msg to the passed in function.</p><pre>def simple_decorator(func):<br>   func.msg = &#39;I am being decorated&#39;<br>   return func</pre><p>Now lets see this decorator in action</p><pre> def greet():<br>   return &quot;Hello world&quot;<br> <br>print(greet.__dict__)    # {}<br> <br>greet = simple_decorator(greet)<br>print(greet.__dict__)    # {&#39;msg&#39;: &#39;I am being decorated&#39;} </pre><p>When we print the __dict__ of greet function, we see it has no attributes. Then we decorate it greet = simple_decorator(greet) and after that when we call the greet function again we were able to see the msg key in the __dict__ .</p><p>There are few problems with decorator syntax we used above</p><ol><li>It impairs the readability of the code as the transformation logic is applied after the function definition, this can be confusing for the longer functions/methods.</li><li>Its arguably not pythonic as well, since the function name (greet in our case) is repeated thrice.</li></ol><p>So is there a better way to do it, yes there is !!</p><pre>@simple_decorator<br>def greet():<br>   return &quot;Hello world&quot;<br> <br>print(greet.__dict__)    # {&#39;msg&#39;: &#39;I am being decorated&#39;   </pre><blockquote>Please note that the @simple_decorator is just a syntactic sugar and while it is the recommended syntax, you should know how that syntax unfolds to the actual call, because it makes easier to understand more complicated decorators like class based and parameterized decorators.</blockquote><p>While the above simple_decorator was technically a decorator but it was limited and added just a static attribute, we will turn it into a much more useful one when we talk about parameterized decorators.</p><p>For now let’s write a decorator that does some useful stuff for example to count the number of times a function has been called and how much time each call took</p><pre>import time<br>import random<br> <br>def spy(func):<br>     def wrapper(*args):<br>          &quot;&quot;&quot;This is the docstring of the closure function&quot;&quot;&quot;<br>          t1 = time.time()<br>          res = func(*args)<br>          t2 = time.time() - t1<br>          print(f&quot;{func.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds&quot;)<br>          wrapper.count += 1<br>          return res<br>    <br>    wrapper.count = 0<br>    return wrapper<br><br>@spy<br>def get_records():<br>    &quot;&quot;&quot;mimics making an actual http api call over the network&quot;&quot;&quot;<br>    time.sleep(random.randint(1, 5))<br><br>@spy<br>def process_records():<br>    &quot;&quot;&quot;in reality you will do some processing of the records here and optionally write to a database&quot;&quot;&quot;<br>    time.sleep(random.randint(1, 5))<br>    <br>if __name__ == &quot;__main__&quot;:<br>    print(process_records)    # &lt;function spy.&lt;locals&gt;.counter at 0x102658e50&gt;<br>    print(get_records)      # &lt;function spy.&lt;locals&gt;.counter at 0x102659870&gt;<br><br>    get_records()<br>    get_records()<br>    get_records()<br><br>    process_records()<br>    process_records()<br><br>    print(f&quot;Number of times get_records called: {get_records.count}&quot;)<br>    print(f&quot;Number of times process_records called: {process_records.count}&quot;)</pre><p>And this is what we get when we call the decorated functions.</p><pre>&lt;function spy.&lt;locals&gt;.wrapper at 0x10d6f5ab0&gt;<br>&lt;function spy.&lt;locals&gt;.wrapper at 0x10d6f5870&gt;<br>get_records() took 3.00427103 seconds<br>get_records() took 5.00074315 seconds<br>get_records() took 3.00240803 seconds<br>process_records() took 4.00294971 seconds<br>process_records() took 2.00388408 seconds<br>Number of times get_records called: 3<br>Number of times process_records called: 2</pre><p>Let’s try to understand step by step what we are doing here.</p><ol><li>We defined the decorator function spy which took the function func as its only argument.</li><li>Then we defined a nested function wrapper inside spy which captured the func from enclosing scope and called it, thereby forming a <em>closure.</em></li><li>Then we initialized the count attribute to 0 on the wrapper and finally we returned the wrapper from the spy.</li><li>Next we decorated the get_records and process_records functions and invoked these decorated functions.</li><li>However you can see print(process_records) and print(get_records) reveals the actual function that will get invoked is the wrapper returned from the spy , now why is that ? Recall the note on<em> syntactic sugar</em> which actually gets translated to get_records = spy(get_records) and since spy returns wrapper, it gets assigned to get_records so when we call it, it’s the wrapper that gets called.</li><li>There is another interesting but hard to notice transformation happening inside the spy decorator. We are setting an attribute on wrapper which we later increment by one on every call. Can’t we do that on the passed input function func directly like func.count = 0 ? Turns out if you do that it will break the code when you access it get_records.count with AttributeError: ‘function’ object has no attribute ‘count’. Hmm… why is that ? Again recall the function that gets called is wrapper and since we never set the count attribute on it, we get the error.</li></ol><p>The beauty of decorators lies in the fact that you can add really complicated behaviours to business logic without changing a single line of source code in them !!</p><p>Notice we never had to change the source code of any of the functions being decorated get_records and process_records to achieve this added spy behaviour. Ofcourse in our case our decorated functions were just time.sleep() to simulate some work happening over the network/disk, but in reality these will be more complicated like making network api calls, doing some post processing and writing to a database.</p><p>Also in this case our spy decorator was much simpler but you can add much more functionality like keeping track of functions taking longer time and all your decorated functions would automatically get that behaviour. Isn’t that magical :)</p><p>So here are couple of powerful yet rarely talked about characteristics of decorators</p><ul><li>They let you in implement a layer of abstraction by hiding the complicated secondary code separately and keeping the business logic simple and readable.</li><li>They also incorporate <a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself">DRY</a> principle, since you can write a decorator and use it decorate multiple functions.</li></ul><h4>What’s up with wraps ?</h4><p>You would have noticed that almost all of the decorators you would see in production code have this @wraps(f) decorating the inner function.</p><p>Also as we have seen in the last section that when you call the decorated function, it’s the closure function that actually gets called, this creates an issue that’s not visible upfront, which is that we lost the name and docstring of the original function we decorated which can be a problem sometimes. Let me show you what I mean, for brevity I am omitting the boilerplate code from above example</p><pre>if __name__ == &quot;__main__&quot;:<br> <br>   print(f&quot;Function name: {get_records.__name__}, Docstring: {get_records.__doc__}&quot;)<br>   print(f&quot;Function name: {process_records.__name__}, Docstring: {process_records.__doc__}&quot;)<br> <br># Output<br># Function name: wrapper, Docstring: This is the docstring of the closure function<br># Function name: wrapper, Docstring: This is the docstring of the closure function</pre><p>Well it is easy to fix this by making the following change</p><pre>def spy(func):<br>   def wrapper(*args):<br>       &quot;&quot;&quot;This is the docstring of the closure function&quot;&quot;&quot;<br>       t1 = time.time()<br>       res = func(*args)<br>       t2 = time.time() - t1<br>       print(f&quot;{func.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds&quot;)<br>       wrapper.count += 1<br>       return res<br> <br>   wrapper.count = 0<br>   wrapper.__name__ = func.__name__<br>   wrapper.__doc__ = func.__doc__<br>   return wrapper<br> <br># output<br># Function name: get_records, Docstring: mimics making an actual http api call over the network<br># Function name: process_records, Docstring: in reality you will do some processing of the records here</pre><p>However it again impairs the readability of the code and feels hackish and that is one of the things thatfunctools.wraps can help us here.</p><pre>def spy(func):<br>   @wraps(func)<br>   def wrapper(*args):<br>       &quot;&quot;&quot;This is the docstring of the closure function&quot;&quot;&quot;<br>       t1 = time.time()<br>       res = func(*args)<br>       t2 = time.time() - t1<br>       print(f&quot;{func.__name__}({&#39;&#39;.join(str(i) for i in args)}) took {t2:.8f} seconds&quot;)<br>       wrapper.count += 1<br>       return res<br> <br>   wrapper.count = 0<br>   return wrapper<br> <br># output<br># Function name: get_records, Docstring: mimics making an actual http api call over the network<br># Function name: process_records, Docstring: in reality you will do some processing of the records here</pre><h4>Decorators in standard library</h4><p>The python standard library ships with lots of helpful decorators and here are a few that I find myself using most of the time.</p><p><strong>classmethod</strong> and <strong>staticmethod</strong>: The builtin decorators to write class and static method for classes.</p><p><a href="https://docs.python.org/3/library/dataclasses.html?highlight=dataclass#dataclasses.dataclass"><strong>@dataclasses.dataclass</strong></a>: To write dataclasses</p><p><a href="https://docs.python.org/3/library/functools.html#module-functools"><strong>Functools</strong></a>: The standard library package has some really handy decorators like <a href="https://docs.python.org/3/library/functools.html#functools.wraps">wraps</a>, <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache">lru_cache</a>, <a href="https://docs.python.org/3/library/functools.html#functools.partial">partial</a>.</p><p>@<a href="https://docs.python.org/3/library/unittest.mock-examples.html?highlight=decorators#patch-decorators">patch</a> from <a href="https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock">unittest.mock:</a> used for patching and mocking objects during testing</p><p><a href="https://docs.python.org/3/library/contextlib.html?highlight=decorators#contextlib.contextmanager">@contextmanager</a>: to write context managers in python using yield statement without the need to write class with __enter__ and __exit__ methods.</p><p>I hope this was helpful in introducing you to the decorators in python, of course there is a lot more to the decorators which we will cover in <a href="https://medium.com/@rbhanot4739/code-transformations-with-decorators-in-python-part-2-f3b5666f3248">part 2</a> of this article, so stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9ed3738115" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/code-transformations-with-decorators-in-python-5d9ed3738115">Code transformations with Decorators in Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>