Python Metaclass
Python Metaclass
In backtrader py3.py
class, there is a magic method which is used extensively by the code.
The with_metaclass()
function makes use of the fact that metaclasses are
a) inherited by subclasses, and
b) a metaclass can be used to generate new classes and
c) when you subclass from a base class with a metaclass, creating the actual subclass object is delegated to the metaclass.
d)
type.__new__(metaclass, 'temporary_class', (), {})
uses themetaclass
metaclass to create a new class object namedtemporary_class
that is entirely empty otherwise.type.__new__(metaclass, ...)
is used instead ofmetaclass(...)
to avoid using the specialmetaclass.__new__()
implementation that is needed for the slight of hand in a next step to work.If
metaclass(...)
is used there will be an extratemporary_class
base class.
It effectively creates a new, temporary base class with a temporary metaclass metaclass
that, when used to create the subclass swaps out the temporary base class.
and it could be used as
At
L1
a class namedtemporary_class
has been created frommetaclass
and assigned to a local variable also namedtemporary_class
.At
L2
when thetemporary_class
is used as the base class, creating the actualFoo
class will be delegated to the temporary_classthe
def __new__(cls, name, this_bases, d)
function will be called andmetaclass
,Foo
,temporary_class
and{}
will be passed in. Thenmeta(name, bases, d)
will be used to create the actualFoo
class. Note that as no instance ofmetaclass
is return in the__new__
method, the__init__
method inside themetaclass
will never be called.
Tests
Reference
Last updated
Was this helpful?