python 类型标注-typing --- 类型标注支持 — Python 3.7.9 文档

类,函数和修饰器.¶

这个模块定义了如下的类,模块和修饰器.

classtyping.TypeVar¶

类型变量

用法:

T = TypeVar("T") # Can be anything

A = TypeVar("A", str, bytes) # Must be str or bytes

Type variables exist primarily for the benefit of static type

checkers. They serve as the parameters for generic types as well

as for generic function definitions. See class Generic for more

information on generic types. Generic functions work as follows:

def repeat(x: T, n: int) -> Sequence[T]:

"""Return a list containing n references to x."""

return [x]*n

def longest(x: A, y: A) -> A:

"""Return the longest of two strings."""

return x if len(x) >= len(y) else y

The latter example"s signature is essentially the overloading

of (str, str) -> str and (bytes, bytes) -> bytes. Also note

that if the arguments are instances of some subclass of str,

the return type is still plain str.

isinstance(x, T) 会在运行时抛出 TypeError 异常。一般地说, isinstance() 和 issubclass() 不应该和类型一起使用。

Type variables may be marked covariant or contravariant by passing

covariant=True or contravariant=True. See PEP 484 for more

details. By default type variables are invariant. Alternatively,

a type variable may specify an upper bound using bound=.

This means that an actual type substituted (explicitly or implicitly)

for the type variable must be a subclass of the boundary type,

see PEP 484.

classtyping.Generic¶

Abstract base class for generic types.

A generic type is typically declared by inheriting from an

instantiation of this class with one or more type variables.

For example, a generic mapping type might be defined as:

class Mapping(Generic[KT, VT]):

def __getitem__(self, key: KT) -> VT:

...

# Etc.

这个类之后可以被这样用:

X = TypeVar("X")

Y = TypeVar("Y")

def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:

try:

return mapping[key]

except KeyError:

return default

classtyping.Type(Generic[CT_co])¶

A variable annotated with C may accept a value of type C. In

contrast, a variable annotated with Type[C] may accept values that are

classes themselves -- specifically, it will accept the class object of

C. For example:

a = 3 # Has type "int"

b = int # Has type "Type[int]"

c = type(a) # Also has type "Type[int]"

Note that Type[C] is covariant:

class User: ...

class BasicUser(User): ...

class ProUser(User): ...

class TeamUser(User): ...

# Accepts User, BasicUser, ProUser, TeamUser, ...

def make_new_user(user_class: Type[User]) -> User:

# ...

return user_class()

The fact that Type[C] is covariant implies that all subclasses of

C should implement the same constructor signature and class method

signatures as C. The type checker should flag violations of this,

but should also allow constructor calls in subclasses that match the

constructor calls in the indicated base class. How the type checker is

required to handle this particular case may change in future revisions of

PEP 484.

The only legal parameters for Type are classes, Any,

type variables, and unions of any of these types.

For example:

def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...

Type[Any] is equivalent to Type which in turn is equivalent

to type, which is the root of Python"s metaclass hierarchy.

3.5.2 新版功能.

classtyping.Iterable(Generic[T_co])¶

classtyping.Iterator(Iterable[T_co])¶

classtyping.Reversible(Iterable[T_co])¶

classtyping.SupportsInt¶

An ABC with one abstract method __int__.

classtyping.SupportsFloat¶

An ABC with one abstract method __float__.

classtyping.SupportsComplex¶

An ABC with one abstract method __complex__.

classtyping.SupportsB

你可能感兴趣的:(python 类型标注-typing --- 类型标注支持 — Python 3.7.9 文档)