Skip to content

[arg-type] wrong argument type in generic function with union #17654

New issue

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

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

Already on GitHub? # to your account

Open
RoketFlame opened this issue Aug 9, 2024 · 1 comment · May be fixed by #18976
Open

[arg-type] wrong argument type in generic function with union #17654

RoketFlame opened this issue Aug 9, 2024 · 1 comment · May be fixed by #18976
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference

Comments

@RoketFlame
Copy link

RoketFlame commented Aug 9, 2024

Bug Report

I have a generic class and function, which return Union containing TypeVar as in generic. Mypy will give error [arg-type] if I pass function result in another function which gets a object. But if i save the result in a variable and then pass it in function, mypy won't show error. It's very counterintuitive

To Reproduce

from typing import *

T = TypeVar("T")
D = TypeVar("D")


class Key: ...


class FancyKey(Generic[T]): ...


def get(key: FancyKey[T], default: D) -> D | T:
    ...
    return default


def foo(value: object) -> Any: ...


key = FancyKey[Key]()
foo(
    get(key, default=None)
)  # mypy: Argument 1 to "bar" of "Bar" has incompatible type "Foo[Lab]"; expected "Foo[object]" [arg-type]

treasure = get(key, default=None)  # no error
foo(treasure)  # no error

Playground

Actual Behavior

mypy: Argument 1 to "bar" of "Bar" has incompatible type "Foo[Lab]"; expected "Foo[object]" [arg-type]

If a return-type function won't be generic or function will return not a Union - no error will be received
If type of value change to Any - no error will be received

Maybe this issue related with another

Your Environment

  • Mypy version used: 1.11.1
  • Mypy command-line flags: no flags
  • Mypy configuration options from mypy.ini (and other config files): no config
  • Python version used: 3.12
@RoketFlame RoketFlame added the bug mypy got something wrong label Aug 9, 2024
@brianschubert
Copy link
Collaborator

topic-type-context Type context / bidirectional inference

This has to do with whether the signature of get is (over)inferred from the type context (yielding def (key: FancyKey[object], default: object) -> object) or from the arguments types (yielding def (key: FancyKey[Key], default: None) -> Key | None). In the first case, passing FancyKey[Key] becomes invalid, since you declared FancyKey[T] to be invariant.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference
Projects
None yet
3 participants