Python 用于类型安全的输入模块
Python typying module for typesafety
python 3.7
我来自严格类型系统的 Scala,这个例子让我感到困惑:
from typing import Optional
tst: Optional[int] = None
tst2: int = None
tst3: Optional[int] = 'string'
print(tst) # prints None
print(tst2) # prints None
print(tst3) # prints string
它执行得很好,没有任何错误。
所以类型注释仅用于描述和外部工具(如 linters),不会影响 python 运行时本身?或者我错过了什么
简而言之:是的,这些注解主要是针对外部工具的。类型注释不会实质性地改变程序的执行方式,您正确地注意到 Python 具有类型错误的程序可以正常执行。
为了详细说明,这些类型提示来自 PEP-483 and PEP-484。这些提案区分了“类型”(您注释的东西)和“class”(在运行时实际上有意义):
Every class is a type as discussed above. But it is tricky and error prone to implement a class that exactly represents semantics of a given type, and it is not a goal of PEP 484. The static types described in PEP 484, should not be confused with the runtime classes.
python 3.7
我来自严格类型系统的 Scala,这个例子让我感到困惑:
from typing import Optional
tst: Optional[int] = None
tst2: int = None
tst3: Optional[int] = 'string'
print(tst) # prints None
print(tst2) # prints None
print(tst3) # prints string
它执行得很好,没有任何错误。
所以类型注释仅用于描述和外部工具(如 linters),不会影响 python 运行时本身?或者我错过了什么
简而言之:是的,这些注解主要是针对外部工具的。类型注释不会实质性地改变程序的执行方式,您正确地注意到 Python 具有类型错误的程序可以正常执行。
为了详细说明,这些类型提示来自 PEP-483 and PEP-484。这些提案区分了“类型”(您注释的东西)和“class”(在运行时实际上有意义):
Every class is a type as discussed above. But it is tricky and error prone to implement a class that exactly represents semantics of a given type, and it is not a goal of PEP 484. The static types described in PEP 484, should not be confused with the runtime classes.