Python Typing: How to Reference Dynamically Created Class in Type Hints

187 views Asked by At

I'm trying to have an iterable of TextXClass instances for the implementation part of my meta-model but since that class is created dynamically, I'm out of luck. Is there still some clever way to type the individual elements of my model or will I have to essentially go with Iterable[Any]?

1

There are 1 answers

0
Jonathan Scholbach On

You can simply create the class dynamically, and forward reference it, by setting it in quotes. The link sais:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

A minimal example:

def expect_class_instance(instance: "MyClass"):
    pass


def factory():
    class SomeClass:
        pass

    return SomeClass

MyClass = factory()