Skip to content

Commit bea9945

Browse files
author
Tim Riddermann
committed
using __new__ instead of __init__ for EnumBase to create enum member objects (fixes #18)
1 parent 80b11b2 commit bea9945

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

construct_typed/tenum.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@ def __init__(self, value: int, doc: t.Optional[str] = None) -> None:
1414
self.value = value
1515
self.__doc__ = doc if doc else ""
1616

17-
def __int__(self) -> int:
18-
return self.value
19-
2017

2118
class EnumBase(enum.IntEnum):
2219
"""
@@ -48,11 +45,16 @@ class EnumBase(enum.IntEnum):
4845
'This is the running state.'
4946
"""
5047

51-
def __init__(self, val: t.Union[EnumValue, int]):
48+
def __new__(cls, val: t.Union[EnumValue, int]) -> "EnumBase":
5249
if isinstance(val, EnumValue):
53-
self.__doc__ = val.__doc__
50+
obj = int.__new__(cls, val.value)
51+
obj._value_ = val.value
52+
obj.__doc__ = val.__doc__
5453
else:
55-
self.__doc__ = ""
54+
obj = int.__new__(cls, val)
55+
obj._value_ = val
56+
obj.__doc__ = ""
57+
return obj
5658

5759
# Extend the enum type with _missing_ method. So if a enum value
5860
# not found in the enum, a new pseudo member is created.
@@ -149,11 +151,16 @@ class FlagsEnumBase(enum.IntFlag):
149151
'This is option two.'
150152
"""
151153

152-
def __init__(self, val: t.Union[EnumValue, int]):
154+
def __new__(cls, val: t.Union[EnumValue, int]) -> "FlagsEnumBase":
153155
if isinstance(val, EnumValue):
154-
self.__doc__ = val.__doc__
156+
obj = int.__new__(cls, val.value)
157+
obj._value_ = val.value
158+
obj.__doc__ = val.__doc__
155159
else:
156-
self.__doc__ = ""
160+
obj = int.__new__(cls, val)
161+
obj._value_ = val
162+
obj.__doc__ = ""
163+
return obj
157164

158165
@classmethod
159166
def _missing_(cls, value: t.Any) -> t.Any:

0 commit comments

Comments
 (0)