【问题标题】:Python 3.5 type hinting does not result in an errorPython 3.5 类型提示不会导致错误
【发布时间】:2015-10-24 08:58:02
【问题描述】:

Python 3.5 中的new features 之一是类型提示,灵感来自mypy

打字: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()))

结果:

<class 'str'>

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

【问题讨论】:

  • "运行时不进行类型检查。" 就在第一部分。

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


【解决方案1】:

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

虽然这些注解在运行时通过通常的__annotations__ 属性可用,但在运行时不会进行类型检查。相反,该提案假设存在一个单独的离线类型检查器,用户可以自愿运行其源代码

【讨论】:

    【解决方案2】:

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

    不会在运行时执行检查在 PEP 中明确声明,以减轻对某些过渡到静态外观 Python 的担忧。


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

    {'return': bool}
    

    对于函数overdrawn()

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

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2021-07-28
      • 2019-01-18
      • 2017-11-21
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2019-10-30
      • 2018-03-29
      相关资源
      最近更新 更多