[Python-Dev] More concerns about decorators

Bob Ippolito bob at redivi.com
Mon Aug 16 18:19:09 CEST 2004


On Aug 16, 2004, at 11:39 AM, Roman Suzi wrote:

> On Mon, 16 Aug 2004, Michael Hudson wrote:
>
>> Bob Ippolito <bob at redivi.com> writes:
>>
>>>> Is it possible to change function inplace? Is it even an option?
>>>
>>> Not sure what you mean.  Functions have a __doc__ slot and a __dict__
>>> slot that are read/write.  __name__ is read-only.
>>
>> __name__ is writable as of a few days ago.
>
> I mean that decorators are... decorators. They by their meaning must 
> not
> change the function but add some twists to their behaviour. Many of 
> decorator
> examples are destructing function attributes.

Some decorators are "decorators", other decorators are transformations 
:)  staticmethod and classmethod certainly aren't "decorators" as they 
change what the function does and return a different object, from an 
implementation standpoint anyway.

> Good example of non-destructing decorator is staticmethod:

Not all decorators are non-destructive.

> So, my concern was that it requires additional efforts to save
> function attributes. My thought was that probably decorators could
> work directly on the function, not changing id of the function?
> (staticmethod changes id, of course). Why? Because the function
> is not accessible any more. while the old way it was possible to store
> intermediate result:

Most, if not all, useful decorators will need to change the id of the 
function.  Even a decorator that optimizes bytecode would have to 
return a new object.  The only things you can do to a function without 
changing its identity (IIRC) are changing the slots __name__, __doc__, 
and __dict__.

> class A:
>      def m(x):
>         """I am method m"""
>      mm = m
>      m = staticmethod(m)
>
>
> And use it somehow. But with decorator function changes. Yes, it is 
> possible
> that some decorators could store function internally for the purpose of
> calling it, but others will not.

I think that most decorators are going to store the function object one 
way or another.  I'm not sure why that matters though?  I've never seen 
production code that uses this pattern (save out an instance method and 
a staticmethod of separate names), except for properties (which is 
somewhat different).

> The transfer of function attributes is on the developer.  And he/she 
> could be
> clueless that docstrings, etc, could be lost in transformation.

That already happens if you do decoration "manually" the pre-2.4 way.  
As long as its documented, it shouldn't be a problem.  A "carryover" 
function as I offered up in my last email (modified to also bring over 
__name__) would help considerably, I think.

-bob


More information about the Python-Dev mailing list