【问题标题】:Get mypy to recognise that object has attribute让 mypy 识别该对象具有属性
【发布时间】:2022-01-23 03:42:52
【问题描述】:

例如:

from typing import Union, List, TypeVar

foo: object

if hasattr(foo, 'bar'):
    print(foo.bar)

返回

main.py:6: error: "object" has no attribute "bar"
Found 1 error in 1 file (checked 1 source file)

但是,我们知道foo 具有属性bar,因为我们只是断言它 - 有没有办法告诉 mypy 这个?

【问题讨论】:

标签: python mypy


【解决方案1】:

您可以使用Protocol 而不是hasattr 来做到这一点:

from typing import Protocol, runtime_checkable


@runtime_checkable
class HasBar(Protocol):
    bar: int


foo: object

if isinstance(foo, HasBar):
    print(foo.bar)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2022-12-22
    • 2021-05-17
    • 2016-06-05
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多