python / python/mypy

Annotation parsing incorrect when class scope defines same name as import

Open
#12,414 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-runtime-semantics topic-variable-scope
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.