Given a Python 2 metaclass defined as:
class Meta(type):
def __init__(cls, name, bases, dct):
pass
what is the purpose of the dct argument? Based on what I've found, it contains identical information to cls.__dict__. The difference being that making changes to dct has no effect on the concrete class but adding things to cls.__dict__ (i.e. by cls.__dict__['a']=True or cls.a=True) will have an effect.
class Meta(type):
def __init__(cls, name, bases, dct):
cls.a = True
dct['b'] = True
class Test(object):
__metaclass__ = Meta
t = Test()
print t.a
print t.b # Raises an AttributeError
Are there situations where they are different?
The dct parameter provides you with the original class namespace, so it's not really used in the metaclass __init__ as the class was already created in __new__. The dct and cls.__dict__ might be equal, but they are not the same dictionary. It can be useful in a situation where you might need the information contained in the original namespace, without any manipulation performed by the __new__ method or by parent metaclasses.
They might be different if the __new__ method is adding attributes to the class -- after its creation -- that weren't in the original namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With