【问题标题】:MyPy / python type hints doesn't catch called function that can return multiple typesMyPy / python 类型提示没有捕获可以返回多种类型的调用函数
【发布时间】:2017-02-21 17:54:05
【问题描述】:

attrgetter 函数可以根据您提供的参数返回不同的类型。如果您传递一个带有一个项目的可迭代对象,它将仅返回对象的给定字段;如果你向它传递一个包含多个项目的可迭代对象,它会返回一个对象的这些字段的元组。

但是,当使用类型提示 + MyPy 时,MyPy 不会发现这种差异(它不会引发错误):

from operator import attrgetter


class OneThing:
    foobar = "hello"
    fields = ['foobar']


class TwoThings:
    foobar = "hello"
    goodbye = "potatoes"
    fields = ['foobar', 'goodbye']


def attrgettertest(thing) -> tuple:
    return attrgetter(*thing.fields)(thing)


def main():
    onething = OneThing()
    twothings = TwoThings()

    t1 = attrgettertest(onething)
    t2 = attrgettertest(twothings)

    print("Attrgettertest on 'onething' returned  {} with type {}".format(
        t1, type(t1)))
    print("Attrgettertest on 'twothings' returned  {} with type {}".format(
        t2, type(t2)))


if __name__ == "__main__":
    main()

还有输出:

$ python attrgettrtest.py 
Attrgettertest on 'onething' returned  hello with type <class 'str'>
Attrgettertest on 'twothings' returned  ('hello', 'potatoes') with type <class 'tuple'>
$ mypy attrgettrtest.py 
$ 

预期的结果是这样的:

import random    

def test() -> tuple:
    if random.choice([0, 1]):
        return ("foo", "bar")
    return "foo"

if __name__ == "__main__":
    for n in range(20):
        print(test())

$ mypy test.py 
test.py:8: error: Incompatible return value type (got "str", expected Tuple[Any, ...])

这是 MyPy 中的错误吗?

【问题讨论】:

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


    【解决方案1】:

    这里的问题似乎是 attrgetter 的返回类型为Any,而 mypy 没有捕捉到这个。

    我将此发布到 mypy 存储库并得到以下answer

    我认为问题在于 attrgetter 的返回类型为Any,因此您的代码可以通过。原则上,在这种情况下,精确的类型检查会很困难,但是,有一个新添加的标志 --warn-return-any 会在这种情况下发出警告(它将在 0.480 中可用,请参阅 PR #2854 了解详细信息)。

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2021-08-30
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 2019-08-21
      • 1970-01-01
      相关资源
      最近更新 更多