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

本文详细介绍了Python `typing`模块中的类型标注,包括`TypeVar`、`Generic`、`Type`等类的用法,以及如何进行类型变量的协变、逆变和边界限制。通过示例展示了如何在类和函数中使用这些类型标注,以提高代码的静态类型检查和可读性。
摘要由CSDN通过智能技术生成

类,函数和修饰器.¶

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值