Order of operations when instantiating classes
The order of operations during class instantiation is very important to keep in mind when debugging issues with dynamically created and/or modified classes. Assuming an incorrect order can cause difficult-to-trace bugs. The instantiation of a class happens in the following order:
- Finding the metaclass
- Preparing the namespace
- Executing the class body
- Creating the class object
- Executing the class decorators
- Creating the class instance
We will go through each of these now.
Finding the metaclass
The metaclass comes from either the explicitly given metaclass on the class or bases
, or by using the default type
metaclass.
For every class, the class itself and the bases, the first matching of the following will be used:
- Explicitly given metaclass
- Explicit metaclass from
bases
type()
Note that if no metaclass is found that is a subtype of all...