Skip to content

Instantly share code, notes, and snippets.

@thanakijwanavit
Created February 13, 2023 01:35
Show Gist options
  • Save thanakijwanavit/966bce11e21a0bbfe2051f7181488c8c to your computer and use it in GitHub Desktop.
Save thanakijwanavit/966bce11e21a0bbfe2051f7181488c8c to your computer and use it in GitHub Desktop.
enum with unknown or missing value
from enum import Enum
class Foo(Enum):
A = 1
B = 2
C = 3
def __str__(self):
return self.name
@classmethod
def _missing_(cls, value):
if cls._member_type_ is object:
# construct a new singleton enum member
new_member = object.__new__(cls)
# include the value representation in _name_ because the Enum hash implementation relies on _name_
new_member._name_ = '%r' % value
new_member._value_ = value
# use setdefault in case another thread already created a composite with this value
new_member = cls._value2member_map_.setdefault(value, new_member)
return new_member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment