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

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to