Skip to content

Type hints of tuple not used effectively when calling a function on its values #16119

Closed
@exoriente

Description

@exoriente

Bug Report

mypy does not use the information is has about the types in a tuple effectively when iterating through the tuple's values. mypy does not allow a function that can handle every type in the tuple to be called on the tuples values. mypy will check only if the function supports the closest common parent class of all types in the tuple.

To Reproduce

class A:
    ...
    
class B:
    ...


def function(x: A | B) -> None:
    return

t: tuple[A, B] = (A(), B())

for x in t:
    function(x)

https://gist.github.com/mypy-play/671835ea899ca94ddd33150f155fbc39

Expected Behavior

We would expect mypy to approve the code. Logically function() can never be called with a value that conflicts with the type hints of its parameter x.

Actual Behavior

mypy exits with an error, even though the code is perfectly safe to run in terms of passing valid types with certainty.

main.py:14: error: Argument 1 to "function" has incompatible type "object"; expected "A | B"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

We used a mypy Playground set up with no defaults changed:

  • Mypy version used: 1.5.1 (latest)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-join-v-unionUsing join vs. using unions

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions