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

sve*_*erg 5 python type-hinting python-3.x

python 3.5 的新功能之一是从该项目中获得启发的类型提示。

键入:PEP 484 –键入提示。

我想测试它,但是它没有按预期工作。

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()))
Run Code Online (Sandbox Code Playgroud)

结果是:

<class 'str'>
Run Code Online (Sandbox Code Playgroud)

我期待一个错误,因为我期望布尔作为回报。我在python:3.5(docker)和local上测试了它。我是否想念一些东西以使其起作用?这种键入是否在运行时不起作用(例如python app.py)?

Dan*_*man 6

请参阅您链接到的PEP中摘要的第五段:

尽管这些注释可以在运行时通过常用__annotations__属性使用,但在运行时不会进行类型检查。相反,该提案假定存在一个单独的脱机类型检查器,用户可以自愿运行其源代码。


Jim*_*ard 6

为了获得支票,请考虑像PEP 484 所基于的static项目。mypy

在 PEP 中显式声明的运行时不会执行任何检查,以减轻对向静态 Python 过渡的担忧。


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

{'return': bool}
Run Code Online (Sandbox Code Playgroud)

为了功能overdrawn()

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