What should a decorator do if an attribute already exists?

Kevin Conway kevinjacobconway at gmail.com
Mon May 16 09:06:51 EDT 2016


> 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.

IMO, decorators are supposed to be transparent. Removing a decorator should
not invalidate other code.

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

On Mon, May 16, 2016, 07:23 jmp <jeanmichel at sequans.com> wrote:

> On 05/10/2016 05:45 PM, Steven D'Aprano wrote:
> > I have a decorator that adds an attribute to the decorated function:
> [snip]
> > 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?
>
> It depends if the attribute "instrument" is part of the public interface.
>
> If not, just find a different name unlikely to clash with an existing
> one *and* raise an exception if it does ever happen anyway.
>
> If the attribute is part of the public interface but you re using the
> code only internally then 1/ raise an exception, otherwise I don't know :o)
>
> It seems to me that over-writing silently (or not) may lead to bugs
> difficult to spot.
>
> jmp
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list