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

Mypy false positive for union validator #1336

Closed
AdrianSosic opened this issue Aug 16, 2024 · 2 comments · Fixed by #1385
Closed

Mypy false positive for union validator #1336

AdrianSosic opened this issue Aug 16, 2024 · 2 comments · Fixed by #1385
Labels
Typing Typing/stub/Mypy/PyRight related bugs.

Comments

@AdrianSosic
Copy link

Not sure if this is a duplicate but I couldn't find the problem in the open issues. If I overlooked it, please close, of course.

from attrs import define, field
from attrs.validators import instance_of

LeTypeAlias = int | str


@define
class LeClass:
    x: LeTypeAlias = field(validator=instance_of(LeTypeAlias))

Works perfectly but mypy complains about:

error: No overload variant of "instance_of" matches argument type "UnionType[int, str]"  [call-overload]
@hynek hynek added the Typing Typing/stub/Mypy/PyRight related bugs. label Aug 17, 2024
@hynek
Copy link
Member

hynek commented Aug 17, 2024

That doesn’t sound familiar and should be easy to fix. 🤞

@Tinche
Copy link
Member

Tinche commented Dec 14, 2024

I think, to be completely correct from a static typing perspective, LeTypeAlias should actually be:

type LeTypeAlias = int | str

In that case, Mypy and Pyright think it's a typing.TypeAliasType. Note that type aliases cannot be used with isinstance - it will blow up at runtime. So we should let this be a type error or change _InstanceOfValidator to explicitly work with them.

I don't remember off the top of my head why you're not supposed to just use LeTypeAlias = int | str, and PEP 695 doesn't say much. I think type works better with generics and forward references?

But if you were to just use the union inline:

from attrs import define, field
from attrs.validators import instance_of

@define
class LeClass:
    x: int | str = field(validator=instance_of(int | str))

Then the argument to instance_of would be types.UnionType.

hynek added a commit that referenced this issue Dec 15, 2024
@hynek hynek closed this as completed in d3f320e Dec 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Typing Typing/stub/Mypy/PyRight related bugs.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants