Skip to content

mypy incorrectly infers type of ClassVar when accessed in try/except AttributeError #19686

Description

@gswifort

mypy incorrectly infers type of ClassVar when accessed in try/except AttributeError

Bug Report

What's wrong

When accessing a ClassVar annotated variable inside a try/except AttributeError block, mypy incorrectly infers the type of the variable, leading to false positive type errors.

How to reproduce

import enum
import typing as t


class MyEnum(float, enum.Enum):
    """Example enum that has a cached class variable."""
    
    if t.TYPE_CHECKING:
        _cache: t.ClassVar[dict[str, "MyEnum"]]
    
    VALUE_A = 1.0
    VALUE_B = 2.0
    
    @classmethod
    def from_string_broken(cls, key: str) -> "MyEnum":
        """This method shows the mypy type inference bug."""
        try:
            # mypy incorrectly thinks cls._cache is MyEnum instead of dict[str, MyEnum]
            cache = cls._cache
        except AttributeError:
            cache = {item.name: item for item in cls}
            cls._cache = cache
        
        return cache[key]

Actual behavior

mypy reports these errors:

error: Incompatible types in assignment (expression has type "dict[str, MyEnum]", variable has type "MyEnum")
error: Incompatible types in assignment (expression has type "MyEnum", variable has type "dict[str, MyEnum]") 
error: Value of type "MyEnum" is not indexable

Expected behavior

mypy should recognize that cls._cache has type dict[str, MyEnum] as declared in the ClassVar annotation, and not report any type errors.

Environment

  • mypy version: 1.17.0
  • Python version: 3.12.7

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions