Lifu Huang
Lifu Huang

Reputation: 12778

What does class `type.__init__` and `type.__new__` do when creating a new `type` instance(i.e. class)?

As is known to all, there are many jobs are done behind the scenes when creating a new class in Python, such as setting attributes like __dict__, __class__, __metaclass__, etc.

I know that when creating a new class, the type.__new__ method will be called, and type.__init__ will also be called on condition that call.__new__ returns a instance of type. So I guess these two methods might be in charge of some of the work, but I cannot find any description in docs about their real function. My question is, what exactly do these two methods do for making a class?

EDIT:

I know what a metaclass is and what roughly metaclass does in the process of creating a type instance, but I am wondering about how these two methods cooperate to achieve the job of creating a type instance. Maybe @BrenBarn is right that this is implementation related. And I just want to make sure about that. For example, if I rewrite the __new__ method in my own metaclass T, and return type(clsname, bases, dct) directly instead of calling __new__ in base class type as what people usually do, then neither T.__init__ nor type.__init__ will be called, since returned object is not an instance of T. If so, what am I expecting to miss owing to the absense of __init__? And also, can I expect that to be a consistent behavior across various implementations?

Upvotes: 5

Views: 1302

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226296

am wondering about how these two methods cooperate to achieve the job of creating a type instance

The type.__init__ method is only responsible for checking that there are 1 or 3 arguments and that there are no keyword arguments. The C source code for this is in the type_init() function in Objects/typeobject.c.

The type.__new__ method does all of the rest work in creating a new class. Here are the steps for type_new_impl in Objects/typeobject.c:

  • type_new_init()
  • type_new_set_attrs()
  • PyType_Ready()
  • fixup_slot_dispatchers()
  • type_new_set_names()
  • type_new_init_subclass()

Upvotes: 2

Related Questions