Skip to content

Mypy mistakes instance attrs for class attrs? #15786

@poneill

Description

@poneill

Bug Report

Consider the following class definition:

from typing import Any


class Foo:
    @classmethod
    def bar(cls) -> Any:
        return cls.baz  # mypy correctly catches attr-defined error

Mypy (1.4.1) correctly notices that baz is not defined. However, if we amend the class definition slightly by adding baz as an instance attr like so:

class Foo2:
    def __init__(self, baz: int) -> None:
        self.baz = baz

    @classmethod
    def bar(cls) -> int:
        return cls.baz  # but mypy doesn't catch the attr-defined error here

now mypy doesn't spot the error anymore: it seems to be confused about whether baz is an instance or a class attr.

To Reproduce

Please see playground gist here.

Expected Behavior

I would expect mypy to raise an [attr-defined] error for Foo2 just as for Foo1.

Actual Behavior

main.py:7: error: "type[Foo]" has no attribute "baz"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

[But mypy finds nothing for Foo2.]

Your Environment

  • Mypy version used: 1.4.1
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): NA
  • Python version used: 3.11

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions