Skip to content

Enum attributes are incorrectly inferred when callables are defined like enum values #15540

@Daverball

Description

@Daverball

Bug Report

The enum metaclass will skip callables so that defining methods on an enum still works. This introduces a subtle logic error that won't be caught be mypy. If you assign callables to the enum members the enum will pick it up as a method, but mypy thinks it will pick it up as an enum member.

To Reproduce

import enum

class Transform(enum.Enum):
    upper = str.upper
    lower = str.lower

reveal_type(Transform.upper)

Expected Behavior

reveal_type on Transform.upper should yield something along the lines of Callable[[str], str], since in the actual class it will be a method.

Actual Behavior

reveal_type yields Literal[Transform.upper]. While this is intuitively what should happen, when looking at this code, in practice this doesn't work, due to the implementation details of Enum. (I'm not sure it's possible to make this work without wrapping the callable in some other object first)

As such it will hide a bug, that should be easy for mypy to detect and report.

Your Environment

  • Mypy version used: 1.4.1
  • Mypy command-line flags: None (just used on the file/module/package)
  • Mypy configuration options from mypy.ini (and other config files):
python_version = "3.10"
ignore_missing_imports = false
namespace_packages = true
disallow_any_generics = true
disallow_untyped_defs = true
warn_redundant_casts = true
warn_unreachable = true
warn_unused_ignores = true
plugins = ["mypy_zope.plugin"]
  • Python version used: 3.10

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