Home > Mobile >  Is there a typing hint in Python for a generic class?
Is there a typing hint in Python for a generic class?

Time:10-29

I have some legacy code that I inherited that creates a class on the fly within a method. The type returned is just <class 'module'>. How do I type hint this?

I know I can use Any, but I was hoping for something a bit more specific.

CodePudding user response:

Well, if the type is <class 'module'> that means it returns modules. The annotation for that is the types.ModuleType. And it is not generic.

CodePudding user response:

You can use Type. It's a generic, and you have to provide it with the base class of the class you create on the flight. If you don't know the base class, you can do Type[Any].

def create_class() -> Type[Any]:
    return type("Foo", tuple(), {})
  • Related