Note This question is not about the Python 3 Enum
data type, it's just the example I'm using.
With PEP 3115 Python 3 added the __prepare__
1 method to type
for the purpose of allowing a custom namespace to be used when creating classes. For example, the new Enum
data type uses __prepare__
to return an instance of the private _EnumDict
for use as the new Enum
class' namespace.
However, I have seen several examples on SO2 of EnumMeta
being subclassed, creating a new namespace for the class in the metaclass __new__
method, but instead of calling the __prepare__
method to acquire that new namespace, type(clsdict)()
is used instead. Are there any risks to doing it this way?
1 The signature for __prepare__
:
@classmethod
def __prepare__(metacls, cls, bases, **kwds):
and for __new__
:
def __new__(metacls, cls, bases, clsdict, **kwds):
2 Example using type(clsdict)
:
from this answer
class CountryCodeMeta(enum.EnumMeta):
def __new__(metacls, cls, bases, classdict):
data = classdict['data']
names = [(country['alpha-2'], int(country['country-code'])) for country in data]
--> temp = type(classdict)()
for name, value in names:
temp[name] = value
excluded = set(temp) | set(('data',))
temp.update(item for item in classdict.items() if item[0] not in excluded)
return super(CountryCodeMeta, metacls).__new__(metacls, cls, bases, temp)