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   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to