python / python/mypy

Flow typing doesn't infer generic arguments

Open
#17,332 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

I think the following should type check, but mypy errors on the last line. It's unable to infer that matching on the type of x.inner means we know that we have a Foo[str] and not a Foo[int].

#!/usr/bin/env python

from typing import *

T = TypeVar('T')

class Foo(Generic[T]):
    def __init__(self, inner: T) -> None:
        self.inner = inner

def foo(x: Foo[int] | Foo[str]) -> Foo[str]:
    match x.inner:
        case int():
            raise Exception("Unsupported")
        case str():
            return x # error: Incompatible return value type (got "Foo[int] | Foo[str]", expected "Foo[str]")  [return-value]

To Reproduce

Gist URL: https://gist.github.com/mypy-play/2be996e76f0d979d32be113f891803ed
Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=2be996e76f0d979d32be113f891803ed

Expected Behavior

It should type check :)

Actual Behavior

error: Incompatible return value type (got "Foo[int] | Foo[str]", expected "Foo[str]")  [return-value]

Your Environment

  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Mypy command-line flags: `--strict``
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

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 by running the supplied Python 3.12 reproducer with mypy 1.10.0 and --strict, using the linked gist or playground. Trace the flow-typing behavior around the match on x.inner and verify that the example returns Foo[str] without the incompatible-return error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.