python / python/mypy

mypy should fail if the first element of the type has the same name as the variable

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

Nobody has claimed this yet.

bug topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

This example file.

import pathlib

class A:
    pathlib: pathlib.Path = pathlib.Path('/')
$ mypy test.py 
Success: no issues found in 1 source file

$ python3 test.py 
Traceback (most recent call last):
  File "/tmp/test.py", line 3, in <module>
    class A:
  File "/tmp/test.py", line 4, in A
    pathlib: pathlib.Path = pathlib.Path('/')
             ^^^^^^^^^^^^
AttributeError: 'PosixPath' object has no attribute 'Path'. Did you mean: 'match'?

Expected Behavior

I would expect mypy to fail, possibly explaining why.

Actual Behavior

It succeeds, even though the type annotations cause a failure.

Your Environment

  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Python version used: Python 3.11.9

I had thought incorrectly that it was an issue with attrs https://github.com/python-attrs/attrs/issues/1282 but @euresti provided the example to re-create the problem.

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 test.py reproducer and run the shown mypy command alongside Python to confirm the mismatch. Trace how mypy resolves the annotation and right-hand side inside class A, then add a regression test showing that the example is rejected with an explanatory 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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.