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

标签 python python-3.x type-hinting python-typing

new features 之一在 Python 3.5 中是类型提示,灵感来自 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 作为返回类型。我在 Python 3.5 (docker) 和本地测试了它。我错过了什么,让它发挥作用吗?这种键入在运行时不起作用吗?

最佳答案

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

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

关于Python 3.5 类型提示不会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33316345/

相关文章:

python - 如何将工作表转换为 Pandas 中的数据框?

python - 有效检测python中的符号变化

python - 如何保持 2 列数据帧的 pandas groupby 计数为零?

python - 日期时间 : ValueError: day is out of range for month

python - Python 3.4 中 _imp 模块位于哪里?

python - Pandas:读取文件时跳过包含特定字符串的行

python - 使用 numpy 连接 2 个列表

python - 定义一个行为类似于打字的自定义类型。Any

python - 如何获取对象属性的类型提示?

python - 预期类型 'MyObject',在带有类型提示的 __init__ 中得到 'None'