Issue 36178: type.init called instead of cls.init when inheriting from type. (original) (raw)
I may be completely misunderstanding here, but: here's a reproducible example:
class MyMeta(type): def new(cls, *args, **kwargs): print('new', *args, **kwargs) super().new(cls, *args, **kwargs)
def __init__(self, a):
print('__init__', *args, **kwargs)
super().__init__(*args, **kwargs)
class A(metaclass=MyMeta): pass
MyMeta('A', (), {'module': 'main', 'qualname': 'A'})
Output:
new A () {'module': 'main', 'qualname': 'A'} new A () {'module': 'main', 'qualname': 'A'}
Is this by design?
Your metaclass.new method returns None instead of the new class. The rule for calling init is:
if the constructor new returns an instance of the type, then call the initializer init
otherwise, don't call init at all.
https://docs.python.org/3/reference/datamodel.html#object.new
Since your new accidentally returns None, the init is not called. If you change the line to say
return super().new(cls, *args, **kwargs)
you will see that init is called. (And discover the bugs in your init method :-)