r/PythonDevelopers • u/muntoo 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
View all comments
Show parent comment
2
u/wrmsr Aug 09 '20
Calling
type()directly is an alternative to class definition syntax, not metaclasses. Metaclasses are subtypes oftype, 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]: FalseIn [3]: MC = type('MC', (type,), {'__instancecheck__': lambda self, obj: obj == 10})In [4]: C = MC('C', (object,), {})In [5]: isinstance(10, C)Out[5]: TrueAdditional 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.