[Python] Why does __init_subclass__ behave unexpectedly when using metaclasses with dynamic...

Discussão em 'Python' iniciado por Stack, Julho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to dynamically generate classes in Python using a custom metaclass and hook into the class creation process using __init_subclass__. However, when I generate subclasses dynamically, it seems like __init_subclass__ isn’t called the way I expect or sometimes not at all.

    Example:

    class Base:
    def __init_subclass__(cls, **kwargs):
    print(f"Initialized subclass: {cls.__name__}")
    super().__init_subclass__(**kwargs)

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

    for i in range(3):
    class_name = f"DynamicClass{i}"
    globals()[class_name] = Meta(class_name, (Base,), {})


    I expected the __init_subclass__ method in Base to be triggered for each dynamically created subclass, but I’m not seeing the print output.

    My question is:

    • Why is __init_subclass__ not getting called here?
    • Is there a proper way to invoke it or ensure it runs when classes are generated dynamically with a metaclass?

    Continue reading...

Compartilhe esta Página