26

How do you decide between using decorators and inheritance when both are possible?

E.g., this problem has two solutions.

I'm particularly interested in Python.

5
  • 1
    If both are possible then the scope of the problem is too small. Commented Jun 20, 2011 at 3:02
  • @Neil G: It's a contrived problem where lots of choices are possible because there aren't enough constraints to make a choice.
    – S.Lott
    Commented Jun 20, 2011 at 3:25
  • 1
    @S.Lott: I understand what you're saying. For the record, it's not "contrived" — It's a real piece of code, and it got me thinking about software design, and I wanted to get an idea of how other people perceive choosing between decorators and inheritance. Coming from a C++ background, I haven't made this choice often. Anyway, thanks for your point about the lack of constraints. It's a good point.
    – Neil G
    Commented Jun 20, 2011 at 3:35
  • @Neil G: actually the solution by mouad at stackoverflow.com/questions/6394511/… is just fine; the way his and mine work is by redefining the decorator into a "hygienic decorator v2.0", so that when decorator v2.0 is applied, it does what it's supposed to do (memoize) but also makes sure the special attributes like __doc__ are transferred. The only difference between the two is that his replaces the memoize(...) decorator with a class, while mine replaces it with a function. Not much difference.
    – ninjagecko
    Commented Jun 20, 2011 at 4:17
  • @ninjagecko: yes, I figured that much out. It's still weird for me to think about decorators and keep everything straight.
    – Neil G
    Commented Jun 20, 2011 at 4:21

5 Answers 5

24

Decorators...:

  • ...should be used if what you are trying to do is "wrapping". Wrapping consists of taking something, modifying (or registering it with something), and/or returning a proxy object that behaves "almost exactly" like the original.
  • ...are okay for applying mixin-like behavior, as long as you aren't creating a large stack of proxy objects.
  • ...have an implied "stack" abstraction:

e.g.

@decoA
@decoB
@decoC
def myFunc(...): ...
    ...

Is equivalent to:

def myFunc(...): ...
    ...
myFunc = decoA(decoB(decoC(myFunc)))  #note the *ordering*

Multiple inheritance...:

  • ... is best for adding methods to classes; you cannot use it to decorate functions easily. In this context, it can be used to achieve mixin-like behavior if all you need is a set of "duck-typing style" extra methods.
  • ... may be a bit unwieldy if your problem is not a good match for it, with issues with superclass constructors, etc. For example, the subclasses __init__ method will not be called unless it is called explicitly (via the method-resolution-order protocol)!

To sum up, I would use decorators for mixin-like behavior if they didn't return proxy objects. Some examples would include any decorator which returns the original function, slightly modified (or after registering it somewhere or adding it to some collection).

Things you will often find decorators for (like memoization) are also good candidates, but should be used in moderation if they return proxy objects; the order they are applied matter. And too many decorators on top of one another is using them in a way they aren't intended to be used.

I would consider using inheritance if it was a "classic inheritance problem", or if all I needed for the mixin behavior were methods. A classic inheritance problem is one where you can use the child wherever you could use the parent.

In general, I try to write code where it is not necessary to enhance arbitrary things.

3
  • 3
    Thinking about this some more, I think a key point is the issubclass and isinstance that are made available by inheritance. If you want those, you probably want inheritance. This justifies Collections.*, being implemented using inheritance rather than decorators.
    – Neil G
    Commented Jun 20, 2011 at 6:56
  • 1
    @Neil: that is exactly what I was getting at when I said "where you can use the child wherever you could use the parent" =)
    – ninjagecko
    Commented Jun 20, 2011 at 6:59
  • 2
    I also want to point out since it's not obvious in your answer that multiple inheritance in Python (unlike, e.g., C++) does have a stack abstraction due to co-operative inheritance. Each successive base class's __init__ sees a modified object.
    – Neil G
    Commented Jun 20, 2011 at 19:16
7

The other answers are quite great, but I wanted to give a succinct list of pros and cons.

The main advantage of mixins is that the type can be checked at runtime using isinstance and it can be checked with linters like MyPy. Like all inheritance, it should be used when you have an is-a relationship. For example dataclass should probably have been a mixin in order to expose dataclass-specific introspection variables like the list of dataclass fields.

Decorators should be preferred when you don't have an is-a relationship. For example, a decorator that propagates documentation from another class, or registers a class in some collection.

Decoration typically only affects the class it decorates, but not classes that inherit from the base class:

@decorator
class A:
    ...  # Can be affected by the decorator.

class B(A):
    ...  # Not affected by the decorator in most cases.

Now that Python has __init_subclass__, everything that decorators can do can be done with mixins, and they typically do affect child subclasses:

class A(Mixin):
    ... # Is affected by Mixin.__init_subclass__.

class B(A):
    ... # Is affected by Mixin.__init_subclass__.

Mixins have another advantage, which is that they can provide empty base class methods. Child classes can override these methods with some "augmenting" behavior, and then call super. The decorator cannot easily provide such base class methods. This is another way in which mixins are more flexible.

In summary, the questions you should ask when deciding between a mixin and decoration are:

  • Is there an is-a pattern?
    • Would you ever call isinstance?
    • Would you use the mixin in a type annotation?
  • Do you want the behavior to affect child classes?
  • Do you need augmenting methods?

In general, lean towards inheritance.

5

The problem you reference is not deciding between decorators and classes. It is using decorators, but you have the option of using either:

  • a decorator, which returns a class
  • a decorator, which returns a function

A decorator is just a fancy name for the "wrapper" pattern, i.e. replacing something with something else. The implementation is up to you (class or function).

When deciding between them, it's completely a matter of personal preference. You can do everything you can do in one with the other.

  • if decorating a function, you may prefer decorators which return proxy functions
  • if decorating a class, you may prefer decorators which return proxy classes

(Why is it a good idea? There may be assumptions that a decorated function is still a function, and a decorated class is still a class.)

Even better in both cases would be to use a decorator which just returns the original, modified somehow.

edit: After better understanding your question, I have posted another solution at Python functools.wraps equivalent for classes

0
1

If both are equivalent, I would prefer decorators, since you can use the same decorator for many classes, while inheriting apply to only one specific class.

3
  • 1
    If this was what the OP actually meant to ask, this would be the perfect answer in languages with single-inheritance. I feel using subclasses would be fine in python though, because one can use multiple inheritance to achieve mixin-like behavior. On one hand I find them a bit harder to deal with; on the other hand, mixins don't lend themselves to the stack abstraction that decorators kind of imply.
    – ninjagecko
    Commented Jun 20, 2011 at 3:15
  • 1
    @ninjagecko: this comment is exactly what I'm looking for. What do you mean by the "stack abstraction"?
    – Neil G
    Commented Jun 20, 2011 at 3:23
  • apologies, I was almost certain Neil was asking something else.
    – ninjagecko
    Commented Jun 20, 2011 at 3:41
1

Personally, I would think in terms of code reuse. Decorator is sometimes more flexible than inheritance.

Let's take caching as an example. If you want to add caching facility to two classes in your system: A and B, with inheritance, you'll probably wind up having ACached and BCached. And by overriding some of the methods in these classes, you'll probably duplicate a lot of codes for the same caching logic. But if you use decorator in this case, you only need to define one decorator to decorate both classes.

So, when deciding which one to use, you may first want to check if the extended functionality is only specific to this class or if the same extended functionality can be reused in other parts of your system. If it cannot be reused, then inheritance should probably do the job. Otherwise, you can think about using decorator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.