[Python] How to annotate classes that are created dynamically?

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    Based on this accepted answer, I have done:

    from typing import Type


    class BaseEntity:
    id: str


    def make_new_entity(name: str, attrs: dict) -> Type[BaseEntity]:
    return type("RuntimeEntity", (BaseEntity,), attrs)


    RuntimeEntity: Type[BaseEntity] = make_new_entity("RuntimeEntity", {"id": "entity.RuntimeEntity"})

    # My code from here

    class Foo:
    entity_instances: list[RuntimeEntity] # <- Here, linter is yelling at me
    other_entity_instances: list["RuntimeEntity"] # <- Same, linter is yelling at me




    I have :

    • from Pylance Variable not allowed in type expression PylancereportInvalidTypeForm
    • from mypy error: Variable "foo.RuntimeEntity" is not valid as a type [valid-type]

    Why ? What is the correct what to annotate a class created dynamically?

    Continue reading...

Compartilhe esta Página