When discussing metaclasses, the docs state:
You can of course also override other class methods (or add new methods); for example defining a custom
__call__()
method in the metaclass allows custom behavior when the class is called, e.g. not always creating a new instance.
[Editor’s note: This was removed from the docs in 3.3. It’s here in 3.2: Customizing class creation]
My questions is: suppose I want to have custom behavior when the class is called, for example caching instead of creating fresh objects. I can do this by overriding the __new__
method of the class. When would I want to define a metaclass with __call__
instead? What does this approach give that isn’t achievable with __new__
?
Advertisement
Answer
The direct answer to your question is: when you want to do more than just customize instance creation, or when you want to separate what the class does from how it’s created.
See my answer to Creating a singleton in Python and the associated discussion.
There are several advantages.
It allows you to separate what the class does from the details of how it’s created. The metaclass and class are each responsible for one thing.
You can write the code once in a metaclass, and use it for customizing several classes’ call behavior without worrying about multiple inheritance.
Subclasses can override behavior in their
__new__
method, but__call__
on a metaclass doesn’t have to even call__new__
at all.If there is setup work, you can do it in the
__new__
method of the metaclass, and it only happens once, instead of every time the class is called.
There are certainly lots of cases where customizing __new__
works just as well if you’re not worried about the single responsibility principle.
But there are other use cases that have to happen earlier, when the class is created, rather than when the instance is created. It’s when these come in to play that a metaclass is necessary. See What are your (concrete) use-cases for metaclasses in Python? for lots of great examples.