george andrew george andrew - 1 year ago 42
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


if (color==Color.None):
#don't fill the rect
#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
doesn't work.
but from the vendor's code, I do see something like this:

I checked the

it is a
<class 'flufl.enum._enum.IntEnumValue'>

so a
is used. I suppose it should not be very different to use a
or a
Thanks a lot!

Answer Source

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>