python / python/mypy

Type narrowing on object attribute with match statement doesn't apply

Open
#14,911 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-match-statement topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

The bug
It seems that doing a "type checking" with the object UI in pattern matching seems to not work properly.
Attribute match is not considered.

Code

class Test:
    def __init__(self, a: int | str):
        self.a: int | str = a

test = Test(5)

match test:
    case Test(a = int()):
        print(test.a + 3)
    case Test(a = str()):
        print(test.a + "3")

Expected behavior
By doing a match with Test(a = int()), python will check test is of type Test AND test.a is of type int.
But mypy "only assert" that test if of type Test. It keep the type int | str for test.a.

Reproduce :
On mypy-playground :
https://mypy-play.net/?mypy=latest&python=3.11&gist=6f05124abd1ef68032d59651a7d5c6c3

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 mypy-playground reproducer linked in the issue and trace how the match statement handles the Test(a=int()) and Test(a=str()) patterns. Compare the inferred type of test.a in each branch. Done means the attribute is narrowed to int or str respectively, with behavior covered by a regression test.

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
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.