'function' Object Has No Attribute 'value' When Class Function Is Used In Enum Values
I just want to achieve some extra which is not there in operator module of python like not_contain. For that I created my own class with the not_contain method. I just want to do s
Solution 1:
Enum uses the presence of the __dunder__
method __get__
to determine if an object is a function/class. Functions and classes created in Python all have a __get__
method, but built-in functions do not.
To get around this problem you can use the aenum
module and its member
function:
from aenum import Enum, member
importoperatorclassUserDefinedOperators:
#@staticmethod
def not_contain(self, a, b):
return a not in b
classMyOperators(Enum):
LT = operator.lt
GT = operator.gt
NOT_CONTAIN = member(UserDefinedOperators.not_contain)
and in use
>>> list(MyOperators)
[
<MyOperators.LT: <built-in function lt>>,
<MyOperators.GT: <built-in function gt>>,
<MyOperators.NOT_CONTAIN: <function UserDefinedOperators.not_contain at 0x7f9c875ed790>>,
]
Note that I made not_contain
be a staticmethod
. This is appropriate since the not_contain
method does not require any instance nor class data to do its job. This also means you do not need to instantiate UserDefinedOperators
with creating the NOT_CONTAIN
enum member.
Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.
Post a Comment for "'function' Object Has No Attribute 'value' When Class Function Is Used In Enum Values"