Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

enums

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!

like image 923
george andrew Avatar asked Aug 04 '16 17:08

george andrew


People also ask

Can you add values to enum?

You can add a new value to a column of data type enum using ALTER MODIFY command. If you want the existing value of enum, then you need to manually write the existing enum value at the time of adding a new value to column of data type enum.

Can enum be null?

Enum types cannot be nullable.

Can an enum type have two values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can we give string value in enum?

When working with enums in C#, it is sometimes necessary to get a string description of the value associated with the enum. This can be accomplished easily by using the DescriptionAttribute class.


1 Answers

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>
like image 172
Brendan Abel Avatar answered Sep 28 '22 18:09

Brendan Abel