Reputation: 471
can I add a value named 'None' to a enum? for example
from enum import Enum
class Color(Enum):
None=0 #represent no color at all
red = 1
green = 2
blue = 3
color=Color.None
if (color==Color.None):
#don't fill the rect
else:
#fill the rect with the color
This question is related to my previous question How to set a variable's subproperty?
Of course, I understand the above None
in enum
doesn't work.
but from the vendor's code, I do see something like this:
bird.eye.Color=bird.eye.Color.enum.None
I checked the type(bird.eye.Color)
it is a <class 'flufl.enum._enum.IntEnumValue'>
so a flufl.enum
is used. I suppose it should not be very different to use a flufl.enum
or a Enum
.
Thanks a lot!
Upvotes: 11
Views: 11854
Reputation: 37539
You can do this using the Enum
constructor rather than creating a subclass
>>> from enum import Enum
>>>
>>> Color = Enum('Color', {'None': 0, 'Red': 1, 'Green': 2, 'Blue': 3})
>>> Color.None
<Color.None: 0
EDIT: This works using the enum34
backport for python 2. In python 3, you will be able to create the Enum
with the None
attribute, but you won't be able to access using dot notation.
>>> Color.None
SyntaxError: invalid syntax
Oddly, you can still access it with getattr
>>> getattr(Color, 'None')
<Color.None: 0>
Upvotes: 14
Reputation: 362945
You can not do this directly because it is a syntax error to assign to None
.
Neither should you set an attribute on your enum class dynamically, because this will interfere with the metaclass logic that Enum
uses to prepare your class.
You should just use a lowercase name none
to avoid the name collision with python's None
singleton. For the use-case you have described, there is no disadvantage to this approach.
Upvotes: 1
Reputation: 21496
Not quite the way you tried, but you can do this:
# After defining the class Color as normal, but excluding the part for None...
setattr(Color, 'None', 0)
color = Color.None
if color == Color.None:
...
Note: I did this in Python 2. Not sure if you want this in Python 2 or 3 because you didn't specify, and I don't have a copy of Python 3 installed on this machine to test with.
Upvotes: -2