What should a decorator do if an attribute already exists?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue May 17 01:05:06 EDT 2016


On Monday 16 May 2016 18:14, Francesco Loffredo wrote:

> On 10/05/2016 17:45, Steven D'Aprano wrote:
>> I have a decorator that adds an attribute to the decorated function:
[...]
>> My question is, what should I do if the decorated function already has an
>> instrument attribute?

>  From your example, it seems that you use your instrument only inside
> your decorator. So I think "instrument" could be a "private variable".

My example was misleading, sorry about that.

Although the instrumentation is used inside the decorator, it is actually part 
of the public API for the function. So the user can do this:


@decorate
def myfunction():
    ...


# later
myfunction.instrument.query()

and see what data has been collected.

So it is important that the name of the attribute be a public name.


> What if you called your instrument "__instrument", taking advantage of
> name mangling?

Double underscore name-mangling only works inside classes.

[...]
> And what happens if you want to add another instrument, decorating the
> target twice?

If the names are the same, the second decorator will over-write the first 
decorator's instrumentation with its own.




-- 
Steve




More information about the Python-list mailing list