<?xml version="1.0" encoding="iso-8859-1"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en"> 
<title>ProgrammingBits</title> 
<link rel="alternate" type="text/html" href="http://programmingbits.pythonblogs.com/27_programmingbits" /> 
	 
	<modified>2009-02-15T12:00:27-08:00</modified> 
<tagline>&lt;p&gt;Exploring Python&#039;s awesomeness. By Ariel Ortiz.&lt;/p&gt;
</tagline> 
<generator url="http://www.lifetype.net/" version="1.2">LifeType</generator> 
 
<copyright>Copyright (c) aortiz</copyright> 
  
 <entry> 
 <id>tag:www.pythonblogs.com,2009-02-15:51</id>
 <title>More On Function Decorators</title> 
 <link rel="alternate" type="text/html" href="http://programmingbits.pythonblogs.com/27_programmingbits/archive/51_more_on_function_decorators.html" /> 
  
 <modified>2009-02-15T12:00:27-08:00</modified> 
 <issued>2009-02-15T12:00:27-08:00</issued> 
 <created>2009-02-15T12:00:27-08:00</created> 
 <summary type="text/plain">  
In my  previous post , I presented a couple of examples on how to use function decorators in Python. Those examples were illustrative, yet fairly restricted. First of all, they assumed that ...</summary> 
 <author> 
  
 <name>aortiz</name> 
 <url>http://programmingbits.pythonblogs.com/27_programmingbits</url> 
</author> 
<dc:subject>
Programming techniques 
</dc:subject> 
 <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://programmingbits.pythonblogs.com/27_programmingbits"> 
 &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;http://programmingbits.pythonblogs.com/plugins/plogeshi/styles/plogeshi.css&quot; /&gt;&lt;p&gt;
In my &lt;a href=&quot;http://programmingbits.pythonblogs.com/27_programmingbits/archive/50_function_decorators.html&quot;&gt;previous post&lt;/a&gt;, I presented a couple of examples on how to use function decorators in Python. Those examples were illustrative, yet fairly restricted. First of all, they assumed that the function being decorated only receives one positional argument. What can I do if I want to decorate a function that takes two or more positional arguments, or one or more keyword arguments? Secondly, they didn&#039;t allow the decorator to be configured in any special way. So, how do I send input arguments to the decorator itself so that I can vary its behavior? 
&lt;/p&gt;
&lt;p&gt;
I will now elaborate in a slightly more complex example that will give us a better insight on how to define much more general decorators, without any of the restrictions I just mentioned.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;NOTE:&lt;/strong&gt; All Python code examples presented here are based in Python 3.0. Full source code: &lt;a href=&quot;http://programmingbits.pythonblogs.com/gallery/27/more_function_decorators.py&quot;&gt;more_function_decorators.py&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Suppose we want a decorator function that is able to &amp;quot;swallow&amp;quot; one or more kinds of exceptions that might be raised during the execution of the decorated function&lt;sup&gt;1&lt;/sup&gt;. If a particular exception is actually produced, we want to be able to specify a default value to be returned instead of allowing the exception to propagate through the execution stack and possibly causing the program to terminate. A client of our decorator would basically be able to avoid the hassle of writing an explicit &lt;tt&gt;try&lt;/tt&gt; statement. 
&lt;/p&gt;
&lt;p&gt;
To demonstrate how this could work, let&#039;s assume we have a function like this one: 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; divide&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;dividend=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, divisor=&lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; dividend / divisor&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
When calling this function, there are at least two possible exceptions that might get raised: &lt;tt&gt;ZeroDivisionError&lt;/tt&gt; and &lt;tt&gt;TypeError&lt;/tt&gt;. The first one is produced when the &lt;tt&gt;divisor&lt;/tt&gt; parameter is zero. The second exception occurs when any of the two arguments sent are not of a numerical type, when more than two arguments are actually sent, or when you try to use a nonexistent keyword argument. Some examples:
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&amp;gt;&amp;gt;&amp;gt; divide(1, 2)
0.5

&amp;gt;&amp;gt;&amp;gt; divide(1, 0)
Traceback (most recent call last):
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 1, in &amp;lt;module&amp;gt;
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 2, in divide
ZeroDivisionError: int division or modulo by zero

&amp;gt;&amp;gt;&amp;gt; divide(&amp;quot;hello&amp;quot;)
Traceback (most recent call last):
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 1, in &amp;lt;module&amp;gt;
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 2, in divide
TypeError: unsupported operand type(s) for /: &#039;str&#039; 
and &#039;int&#039; 

&amp;gt;&amp;gt;&amp;gt; divide(whatever=1)
Traceback (most recent call last):
  File &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 1, in &amp;lt;module&amp;gt;
TypeError: divide() got an unexpected keyword 
argument &#039;whatever&#039;
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Our &lt;tt&gt;swallow&lt;/tt&gt; decorator will receive two keyword arguments: 
&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;tt&gt;exceptions&lt;/tt&gt;: a single exception class or a tuple containing several exception classes. These represent the exceptions that should be swallowed. Any other exception will be propagated as usual. Defaults to &lt;tt&gt;BaseException&lt;/tt&gt; (the root of Python&#039;s exception hierarchy) if it&#039;s not explicitly provided.&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;default&lt;/tt&gt;: the value to return if one of the specified exceptions is raised. Defaults to &lt;tt&gt;None&lt;/tt&gt; when not provided.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Let&#039;s look at three usage examples.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Example 1:&lt;/strong&gt; If a division by zero is attempted, return zero:
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;@swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;exceptions=&lt;span class=&quot;kw1&quot;&gt;ZeroDivisionError&lt;/span&gt;, default=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; divide&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;dividend=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, divisor=&lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; dividend / divisor&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Example 2:&lt;/strong&gt; If a &lt;tt&gt;ZeroDivisionError&lt;/tt&gt; or a &lt;tt&gt;TypeError&lt;/tt&gt; is raised, return zero:
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;@swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;
    exceptions=&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;kw1&quot;&gt;ZeroDivisionError&lt;/span&gt;, &lt;span class=&quot;kw1&quot;&gt;TypeError&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;, 
    default=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; divide&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;dividend=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, divisor=&lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; dividend / divisor&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Example 3:&lt;/strong&gt; Chain two &lt;tt&gt;swallow&lt;/tt&gt; decorators, so that each specific exception has its own default value:
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;@swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;exceptions=&lt;span class=&quot;kw1&quot;&gt;TypeError&lt;/span&gt;, default=&#039;Huh?&#039;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
@swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;exceptions=&lt;span class=&quot;kw1&quot;&gt;ZeroDivisionError&lt;/span&gt;, default=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; divide&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;dividend=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, divisor=&lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; dividend / divisor&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
For this last example, this is how we could now use our decorated &lt;tt&gt;divide&lt;/tt&gt; function: 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&amp;gt;&amp;gt;&amp;gt; divide(1, 2)
0.5
&amp;gt;&amp;gt;&amp;gt; divide(1, 0)
0
&amp;gt;&amp;gt;&amp;gt; divide(&amp;quot;hello&amp;quot;)
&#039;Huh?&#039;
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
In order to implement the &lt;tt&gt;swallow&lt;/tt&gt; decorator, we must take a better look on how the &lt;tt&gt;@&lt;/tt&gt; syntax works. After the &lt;tt&gt;@&lt;/tt&gt; sign, you must actually specify an expression that when evaluated produces a callable object&lt;sup&gt;2&lt;/sup&gt;. When this callable object is effectively called, it receives as its only argument the function that is to be decorated, and it returns that same function or some new callable thing. 
&lt;/p&gt;
&lt;p&gt;
The expression after the &lt;tt&gt;@&lt;/tt&gt; sign is commonly just the name of a function (the decorator function), but it can also be: 1) a new instance of a class that contains an implementation of the &lt;tt&gt;__call__&lt;/tt&gt; method; or 2) a call to some other function. Both these options allow us to send additional information to the decorator by specifying it via input parameters.
&lt;/p&gt;
&lt;p&gt;
A first implementation using classes that define the &lt;tt&gt;__call__&lt;/tt&gt; method could be as follows: 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;class&lt;/span&gt; swallow:
    
    &lt;span class=&quot;kw1&quot;&gt;class&lt;/span&gt; helper:
        
        &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;, outer, fun&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
            &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;outer&lt;/span&gt; = outer
            &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;fun&lt;/span&gt; = fun            
            
        &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;, *args, **kwargs&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
            &lt;span class=&quot;kw1&quot;&gt;try&lt;/span&gt;:
                &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;fun&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;*args, **kwargs&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
            &lt;span class=&quot;kw1&quot;&gt;except&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;outer&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;exceptions&lt;/span&gt;:
                &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;outer&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;default&lt;/span&gt;
    
    &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;, 
                 default=&lt;span class=&quot;kw1&quot;&gt;None&lt;/span&gt;, 
                 exceptions=BaseException&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
        &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;default&lt;/span&gt; = default
        &lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;exceptions&lt;/span&gt; = exceptions
        
    &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;, fun&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:                            
        &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; swallow.&lt;span class=&quot;me1&quot;&gt;helper&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;kw1&quot;&gt;self&lt;/span&gt;, fun&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt; 
&lt;/p&gt;
&lt;p&gt;
Let&#039;s try to understand how this works. This code: 
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;@swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;exceptions=&lt;span class=&quot;kw1&quot;&gt;ZeroDivisionError&lt;/span&gt;, default=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; divide&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;dividend=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, divisor=&lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; dividend / divisor&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
is basically equivalent to this one:
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; divide&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;dividend=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, divisor=&lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; dividend / divisor     
divide = swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;exceptions=&lt;span class=&quot;kw1&quot;&gt;ZeroDivisionError&lt;/span&gt;, 
                 default=&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;.__call__&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;divide&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
In the last statement of the above code, an instance of the &lt;tt&gt;swallow&lt;/tt&gt; class is created and initialized according to our needs. Then, the &lt;tt&gt;__call__&lt;/tt&gt; method is invoked on that very same instance, which in turn creates and returns a new instance of the &lt;tt&gt;swallow.helper&lt;/tt&gt; nested class. The final effect is that the &lt;tt&gt;divide&lt;/tt&gt; variable refers to an instance of this specific class.&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The &lt;tt&gt;swallow.helper&lt;/tt&gt; class implements a &lt;tt&gt;__call__&lt;/tt&gt; method that accepts any number of positional and keyword arguments&lt;sup&gt;3&lt;/sup&gt;. Thus, instances of this class can effectively decorate any function that takes whatever arguments it needs. The &lt;tt&gt;__call__&lt;/tt&gt; method itself contains a &lt;tt&gt;try&lt;/tt&gt; statement that does all the work: it invokes the decorated function and sends back the returned value, unless  any of the specified exceptions get caught, in which case it returns the specified default value. Note that all the values that are required to do the job are conveniently stored and shared using the instance variables of the &lt;tt&gt;swallow&lt;/tt&gt; and &lt;tt&gt;swallow.helper&lt;/tt&gt; classes.
&lt;/p&gt;
&lt;p&gt;
A second implementation of the &lt;tt&gt;swallow&lt;/tt&gt; decorator can be coded using only function definitions (and their corresponding lexical closures). Although it&#039;s considerably shorter, it might be a little bit more difficult to understand at first: 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; swallow&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;default=&lt;span class=&quot;kw1&quot;&gt;None&lt;/span&gt;, exceptions=BaseException&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; helper1&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;fun&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
        &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; helper2&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;*args, **kwargs&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
            &lt;span class=&quot;kw1&quot;&gt;try&lt;/span&gt;:
                &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; fun&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;*args, **kwargs&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
            &lt;span class=&quot;kw1&quot;&gt;except&lt;/span&gt; exceptions:
                &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; default
        &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; helper2
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; helper1&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
As can be observed, the &lt;tt&gt;swallow&lt;/tt&gt; function takes the two input parameters that allow us to configure the decorator. It returns the nested function &lt;tt&gt;helper1&lt;/tt&gt;, which is just what the &lt;tt&gt;@&lt;/tt&gt; syntax expects. The &lt;tt&gt;helper1&lt;/tt&gt; function will be immediately called with the function being decorated as its only argument, returning function &lt;tt&gt;helper2&lt;/tt&gt; as its result. This means that if we are decorating a function called &lt;em&gt;f&lt;/em&gt;, variable &lt;em&gt;f&lt;/em&gt; will end up holding a reference to the &lt;tt&gt;helper2&lt;/tt&gt; function. So now, whenever &lt;em&gt;f&lt;/em&gt; gets invoked, &lt;tt&gt;helper2&lt;/tt&gt; will be called and the &lt;tt&gt;try&lt;/tt&gt; statement will do its job exactly as described before.
&lt;/p&gt;
&lt;p&gt;
&lt;span style=&quot;font-size: medium&quot;&gt;&lt;strong&gt;Notes&lt;/strong&gt;&lt;/span&gt;&lt;span style=&quot;font-size: medium&quot;&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;sup&gt;1&lt;/sup&gt; Swallowing exceptions can be convenient under certain circumstances, but you should avoid using this technique indiscriminately. Specifically, it can make debugging code very hard.
&lt;/p&gt;
&lt;p&gt;
&lt;sup&gt;2&lt;/sup&gt; Callable objects contain a special attribute named &lt;tt&gt;__call__&lt;/tt&gt;. If &lt;tt&gt;x&lt;/tt&gt; is a callable object, then the syntax: 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;arg1, arg2, arg3&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
is equivalent to: 
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;x.__call__&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;arg1, arg2, arg3&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Callable objects include user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and instances of classes that define or inherit their own &lt;tt&gt;__call__&lt;/tt&gt; method. 
&lt;/p&gt;
&lt;p&gt;
&lt;sup&gt;3&lt;/sup&gt; If your not familiar with the &lt;tt&gt;*args&lt;/tt&gt; and &lt;tt&gt;**kwargs&lt;/tt&gt; notation, check the &lt;a href=&quot;http://docs.python.org/3.0/tutorial/controlflow.html#more-on-defining-functions&quot; target=&quot;_blank&quot;&gt;Python tutorial&lt;/a&gt; for more details.
&lt;/p&gt; 
</content> 
</entry> 
 
 <entry> 
 <id>tag:www.pythonblogs.com,2009-01-31:50</id>
 <title>Function Decorators</title> 
 <link rel="alternate" type="text/html" href="http://programmingbits.pythonblogs.com/27_programmingbits/archive/50_function_decorators.html" /> 
  
 <modified>2009-01-31T09:50:56-08:00</modified> 
 <issued>2009-01-31T09:50:56-08:00</issued> 
 <created>2009-01-31T09:50:56-08:00</created> 
 <summary type="text/plain">  
The Python programming language has an interesting syntactic feature called a  decorator . Let&#039;s use an example in order to explain how and why you would want to use a Python decorator. ...</summary> 
 <author> 
  
 <name>aortiz</name> 
 <url>http://programmingbits.pythonblogs.com/27_programmingbits</url> 
</author> 
<dc:subject>
Programming techniques 
</dc:subject> 
 <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://programmingbits.pythonblogs.com/27_programmingbits"> 
 &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;http://programmingbits.pythonblogs.com/plugins/plogeshi/styles/plogeshi.css&quot; /&gt;&lt;p&gt;
The Python programming language has an interesting syntactic feature called a &lt;em&gt;decorator&lt;/em&gt;. Let&#039;s use an example in order to explain how and why you would want to use a Python decorator. 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;NOTE:&lt;/strong&gt; All Python code examples presented here are based in Python 3.0. Full source code: &lt;a href=&quot;http://programmingbits.pythonblogs.com/gallery/27/function_decorators.py&quot;&gt;function_decorators.py&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Suppose we want to compute the &lt;a href=&quot;http://en.wikipedia.org/wiki/Fibonacci_number&quot; target=&quot;_blank&quot;&gt;Fibonacci numbers&lt;/a&gt; using a recursive function&lt;sup&gt;1&lt;/sup&gt;. The following function definition does the trick: 
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; fib&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;n&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;if&lt;/span&gt; n &lt;span class=&quot;kw1&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;nu0&quot;&gt;0&lt;/span&gt;, &lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
        &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; n
    &lt;span class=&quot;kw1&quot;&gt;else&lt;/span&gt;:
        &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; fib&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;n - &lt;span class=&quot;nu0&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt; + fib&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;n - &lt;span class=&quot;nu0&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
We can now test the function with different input values:&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;
&gt;&gt;&gt; fib(0)
0
&gt;&gt;&gt; fib(1)
1
&gt;&gt;&gt; fib(4)
3
&gt;&gt;&gt; fib(10)
55
&gt;&gt;&gt; fib(30)
832040
&gt;&gt;&gt; fib(35)
9227465
&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
If you&#039;ve actually typed these examples in a Python shell, you&#039;ve probably noticed that obtaining a result takes longer for bigger inputs. In order to make it run faster, we can use a technique called &lt;em&gt;memoization&lt;/em&gt;. A memoized function stores in a cache the results corresponding to some set
of specific inputs. Later calls, with previously computed inputs, return the
results stored in the cache, thus avoiding their recalculation. This means that the primary
cost of a call with certain parameters is taken care of during the first call made to the
function with those same parameters.
&lt;/p&gt;
&lt;p&gt;
Instead of modifiying the &lt;tt&gt;fib&lt;/tt&gt; function directly, it&#039;s better to write a reusable memoizing function: 
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; memoize&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;f&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    cache = &lt;span class=&quot;br0&quot;&gt;&amp;#123;&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#125;&lt;/span&gt;
    &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; helper&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
        &lt;span class=&quot;kw1&quot;&gt;if&lt;/span&gt; x &lt;span class=&quot;kw1&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;kw1&quot;&gt;in&lt;/span&gt; cache:            
            cache&lt;span class=&quot;br0&quot;&gt;&amp;#91;&lt;/span&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#93;&lt;/span&gt; = f&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
        &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; cache&lt;span class=&quot;br0&quot;&gt;&amp;#91;&lt;/span&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#93;&lt;/span&gt;
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; helper&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
The &lt;tt&gt;memoize&lt;/tt&gt; function wraps another function, called &lt;tt&gt;helper&lt;/tt&gt;, which is going to provide additional functionality to the function received through parameter &lt;tt&gt;f&lt;/tt&gt;. The &lt;tt&gt;helper&lt;/tt&gt; function is actually a &lt;em&gt;lexical closure&lt;/em&gt;, that is, a function object that remembers the variable bindings that were in its scope when it was created. In this case, &lt;tt&gt;helper&lt;/tt&gt; remembers variables &lt;tt&gt;f&lt;/tt&gt; and &lt;tt&gt;cache&lt;/tt&gt;, which happen to hold a function object and a dictionary, respectively. The last statement in &lt;tt&gt;memoize&lt;/tt&gt; just returns to its caller the &lt;tt&gt;helper&lt;/tt&gt; lexical closure. 
&lt;/p&gt;
&lt;p&gt;
Type the following code, and you&#039;ll notice right away a speed increase when calling &lt;tt&gt;fib&lt;/tt&gt;. The speedup can be appreciated even in the very first call because the
memoization immediately boosts all the recursive calls inside &lt;tt&gt;fib&lt;/tt&gt;&#039;s
definition.
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;
&gt;&gt;&gt; fib = memoize(fib)
&gt;&gt;&gt; fib(50)
12586269025
&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
The assignment in the first line can be read as: the &lt;tt&gt;fib&lt;/tt&gt; function is being &lt;em&gt;decorated&lt;/em&gt; by the &lt;tt&gt;memoize&lt;/tt&gt; function. Because this is such a common programming idiom in Python, there&#039;s a special decorator syntax to simplify its use. This syntax was originally inspired by Java&#039;s annotations: just above the definition of the function that is to be decorated, place an at sign (@) followed by the name of the decorator function. 
&lt;/p&gt;
&lt;p&gt;
In other words, this Python syntax:
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;@some_decorator
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; some_function&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;co1&quot;&gt;# function body...&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
is equivalent to: 
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; some_function&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;co1&quot;&gt;# function body...&lt;/span&gt;
some_function = some_decorator&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;some_function&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
Most should agree that the @ notation is more readable and less error prone.
&lt;/p&gt;
&lt;p&gt;
In order to use the Python decorator with our &lt;em&gt;Fibonacci + memoization&lt;/em&gt; example, we would have to rewrite as follows: 
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; memoize&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;f&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;co1&quot;&gt;# Same code as before...&lt;/span&gt;
&amp;nbsp;
@memoize 
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; fib&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;n&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;co1&quot;&gt;# Same code as before...&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
The &lt;tt&gt;memoize&lt;/tt&gt; function shows the general structure that a typical function decorator should have: it receives a function &lt;em&gt;f&lt;/em&gt; as its input parameter, and it returns another function that attaches some additional responsibilities to &lt;em&gt;f&lt;/em&gt;.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Another interesting thing about Python decorators is that you can chain two or more together. Let&#039;s extend our example in order to incorporate a tracing decorator that will display a message before the decorated function gets called and also when it returns.
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; memoize&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;f&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;co1&quot;&gt;# Same code as before...&lt;/span&gt;
&amp;nbsp;
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; trace&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;f&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; helper&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
        call_str = &lt;span class=&quot;st0&quot;&gt;&quot;{0}({1})&quot;&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;f.__name__, x&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
        &lt;span class=&quot;kw1&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;st0&quot;&gt;&quot;Calling {0} ...&quot;&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;call_str&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
        result = f&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;x&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
        &lt;span class=&quot;kw1&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;&lt;span class=&quot;st0&quot;&gt;&quot;... returning from {0} = {1}&quot;&lt;/span&gt;.&lt;span class=&quot;me1&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;
              call_str, result&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;
        &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; result
    &lt;span class=&quot;kw1&quot;&gt;return&lt;/span&gt; helper
&amp;nbsp;
@memoize
@trace
&lt;span class=&quot;kw1&quot;&gt;def&lt;/span&gt; fib&lt;span class=&quot;br0&quot;&gt;&amp;#40;&lt;/span&gt;n&lt;span class=&quot;br0&quot;&gt;&amp;#41;&lt;/span&gt;:
    &lt;span class=&quot;co1&quot;&gt;# Same code as before...&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
Notice the use &lt;tt&gt;@memoize&lt;/tt&gt; and &lt;tt&gt;@trace&lt;/tt&gt; just before the definition of &lt;tt&gt;fib&lt;/tt&gt;. Now, when invoking &lt;tt&gt;fib&lt;/tt&gt;, first the &lt;tt&gt;memoize&lt;/tt&gt; decorator gets called, then the &lt;tt&gt;trace&lt;/tt&gt; decorator, and finally the original &lt;tt&gt;fib&lt;/tt&gt; code. Check this example: 
&lt;/p&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;
&gt;&gt;&gt; fib(5)
Calling fib(5) ...
Calling fib(4) ...
Calling fib(3) ...
Calling fib(2) ...
Calling fib(1) ...
... returning from fib(1) = 1
Calling fib(0) ...
... returning from fib(0) = 0
... returning from fib(2) = 1
... returning from fib(3) = 2
... returning from fib(4) = 3
... returning from fib(5) = 5
5
&lt;/pre&gt;
&lt;p&gt;
&lt;p&gt;
Python has three built-in functions that are intended to be used as function decorators:
&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;tt&gt;classmethod&lt;/tt&gt;: used to indicate that the decorated method is a class method, similar to those in Smalltalk or Ruby.&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;staticmethod&lt;/tt&gt;: used to indicate that the decorated method is a static method, like those in C++, C# or Java.&lt;/li&gt;
	&lt;li&gt;&lt;tt&gt;property&lt;/tt&gt;: used to decorate methods that will be used to get, set and delete object properties.&amp;nbsp; &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
It&#039;s also worth noting that Python 3.0 not only allows you to decorate functions, but also complete classes. Hopefully, I&#039;ll take some time to write about these specific kinds of decorators in a a future post. 
&lt;/p&gt;
&lt;p&gt;
&lt;span style=&quot;font-size: medium&quot;&gt;&lt;strong&gt;Notes&lt;/strong&gt;&lt;/span&gt;&lt;span style=&quot;font-size: medium&quot;&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;sup&gt;1&lt;/sup&gt; Yes, I know that using recursion to implement the Fibonacci sequence is very inefficient. But that was my intention. I wanted a simple algorithm that produces a perceivable time delay for certain inputs.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
&lt;span style=&quot;font-size: medium&quot;&gt;&lt;strong&gt;Further Reading&lt;/strong&gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href=&quot;http://www.python.org/dev/peps/pep-0318/&quot; target=&quot;_blank&quot;&gt;PEP: 318 Decorators for Functions and Methods&lt;/a&gt; 
&lt;/p&gt; 
</content> 
</entry> 
 
 <entry> 
 <id>tag:www.pythonblogs.com,2009-01-24:48</id>
 <title>Exploring Python&#039;s Awesomeness</title> 
 <link rel="alternate" type="text/html" href="http://programmingbits.pythonblogs.com/27_programmingbits/archive/48_exploring_pythons_awesomeness.html" /> 
  
 <modified>2009-01-24T06:23:02-08:00</modified> 
 <issued>2009-01-24T06:23:02-08:00</issued> 
 <created>2009-01-24T06:23:02-08:00</created> 
 <summary type="text/plain"> I recently saw  The Kung Fu Panda  movie, and it has this really cool and funny saying that made me think about the way I perceive the Python programming language: 
 
	 
	&amp;quot;There is no ...</summary> 
 <author> 
  
 <name>aortiz</name> 
 <url>http://programmingbits.pythonblogs.com/27_programmingbits</url> 
</author> 
<dc:subject>
General 
</dc:subject> 
 <content type="text/html" mode="escaped" xml:lang="en" xml:base="http://programmingbits.pythonblogs.com/27_programmingbits"> 
 &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;http://programmingbits.pythonblogs.com/plugins/plogeshi/styles/plogeshi.css&quot; /&gt;I recently saw &lt;em&gt;The Kung Fu Panda&lt;/em&gt; movie, and it has this really cool and funny saying that made me think about the way I perceive the Python programming language:&lt;br /&gt;
&lt;blockquote&gt;
	&lt;p&gt;
	&amp;quot;There is no charge for awesomeness... or attractiveness.&amp;quot;
	&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
&lt;img src=&quot;http://programmingbits.pythonblogs.com/gallery/27/panda.png&quot; alt=&quot;A panda bear image.&quot; align=&quot;left&quot; /&gt;
&lt;/p&gt;
&lt;p&gt;
Python is a really awsome language, and many people (including myself) find it extremely attractive. Additionally, it&#039;s an open language with great free implementations. What else can you ask for? 
&lt;/p&gt;
&lt;p&gt;
This is my first &lt;em&gt;ProgrammingBits&lt;/em&gt; post. It&#039;s my intention to
use this blog to write some insights about deep technical
(and maybe even philosophical) issues regarding the Python programming
language and its use in education. 
&lt;/p&gt;
&lt;p&gt;
I just basically want to give back a little bit of what I&#039;ve received from the generous Python community. Hopefully, some people will find my writings somehow useful. Or maybe just amusing. That&#039;s fine with me.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt; 
</content> 
</entry> 
 
</feed>