python / python/mypy

mypy can not correctly tell when optional type can not be None

Open
#14,266 3 comments 1 reaction 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

mypy can not correctly tell when optional type can not be None if the variable was previously set or checked in @property.

To Reproduce

class Test(object):
    def __init__(self) -> None:
        self.test: str | None = None

    @property
    def is_set(self) -> bool:
        return self.test is not None

    def failed_check(self) -> None:
        if not self.is_set:
            return

        # self.test can not be None
        value = self.test.strip(',')
        print(value)

class Test2(object):
    def __init__(self) -> None:
        self.test: str | None = None

    def set_me(self) -> None:
        self.test = 'test'

    def use_me(self) -> None:
        self.set_me()

        # self.test can not be None
        self.test.strip(',')

Expected Behavior

No issues found.

Actual Behavior

test.py:14: error: Item "None" of "Optional[str]" has no attribute "strip"  [union-attr]
test.py:28: error: Item "None" of "Optional[str]" has no attribute "strip"  [union-attr]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 0.991 (compiled: yes)
  • Mypy command-line flags: mypy test.py
  • Mypy configuration options fro m mypy.ini (and other config files):
  • Python version used: Python 3.10.8

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 saving the examples as test.py and running mypy test.py with the reported Python and mypy versions. Trace how mypy narrows Optional values after property checks and method calls; done means both examples produce no errors, with regression coverage for the reported behavior.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.