Python 3.5 类型提示不会导致错误

Python 3.5 type hinting does not result in an error

其中一个new features in Python 3.5 is type-hinting, inspired by mypy

typing: PEP 484 – Type Hints.

我想测试一下,但效果不如预期。

import typing

class BankAccount:
    def __init__(self, initial_balance: int = 0) -> None:
        self.balance = initial_balance
    def deposit(self, amount: int) -> None:
        self.balance += amount
    def withdraw(self, amount: int) -> None:
        self.balance -= amount
    def overdrawn(self) -> bool:
        return str(self.balance < 0)

my_account = BankAccount(15)
my_account.withdraw(5)
print(type(my_account.overdrawn()))

结果:

<class 'str'>

我预计会出现错误,因为我期望 bool 作为 return 类型。我在 Python 3.5 (docker) 和本地测试了它。我错过了什么,让它发挥作用吗?这种键入在运行时不起作用吗?

请参阅 PEP 中摘要的第五段 link 至:

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime . Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily

为了获得 static 检查,请考虑像 mypy 这样的项目,PEP 484 就是基于该项目。

不会在运行时执行检查 在 PEP 中明确声明 以缓解担心某些过渡到静态外观 Python。


正如丹尼尔指出的,您可以通过以下形式查看 __annotations__ 属性中的属性:

{'return': bool}

用于函数 overdrawn()

如果需要,您可以创建自己的小型类型检查函数来利用此 dict 执行少量运行时检查。玩弄它。此外,如果您愿意阅读,请查看我对类型提示 .

的回答