Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python enum.Enum _value_ vs value

Tags:

python

enums

from enum import Enum
class Type(Enum):
  a = 1
  b = 2

print Type.a.value, Type.a._value_

This prints

1 1

What is the difference between _ value_ and value?

like image 369
Nannan AV Avatar asked Jan 30 '18 14:01

Nannan AV


People also ask

Is enum value or reference?

Enum is a reference type, but any specific enum type is a value type. In the same way, System. ValueType is a reference type, but all types inheriting from it (other than System. Enum ) are value types.

Is value in enum Python?

To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.

Should enum values be capital?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.

Can enum have two same values Python?

CA1069: Enums should not have duplicate values.


1 Answers

The difference is that .value is the property-backed version and cannot be changed:

>>> from enum import Enum
>>> class Color(Enum):
...   red = 1
...   green = 2
...   blue = 3
... 
>>> Color.green
<Color.green: 2>
>>> Color.green.value
2
>>> Color(2)
<Color.green: 2>
>>> Color.green.value = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/types.py", line 141, in __set__
    raise AttributeError("can't set attribute")
AttributeError: can't set attribute

But ._value_ is where the actual value is stored in the instance-dict, and can be changed:

>>> Color.green._value_ = 4
>>> Color.green
<Color.green: 4>

As Tobias explained, names that begin with an underscore should be avoided unless you have a really good reason, as you can break things using them:

>>> Color(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/enum.py", line 241, in __call__
    return cls.__new__(cls, value)
  File "/usr/local/lib/python3.5/enum.py", line 476, in __new__
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 4 is not a valid Color
like image 109
Ethan Furman Avatar answered Oct 02 '22 22:10

Ethan Furman