Skip to content

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

Open
@RoketFlame

Description

@RoketFlame

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

Activity

brianschubert

brianschubert commented on Nov 2, 2024

@brianschubert
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Participants

      @JelleZijlstra@brianschubert@RoketFlame

      Issue actions

        [arg-type] wrong argument type in generic function with union · Issue #17654 · python/mypy