I have a question related to using auto() with python enum.
I have a base clase like this:
class TokenEnum(IntEnum):
def __new__(cls, value):
member = object.__new__(cls)
# Always auto-generate the int enum value
member._value_ = auto() # << not working !!
member.rule = value
return member
and want to use it like this. The enum value should be an int and auto-generated. The string provided should go into the additional 'rule' variable.
class Tokens(TokenEnum):
ID = r'[a-zA-Z_][a-zA-Z0-9_]*'
...
auto() doesn't seem to work in the place where I'm using it. And idea on how to get this working?
autois resolved before__new__is called -- it should only be used on the member assignment line (i.e.ID = auto()).If you need
TokenEnummembers to be integers, you'll want:If they don't need to be integers, but you want the value to be an integer, you can do:
If you don't need the value to be an integer, but you do need the
ruleattribute:Finally, if you want to just use the enum as if it were a string:
1 Disclosure: I am the author of the Python stdlib
Enum, theenum34backport, and the Advanced Enumeration (aenum) library.