简体   繁体   中英

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

To annotate the type of a class itself, useType .

from typing import Type

class AClass(object):
    pass

def a_function(a_string: str, a_class: Type[AClass]) -> None:
    pass

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)

You can resolve an annotation at runtime. See PEP 563

The functionality described above can be enabled starting from Python 3.7 using the following special import:

from __future__ import annotations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM