Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the dct argument of a metaclass __init__ method?

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?

like image 628
Milliams Avatar asked Oct 23 '25 01:10

Milliams


1 Answers

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.

like image 116
Pedro Werneck Avatar answered Oct 24 '25 13:10

Pedro Werneck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!