What should a decorator do if an attribute already exists?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue May 17 01:12:23 EDT 2016
On Monday 16 May 2016 23:06, Kevin Conway wrote:
>> I have a decorator that adds an attribute to the decorated function
>
> I might try to argue that this is not actually a decorator or, at least,
> this is not a great decorator pattern for Python. Adding the attribute to
> the function object implies you need to access it at some later point. If
> so then your decorator has changed the public interface of the wrapped
> item. Downstream code will depend on the new interface which is only
> provided by the decorator so it becomes a hard requirement.
This analysis is correct, apart from the value judgement "this is not a great
decorator pattern".
> IMO, decorators are supposed to be transparent. Removing a decorator should
> not invalidate other code.
Consider the three most obvious decorators in the language: property,
classmethod and staticmethod. What happens if you remove them?
> With your particular example, I believe you are actually implementing a
> context manager and the more appropriate code would look like:
>
> with Instrument() as instrument:
> # other code
It is funny you say that, because my project offers a context manager interface
as well.
The context manager interface is based on this recipe:
http://code.activestate.com/recipes/577896
but it adds a decorator interface so you can decorate a function, run the
function as often as you want, then look at the timing statistics.
--
Steve
More information about the Python-list
mailing list