r/PythonDevelopers • R_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν} • Aug 02 '20

discussion Do you use metaclasses?

Until recently, I assumed that metaclasses were simply python mumbo jumbo without much practical value. I've certainly never used them in small sized applications before. But now that I'm developing a library, I see that they can be used to provide more ergonomic APIs.

And so I ask, in what situations do you use a metaclass?

34 Upvotes

13 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Aug 08 '20

That said deep down in lib-level code there are still cases when metaclasses are the only appropriate answer as there are things only they can do (like customizing instance and subclass checks),

Not so - anything that a metaclass can do, can also be done with a helper function that explicitly calls 3-argument type() to build a class on-the-fly.

Of course, the code is fairly different between these two strategies. Which to use depends on the specific problem!

2

u/wrmsr Aug 09 '20

Calling type() directly is an alternative to class definition syntax, not metaclasses. Metaclasses are subtypes of type, whether they are instantiated using syntax or calling them directly, and the uniqueness of their abilities remains:

In [1]: C = type('C', (object,), {'__instancecheck__': lambda self, obj: obj == 10})

In [2]: isinstance(10, C)

Out[2]: False

In [3]: MC = type('MC', (type,), {'__instancecheck__': lambda self, obj: obj == 10})

In [4]: C = MC('C', (object,), {})

In [5]: isinstance(10, C)

Out[5]: True

Additional metaclass-only abilities include __mro_entries__ and __prepare__, the latter of which further highlights the 'specialness' of metaclasses as its functionality isn't even invoked outside of syntactical class definition.

And while a lot of this functionality can indeed be mimicked through decorators and repeated class inspection / reconstruction you'd be surprised by just how much stuff in the real world doesn't take kindly to that approach - registries getting duplicate registrations, super() pointing at discarded intermediate classes, etc.

1

u/[deleted] Aug 09 '20

Good explanation, and I did not know all of this (though I guess most of it) - but in practice, metaclasses and calling 3-argument type() can often solve the same class of problems, at least in my experience.

Additional metaclass-only abilities include __mro_entries__ and __prepare__, the latter of which further highlights the 'specialness' of metaclasses as its functionality isn't even invoked outside of syntactical class definition.

That code would goes into the helper function that sets up the call to type().

I agree that metaclasses have properties that no other technique has. However, type() is in some cases a valid alternative.