Decorator Dissection

Bengt Richter bokr at oz.net
Sat Apr 2 17:24:12 EST 2005


On Sat, 02 Apr 2005 21:04:57 +0200, "Diez B. Roggisch" <deetsNOSPAM at web.de> wrote:

>> I followed that part.  The part that I'm having problems with is the
>> first nested function get's the argument for the function name without
>> a previous reference to the argument name in the outer frames. So, a
>> function call to it is being made with the function name as the
>> argument, and that isn't visable so it looks as if it's magic.
>
>No, its not - but I stepped into that trap before - and thought its magic :)
>
>The trick is to know that
>
> - a decorator is a callable
Strictly speaking, UIAM "deco" in @deco is a non-general
very-limited-syntax expression that should evaluate to a callable.
> - get passed a callable
> - has to return a callable

That last is a "should" ;-) Actually, you can abuse the def just
to provide a binding name whose associated function is otherwise ignored
(other than syntax check and compilation ), e.g.,

 >>> def maverick(f): return 'maverick'
 ...
 >>> @maverick
 ... def foo(): pass
 ...
 >>> foo
 'maverick'

Or

 >>> @str
 ... def foo(): pass
 ...
 >>> foo
 '<function foo at 0x02EE8D14>'

Note the quotes ;-)

 >>> type(foo)
 <type 'str'>

Just being picky about absolute statements ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list