pythontype-hinting

How to add type hinting to "class" type in python


# Java
public <T> T findById(String id, Class<T> clazz)

How should the Class<T> type in the above Java method signature be represented by Python type hint?

# Python
def find_by_id(id: str, clazz: ???) -> T

Solution

  • To annotate the type of a class itself, use Type.

    class AClass:
        ...
    
    
    def a_function(a_string: str, a_class: type[AClass]) -> None:
        ...
    

    Since a class is a type, the class name can be an annotation itself:

    def a_class_factory(a_class: type[AClass], *args, **kwargs) -> AClass:
        return a_class(*args, **kwargs)