Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

attr.ib(converter=) appears to cause mypy to lose generic types for __init__ function. #8417

Open
rowillia opened this issue Feb 18, 2020 · 2 comments
Labels
bug mypy got something wrong topic-attrs

Comments

@rowillia
Copy link
Contributor

rowillia commented Feb 18, 2020

$ mypy --version
mypy 0.760

attr_test.py:

import attr
from typing import Sequence

@attr.s(auto_attribs=True)
class Foo:
    things: Sequence[str]

@attr.s(auto_attribs=True)
class Bar:
    things: Sequence[str] = attr.ib(converter=tuple)

@attr.s(auto_attribs=True)
class Raz:
    thing: str = attr.ib(converter=str) 

Foo(['hello', 'world'])
Raz('hello')
Bar(['hello', 'world'])
reveal_type(Foo.__init__)
reveal_type(Bar.__init__)
reveal_type(Raz.__init__)

Output:

$ mypy attr_test.py
attr_test.py:18: error: List item 0 has incompatible type "str"; expected "_T_co"
attr_test.py:18: error: List item 1 has incompatible type "str"; expected "_T_co"
attr_test.py:19: note: Revealed type is 'def (self: attr_test.Foo, things: typing.Sequence[builtins.str])'
attr_test.py:20: note: Revealed type is 'def (self: attr_test.Bar, things: typing.Iterable[_T_co`1])'
attr_test.py:21: note: Revealed type is 'def (self: attr_test.Raz, thing: builtins.object)'

I would expect attr_test.py to typecheck cleanly and for the signature of Bar.__init__ to be def (self: attr_test.Bar, things: typing.Iterable[str]) . I'm guessing mypy created a new type _T_co`1 that's something like TypeVar('T', bound=str, covariant=True) but it doesn't seem like that's being used later.

@rowillia
Copy link
Contributor Author

Note that hand rolling the converter function seems to fix this:

import attr
from typing import Iterable, Sequence

def tuple_converter(x: Iterable[str]) -> Sequence[str]:
    return tuple(x)

@attr.s(auto_attribs=True)
class Bar:
    things: Sequence[str] = attr.ib(converter=tuple_converter)

Bar(['hello', 'world'])
reveal_type(Bar.__init__)

@glyph
Copy link

glyph commented Sep 4, 2020

Still an issue on 0.782. Thanks for filing this, I just bumped into it as well. My more minimal illustration:

from typing import List

import attr


@attr.s(auto_attribs=True)
class C:
    a: List[int] = attr.ib(converter=list)


C((x for x in (1, 2, 3)))

@AlexWaygood AlexWaygood added topic-attrs bug mypy got something wrong labels Mar 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-attrs
Projects
None yet
Development

No branches or pull requests

3 participants