Python 3.9 和 PEP 585 中的typing.Any - 标准集合中的类型提示泛型

gar*_*ryj 12 python type-hinting python-typing python-3.9

我想了解是否typing仍然需要该软件包?

如果在 Python 3.8 中我这样做:

from typing import Any, Dict
my_dict = Dict[str, Any]
Run Code Online (Sandbox Code Playgroud)

现在,在通过 PEP 585 的 Python 3.9 中,现在首选使用集合的内置类型,因此:

from typing import Any
my_dict = dict[str, Any]
Run Code Online (Sandbox Code Playgroud)

我是否仍然需要使用typing.Any或者是否有一个我找不到的内置类型来替换它?

ale*_*ame 15

的用法Any保持不变。PEP 585仅适用于标准集合。

此 PEP 建议在模块中当前可用的所有标准集合中启用对泛型语法的支持typing

从 Python 开始3.9,以下集合成为generic并且typing不推荐从中导入这些集合:

  • 元组#打字.元组
  • 列表#打字.列表
  • dict # 打字.Dict
  • 设置#打字。设置
  • freezeset # 打字.FrozenSet
  • type # 打字.Type
  • 集合.deque
  • 集合.defaultdict
  • 集合.OrderedDict
  • 收藏.柜台
  • 集合.ChainMap
  • 集合.abc.Awaitable
  • collections.abc.Coroutine
  • collections.abc.AsyncIterable
  • collections.abc.AsyncIterator
  • collections.abc.AsyncGenerator
  • 集合.abc.Iterable
  • 集合.abc.Iterator
  • 集合.abc.Generator
  • collections.abc.Reversible
  • 集合.abc.Container
  • 集合.abc.Collection
  • 集合.abc.Callable
  • collections.abc.Set #打字.AbstractSet
  • collections.abc.MutableSet
  • 集合.abc.Mapping
  • collections.abc.MutableMapping
  • 集合.abc.序列
  • collections.abc.MutableSequence
  • collections.abc.ByteString
  • collections.abc.MappingView
  • collections.abc.KeysView
  • collections.abc.ItemsView
  • collections.abc.ValuesView
  • contextlib.AbstractContextManager #打字.ContextManager
  • contextlib.AbstractAsyncContextManager #打字.AsyncContextManager
  • re.Pattern # 打字.Pattern, 打字.re.Pattern
  • re.Match # 打字.Match, 打字.re.Match

  • `NoReturn`、`Union`、`Optional`、`Literal`、`ClassVar`、`Final`、`Annotated`、`Generic`、`TypeVar`、`AnyStr`、`Protocol`、`NewType`、`TypedDict `、`IO`、`TextIO`、`BinaryIO`、`Text`、`SupportsAbs`、`SupportsBytes`、`SupportsComplex`、`SupportsFloat`、`SupportsIndex`、`SupportsInt`、`SupportsRou​​nd` 是其他类型在Python 3.9中,除了“Any”之外,还需要从“typing”模块导入。 (6认同)