A fleeting thought that maybe I've been writing Python class decorators wrong all along.

To elaborate, I've been thinking about how a class decorator expands into something like `cls = decorator(cls)`. A function call. So, why in the hell do most class decorators *mutate* the cls argument in-place as a side effect? (a very non-function kind of thing to do).

I've done this with class decorators in my books, but I'm hardly the only offender. Also class decorators in the standard library (e.g., dataclass) mutate the class. It now just feels off to me.

To further elaborate, I got to thinking about this in the context of mixins. Class decorators are sometimes pitched as an alternative to mixin classes. Which is fine except for the fact that mixins DON'T mutate the other classes that they're mixed with.

I was also thinking about this in the context of dependency injection. Could you use a class decorator in a different way to provide a modified class as a dependency? Yes, but it only works once if there's mutation.

Follow

@dabeaz

Decorators shouldn't mutate the wrapped object(s). Perhaps it can work in many cases, but imagine for instance that the underlying instance is an authorized network connection.

I have not seen the "mutate" approach in any actual code, but I am mostly in the Java ecosystem and not Python.

· · Web · 1 · 0 · 0

@niclas @dabeaz Decorator in Python can be used on functions and classes. They never wrap objects. So no references exist outside of the decorator, yet.

But now think about using decorators to integrate into a registry of classes. Then developers will get grumpy, if some decorator would generate a copy of the class.

Sign in to participate in the conversation
Angry Today?

Angry People are Most Welcome! Vent your frustration and go nuts on things that irritates you.