Differences between class and function decorator

Terry Reedy tjreedy at udel.edu
Fri Jan 16 20:27:45 EST 2009


mk wrote:
> Hello everyone,
> 
> I rewrote an example someone posted here recently from:
> 
>  >>> def print_method_name(method):
>     def new_meth(*args, **kwargs):
>         print method.func_name
>         return method(*args, **kwargs)
>     return new_meth
> 
>  >>> @print_method_name
> def f2():
>     pass
> 
>  >>> f2()
> f2
> 
> 
> ..to:
> 
>  >>> class MyMethod(object):
>     def __init__(self, func):
>         self.name = func.func_name
>         self.func = func
>     def __call__(self):
>         print self.name
>         return self.func
> 
>     
>  >>> @MyMethod
> def f():
>     pass
> 
>  >>> f()
> f
> <function f at 0x017CDA70>
> 
> Note that function decorator returned None, while class decorator 
> returned function.

To repeat and expand a bit what I said to the OP: these are both 
callables (functions in the math sense) because they both of instances 
of a class with a .__call__ instance method.  Both are used as function 
decorators.  One is an instance of class 'function', the other an 
instance of class 'MyMethod'.  The class difference is not relevant to 
the usage.  This is duck typing in action.

A class decorator is a callable (in 2.6+/3.0+) that decorates a class.

tjr




More information about the Python-list mailing list