Skip to content

Annotation parsing incorrect when class scope defines same name as import #12414

Open
@PeterJCLaw

Description

@PeterJCLaw

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; PyCQA/pyflakes#682; PyCQA/pyflakes#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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions