Open
Description
I was playing around with a custom enum and wanted to give it custom auto
values. But come time to override _generate_next_value_
and pyright tells me that: Method "_generate_next_value_" overrides class "Enum" in an incompatible manner. Base method is declared as a staticmethod but override is not
.
mypy:
error: Signature of "_generate_next_value_" incompatible with supertype "Enum" [override]
note: Superclass:
note: def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any
note: Subclass:
note: def _generate_next_value_(name, *_: Any) -> Any
The following code in Python 3.9 works as expected, although with a type error:
from enum import Enum, EnumMeta, auto, unique
from typing import cast
from typing_extensions import override
class CaptureMethodMeta(EnumMeta):
# Allow checking if simple string is enum
@override
def __contains__(self, other: object):
try:
self(other)
except ValueError:
return False
return True
@unique
# TODO: Replace with StrEnum in Python 3.11
class CaptureMethodEnum(str, Enum, metaclass=CaptureMethodMeta):
# Allow TOML to save as a simple string
@override
def __repr__(self):
return self.value
__str__ = __repr__
@override
def _generate_next_value_(name: str, *_):
return name
NONE = ""
BITBLT = auto()
WINDOWS_GRAPHICS_CAPTURE = auto()
PRINTWINDOW_RENDERFULLCONTENT = auto()
DESKTOP_DUPLICATION = auto()
VIDEO_CAPTURE_DEVICE = auto()
bitblt: str = cast(str, "BITBLT")
bar: str = cast(str, "bar")
print(bitblt == CaptureMethodEnum.BITBLT)
print(bar == CaptureMethodEnum.BITBLT)
print("BITBLT" in CaptureMethodEnum)
print("bar" in CaptureMethodEnum)
If I decorate _generate_next_value_
with @staticmethod
, I get the following error:
Traceback (most recent call last):
File "c:\Users\Avasam\Desktop\from enum import Enum, EnumMeta, unique.py", line 18, in <module>
class CaptureMethodEnum(str, Enum, metaclass=CaptureMethodMeta):
File "c:\Users\Avasam\Desktop\from enum import Enum, EnumMeta, unique.py", line 31, in CaptureMethodEnum
BITBLT = auto()
File "C:\Program Files\Python39\lib\enum.py", line 142, in __setitem__
value.value = self._generate_next_value(
TypeError: 'staticmethod' object is not callable