python / python/mypy

False negative: potentially unbound instance attribute doesn't trigger `possibly-undefined` error

Open
#17,837 2 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

When enabling the possibly-undefined error code, a potentially undefined instance attribute doesn't trigger the error, while a potentially unbound variable does.

To Reproduce

def test_possibly_undefined(flag: bool):
    if flag:
        a = 1
    print(a)  # error: Name "a" may be undefined  [possibly-undefined]


class Foo:
    def test_possibly_undefined(self, flag: bool):
        if flag:
            self.a = 1
        print(self.a)  # false negative, should also be a possibly-undefined error


try:
    test_possibly_undefined(False)
except Exception as e:
    print(f"{type(e).__name__}: {e}")  # UnboundLocalError: cannot access local variable 'a' where it is not associated with a value

f = Foo()
try:
    f.test_possibly_undefined(False)
except Exception as e:
    print(f"{type(e).__name__}: {e}")  # AttributeError: 'Foo' object has no attribute 'a'

Also available as mypy Playground, but cannot enable enable_error_code = possibly-undefined there.

Expected Behavior

A possible-undefined error should be reported for line 11 as well, e.g.:

test.py:4: error: Name "a" may be undefined  [possibly-undefined]
test.py:11: error: Attribute "a" may be undefined  [possibly-undefined]
Found 2 errors in 1 file (checked 1 source file)

Actual Behavior

No error reported for line 11.

test.py:4: error: Name "a" may be undefined  [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: --enable-error-code=possibly-undefined
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12.6

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 reproducing the example with mypy 1.11.2 and the possibly-undefined error code, then locate the checker logic and regression tests for possibly undefined local variables. Compare handling of local names with instance attributes and add coverage for the Foo example; done means mypy reports the expected Attribute "a" may be undefined error.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.