python / python/mypy

An Enum with multiple initialisation arguments incorrectly infers the type when calling the Enum.

Open
#10,573 4 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-enum
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When an Enum is created that takes multiple initialisation arguments then the signature for calling the Enum with the value is incorrectly inferred to expect every parameter from __new__ and/or __init__ rather than just the value type.

To Reproduce

from enum import IntEnum
from typing import Final, Type

class Colour(IntEnum):
    value: int
    r: Final[int]
    g: Final[int]
    b: Final[int]

    RED = 0, b"\xFF\x00\x00"
    GREEN = 1, b"\x00\xFF\x00"
    BLUE = 2, b"\x00\x00\xFF"
    
    def __new__(cls: Type["Colour"], value: int, _hue: bytes) -> "Colour":
        member = int.__new__(cls, value)
        member._value_ = value
        return member
      
    def __init__(self: "Colour", _value: int, hue: bytes) -> None:
        self.r = hue[0]
        self.g = hue[1]
        self.b = hue[2]
        
c = Colour(0)
print(c)

Expected Behavior

MyPy should have no errors.

Actual Behavior

Outputs:

test_call_enum.py:24: error: Missing positional argument "hue" in call to "Colour"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8.10
  • Operating system and version: Ubuntu 18.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

Run mypy on the supplied Colour example with the reported Python version and confirm that Colour(0) incorrectly requires the hue argument. Trace the Enum call-signature inference involved in this example, then verify that the completed change accepts the value-only call without errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.