python / python/mypy

Detect exhaustiveness in partially-defined variable checks

Open
#13,926 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-possibly-undefined
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

For the partially defined check (--enable-error-code partially-defined), mypy generates a false-positive in the following case:

def f1(x: int | str) -> int:
  if isinstance(x, int):
    y = 1
  elif isinstance(x, str): 
    y = 2 
  return y # error: Name "y" may be undefined

The same applies to match statements:

def f(x: int | str) -> int:
  match x: 
    case int():
      y = 1 
    case str():
      y = 2 
  return y # error: Name "y" may be undefined

It's likely that mypy already detects this somewhere, since it doesn't complain about the missing return:

def f3(x: int | str) -> int:
  if isinstance(x, int):
    return 1
  elif isinstance(x, str): 
    return 2

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 tracing mypy's partially-defined variable analysis and the existing exhaustiveness logic used for missing-return checks. Add regression coverage for the isinstance and match examples, then verify that exhaustive branches no longer report y as possibly undefined while genuinely non-exhaustive checks still do.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.