Skip to content

Commit 7785850

Browse files
committed
Add EnumMeta to handle unknown values
1 parent 781125d commit 7785850

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

apininjas/enums.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
SOFTWARE.
2323
"""
2424

25-
from enum import Enum
25+
import enum
2626

2727

2828
# fmt: off
@@ -32,7 +32,28 @@
3232
# fmt: on
3333

3434

35-
class CommodityType(Enum):
35+
class EnumMeta(enum.EnumMeta):
36+
def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1):
37+
if names is not None:
38+
return super().__call__(
39+
value,
40+
names=names,
41+
module=module,
42+
qualname=qualname,
43+
type=type,
44+
start=start,
45+
)
46+
try:
47+
return super().__call__(value)
48+
except ValueError:
49+
# return fallback object if value is invalid
50+
obj = object.__new__(cls) # type: ignore
51+
obj._value_ = value
52+
obj._name_ = f"unknown_{value}"
53+
return obj
54+
55+
56+
class CommodityType(enum.Enum, metaclass=EnumMeta):
3657
gold = "gold"
3758
soybean_oil = "soybean_oil"
3859
wheat = "wheat"

0 commit comments

Comments
 (0)