在 python 中使用类型别名然后将其声明为变量是一个好主意吗?

Ala*_*an2 3 python python-3.x python-typing

我正在看这样的代码:

class DeckManager:

   decks: Dict[str, Any]

   def __init__(self, col: a) -> None:

        self.decks = {}
Run Code Online (Sandbox Code Playgroud)

Decks: Dict[str, Any] 指定类型别名是否正确?如果是这样,那么稍后在代码中使用 self.decks 是否有意义。这不是很混乱吗?

jua*_*aga 5

不,decks不是类型别名它是一个类型注释。根据PEP-484

类型别名是通过简单的变量赋值来定义的。

或者根据typing文档

类型别名是通过将类型分配给别名来定义的。

因此,为变量分配任何有效类型注释的内容都是类型别名:

decks = Dict[str, Any]
Run Code Online (Sandbox Code Playgroud)

这种方式decks将是一个类型别名。

但是当您使用冒号时,您是在注释该变量,而不是创建类型别名:

decks: Dict[str, Any]
Run Code Online (Sandbox Code Playgroud)

根据 Python 的类型注释约定,您只需将实例decks的属性注释DeckManager为 type Dict[str, Any]

  • 看来“decks: TypeAlias = dict[str, Any]”现在是[别名类型](https://peps.python.org/pep-0613/)的方法。 (2认同)