otsuka
otsuka

Reputation: 139

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

Upvotes: 3

Views: 2214

Answers (1)

kojiro
kojiro

Reputation: 77059

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)

Upvotes: 6

Related Questions