Annotation parsing incorrect when class scope defines same name as import
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Given:
import uuid
class Bar:
uuid: uuid.UUID = uuid.uuid4()
reveal_type(Bar().uuid)
mypy reports no errors and will inform the user that the type of the attribute is uuid.UUID.
However this isn't strictly correct and without lazy annotations enabled this code will actually error at runtime:
File ".../demo.py", line 3, in Bar
uuid: uuid.UUID = uuid.uuid4()
AttributeError: 'UUID' object has no attribute 'UUID'
Ideally mypy would report the missing attribute (UUID) along with a mention of the name overlap between the type name and the attribute name.
Cross-linking: a related issue was raised against pyflakes (that the import appeared unused; https://github.com/PyCQA/pyflakes/issues/682; https://github.com/PyCQA/pyflakes/issues/648), though rejected on the grounds that this code is indeed invalid. Unfortunately when this code is alongside other code it is easy for there not to be any linter errors.
Your Environment
- Mypy version used: 0.910, also tested 0.941
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none that matter - Python version used: 3.9
- Operating system and version: Ubuntu 20.04
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the issue with the provided Python snippet using mypy without configuration flags, then trace annotation name resolution for the class attribute and imported uuid. Add coverage for the missing-attribute and name-overlap diagnostic, and verify the behavior against the runtime-invalid example.
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