What's The Correct Way To Implement A Metaclass With A Different Signature Than `type`?
Say I want to implement a metaclass that should serve as a class factory. But unlike the type constructor, which takes 3 arguments, my metaclass should be callable without any argu
Solution 1:
An interface deviating from the parent signature is a questionable design in regular classes too. You don't need the extra complexity of metaclasses to get into this kind of mess - you can cause the same new/init jumble by subclassing a datetime
or whatever.
I want to have a metaclass and an easy way to create instances of that metaclass.
The usual pattern in Python is to write a factory using a from_something
classmethod. To take the example of creating datetime instances from a different init signature, there is for example datetime.fromtimestamp
, but you have many other examples too (dict.fromkeys
, int.from_bytes
, bytes.fromhex
...)
There is nothing specific to metaclasses here, so use the same pattern:
classMyMeta(type):
@classmethoddeffrom_no_args(cls, name=None):
if name isNone:
name = cls.__name__ + 'Instance'return cls(name, (), {})
Usage:
>>>classA(metaclass=MyMeta):...pass...>>>B = MyMeta.from_no_args()>>>C = MyMeta.from_no_args(name='C')>>>A.__name__
'A'
>>>B.__name__
'MyMetaInstance'
>>>C.__name__
'C'
Post a Comment for "What's The Correct Way To Implement A Metaclass With A Different Signature Than `type`?"