python / python/mypy

Union type narrowing behaves differently depending on argument position

Open
#16,401 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-join-v-union topic-type-context
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

In the following example the type narrowing of the union types works as expected if it appears in the first or second argument position, but breaks if it appears in position three (or later).

This issue probably falls into the topic-join-v-union.

To Reproduce

Example on mypy playground

from typing import Callable, TypeVar

T = TypeVar("T")

def func(
    a: Callable[[], T],
    b: Callable[[], T],
    c: Callable[[], T],
) -> T:
    raise NotImplementedError()
        

class Foo:
    ...
    
class Bar:
    ...

def make_foo() -> Foo:
    raise NotImplementedError()
    
def make_bar() -> Bar:
    raise NotImplementedError()
    
def make_foo_or_bar() -> Foo | Bar:
    raise NotImplementedError()

x1: Foo | Bar = func(a=make_foo_or_bar, b=make_foo, c=make_bar)
x2: Foo | Bar = func(a=make_foo, b=make_foo_or_bar, c=make_bar)
x3: Foo | Bar = func(a=make_foo, b=make_bar, c=make_foo_or_bar)

Expected Behavior

The example should type check properly.

Actual Behavior

Inferring the return type works properly for x1 and x2, but it fails for x3 with:

Incompatible types in assignment (expression has type "object", variable has type "Foo | Bar")  [assignment]

Considering that the code is fully valid and symmetric, there should not be a difference in the behavior.

Side note: The issue cannot be work-around at call site by just swapping the order of a and c in the func(...) call. Apparently it has to do with the order in which they appear in the function signature.

Your Environment

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproducer in the issue and run it against mypy 1.6.1 or the current version to confirm the positional difference. Trace callable argument type inference for func and investigate why the third parameter produces object; done when x1, x2, and x3 all type-check consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.