What should a decorator do if an attribute already exists?

Francesco Loffredo fal at fastwebnet.it
Mon May 16 04:14:26 EDT 2016


On 10/05/2016 17:45, Steven D'Aprano wrote:
> I have a decorator that adds an attribute to the decorated function:
>
>
> def decorate(func):
>      instrument = make_instrument()
>
>      @functools.wraps(func)
>      def inner(*args):
>          instrument.start()
>          result = func(*args)
>          instrument.finish()
>          return result
>
>     inner.instrument = instrument
>     return inner
>
>
> The actual nature of the instrumentation isn't important: depending on the
> decorator, it might count the number of function calls made, how long it
> takes, count cache hits, or something else.
>
> My question is, what should I do if the decorated function already has an
> instrument attribute?
>
> 1. raise an exception?
>
> 2. raise a warning, and over-write the attribute?
> 3. raise a warning, and skip adding the attribute?
> 4. raise a warning, and rename the existing instrument to
>     something else before writing my own instrument?
>
> 5. silently over-write the attribute?
>
>
> I think 5 is clearly wrong, 4 is too difficult, and 3 seems pointless. So I
> think either 1 or 2 is the right thing to do.
>
> Thoughts?
>
CAVEAT: I speak out of utter ignorance, please don't slap me if i'm 
saying something blatantly stupid...

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

What if you called your instrument "__instrument", taking advantage of 
name mangling?
This would, IMHO, solve entirely the name clash problem, and you could 
even access your instrument from outside, using its "mangled" name.
This, of course, leads to another question: what happens to name 
mangling in a decorator? What will be actually called the variable 
"__instrument"?

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

Francesco



More information about the Python-list mailing list