python / python/cpython

Cannot define Enum class with a mixin class derived from ABC

Offen
#119,946 15 Kommentare 1 Reaktion 1 zugewiesene Person Auf GitHub ansehen

@ethanfurman arbeitet bereits daran.

Seit 02.6.2024.

stdlib type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

Bug description:
from abc import ABC, abstractmethod
from enum import Enum

class HasColor(ABC):
    @abstractmethod
    def color(self):
        ...

class Flowers(HasColor, Enum):
    ROSES = 1
    VIOLETS = 2
    def color(self):
        match self:
            case self.ROSES:
                return 'red'
            case self.VIOLETS:
                return 'blue'

This results in:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

There is a work-around by metaclass hacking. But these two basic Python features are expected to Just Work together in a simple, intuitive, and pythonic way.

The fix should be very simple - make EnumType a subclass of ABCMeta. But it's slightly more complicated than that, so that the _simple_enum decorator and _test_simple_enum continue to work as expected. See the provided patch.

CPython versions tested on:

3.12, 3.13

Operating systems tested on:

macOS

Linked PRs
  • gh-119947
  • gh-149830

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.