What should a decorator do if an attribute already exists?

Steven D'Aprano steve at pearwood.info
Tue May 10 11:45:29 EDT 2016


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?



-- 
Steven




More information about the Python-list mailing list