Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: __init_subclass__() takes no keyword arguments

I'm trying to create a metaclass but when I assign it to another class I receive the error TypeError: __init_subclass__() takes no keyword arguments but I don't implement any __init_subclass__. Why is this function being called?

class Meta(type):
    def __new__(cls, name, bases, dct):
        return super().__new__(cls, name, bases, dct)

class MyClass(meta=Meta):
    pass
like image 218
Robin De Schepper Avatar asked Jan 24 '23 19:01

Robin De Schepper


1 Answers

Change meta to metaclass. Any keyword arguments passed to the signature of your class are passed to its parent's __init_subclass__ method. Since you entered meta instead of metaclass this meta kwarg is passed to its parent's (object) __init_subclass__ method:

>>> object.__init_subclass__(meta=5)
TypeError: __init_subclass__() takes no keyword arguments

A similar error would be raised if you actually implemented a __init_subclass__ but made a typo:

class Parent:
  def __init_subclass__(cls, handler=None):
    super().__init_subclass__()
    cls.handler = handler

class CorrectChild(Parent, handler=5):
  pass

class TypoChild(Parent, handle=5):
  # TypeError: __init_subclass__() got an unexpected keyword argument 'handle'
  pass
like image 176
Robin De Schepper Avatar answered Feb 01 '23 23:02

Robin De Schepper