Search code examples
pythonpython-3.xkeyword-argument

How to pass kwargs to __init_subclass__ when creating dynamic class


How can I pass values to kwargs parameter in the __init__subclass__() when creating a dynamic class with type()

class Base():
    def __init_subclass__(cls, **kwargs):
        print (kwargs)

class Derived(Base, arg1='test_val'):
    pass


op: {'arg1': 'test_val'}

How can I do this with type() ?

type('newtype', (Base,), {})

Solution

  • You need to use types.new_class instead of type. E.g.

    from types import new_class
    
    new_class('newtype', (Base,), {'arg1': 'test_val'})