george andrew george andrew - 4 months ago 6
Python Question

Is it possible to add a value named 'None' to enum type?

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!

Answer

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>
Comments