3
# 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
2
  • Possible duplicate of Type hints with user defined classes Commented Nov 3, 2019 at 14:41
  • Not a dupe IMO. That question is, at best, ambiguous about whether it asks for the instance or the class. This one is explicit. Commented Nov 3, 2019 at 17:02

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

1 Comment

since Python 3.9, Type is deprecated and type should be used now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.