Skip to content

mypy doesn't throw error when function calls operator.attrgetter #2884

Closed
@joshp123

Description

@joshp123

It seems that when calling operator.attrgetter, type errors are not caught.

Given the following:

# attrgettertest.py
from operator import attrgetter


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


class TwoThings:
    foo = "hello"
    bar = "baz"
    fields = ['foo', 'bar']


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()

The output is:

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

One would expect the output to be something like:

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, ...])

It seems that mypy cannot catch the error.

I am using python 3.5.2 and mypy 0.4.71.

(Please let me know if I am missing something, I am somewhat new to mypy 😉 )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions