A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2006-April/063260.html below:

[Python-Dev] Class decorators

[Python-Dev] Class decoratorsNick Coghlan ncoghlan at gmail.com
Sat Apr 1 06:58:34 CEST 2006
Jim Jewett wrote:
> Nick Coghlan wrote:
> 
>> [ much good, including the @instance decorator ]
> 
>> P.S.  If all you want is somewhere to store mutable
>> state between invocations, you can always use the
>> function's own attribute space
> 
>     >>> def f(): print "Hi world from %s!" % f
> 
>     >>> f()
>     Hi world from <function f at 0x00AE90B0>!
> 
> Not really.  That assumes the expected name is (permanently) bound to
> *this* function in this function's globals.  That's normally true, but
> not always, so relying on it seems wrong.

Well, true. If you want it to be bullet-proof, you have to use a closure instead:

 >>> def make_f():
...     def f():
...         print "Hi world from %s!" % f
...     return f
...
 >>> f = make_f()
 >>> f()
Hi world from <function f at 0x00AE90B0>!

The point about the decorators still holds - they stay with the function 
they're decorating (the inner one), and you don't need to make any of the 
changes needed in order to decorate the class instead.

The above is also a use case for a *function* decorator I've occasionally 
wanted - an @result decorator, that is the equivalent of the @instance 
decorator I suggested for classes:


 >>> def result(f):
...     return f()
...
 >>> @result
... def f():
...     def f():
...         print "Hi world from %s!" % f
...     return f
...
 >>> f()
Hi world from <function f at 0x00AE90B0>!

I never actually did it, though, as I was stuck on Python 2.2 at the time.

This is something of a tangent to the real discussion though, so I'll leave 
this one there :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org
More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4