Python Enum: Name vs Value Explained
In this article
In Python's enum module, .name gives you the member's identifier as a string (for example Color.RED.name is 'RED'), while .value gives you the assigned value (for example Color.RED.value is 1 if you defined RED = 1). Use .name when you need a stable, human-readable label for display or serialization; use .value when you need the underlying data for storage, comparison, or APIs. The two are not interchangeable, and mixing them up is the most common source of bugs with enums.
What You'll Need
- Python 3.4 or newer (the
enummodule is in the standard library from 3.4 onward). - A text editor or IDE to write and run a small script.
- Basic familiarity with defining classes and using dot notation.
Step-by-Step
- Import the Enum class. At the top of your file, write
from enum import Enum. This gives you the base class for creating enumerations. - Define an enum with explicit values. Create a class that inherits from
Enumand assign each member a value. For example:
The names areclass Color(Enum): RED = 1 GREEN = 2 BLUE = 3RED,GREEN,BLUE; the values are1,2,3. - Access a member and inspect its name and value. Use
Color.RED.nameto get'RED'andColor.RED.valueto get1. Print both to see the difference:print(Color.RED.name, Color.RED.value)outputsRED 1. - Look up a member by name. Use square brackets with the name string:
Color['RED']returns the memberColor.RED. This is useful when you have a name from user input or a config file. - Look up a member by value. Call the enum class with the value:
Color(1)returnsColor.RED. If the value does not exist, it raisesValueError. - Iterate over members. A
forloop over the enum class yields members in definition order:for c in Color: print(c.name, c.value). You can also uselist(Color)to get all members. - Compare members correctly. Always compare enum members to other members, not to their names or values.
Color.RED == Color.REDisTrue;Color.RED == 1isFalse(unless you useIntEnum). UseColor.RED.value == 1if you need to compare the underlying value. - Serialize for storage or APIs. When saving to JSON or a database, decide whether to store the name or the value. Names are more readable and resilient to value changes; values are compact and may match external systems. For example,
json.dumps({'color': Color.RED.name})produces{"color": "RED"}. - Deserialize back to a member. If you stored the name, use
Color['RED']; if you stored the value, useColor(1). Wrap in a try/except to handle invalid data gracefully. - Use
auto()for automatic values. If you don't care about specific values, importautofromenumand writeRED = auto(). The values become integers starting at 1, but the names remain what you write. This keeps your code clean when only names matter.
Common Mistakes
- Using
.valuewhen you need a string label. If you printColor.RED.valueexpecting'RED', you'll get1. Use.namefor the identifier. - Comparing an enum member to its value.
Color.RED == 1isFalsefor a standardEnum. UseColor.RED.value == 1or define anIntEnumif you need integer comparison. - Assuming names and values are always the same. They can differ; for example,
RED = 'red'gives name'RED'and value'red'. Always check which one you need. - Forgetting that duplicate values create aliases. If two members have the same value, the second becomes an alias and iteration skips it. Use
@uniquedecorator to prevent duplicates. - Using
.namefor JSON keys without considering case. Names are case-sensitive; ensure consistency across your codebase.
Tips
- Prefer
.namefor display and logging; it's more readable and stable if you later change values. - Prefer
.valuewhen interfacing with external systems that expect specific codes. - Use
StrEnum(Python 3.11+) if you want members to be string-like and compare equal to their values. - Document your enum's value semantics in a docstring to avoid confusion.
- When writing tests, assert both name and value to catch accidental changes.
Troubleshooting
- AttributeError: 'Color' has no attribute 'name' — you likely tried to access
.nameon the class itself, not a member. UseColor.RED.name. - ValueError when calling
Color(5)— the value 5 is not defined. Check available values withlist(Color)or[m.value for m in Color]. - KeyError when using
Color['PURPLE']— the name doesn't exist. Verify spelling and case. - Unexpected alias behavior — if two members share a value, the second is an alias. Use
@uniqueto enforce uniqueness, or access aliases viaColor.__members__. - JSON serialization fails — enum members are not JSON serializable by default. Convert to
.nameor.valuebefore dumping.
Frequently Asked Questions
What is the difference between .name and .value in a Python Enum?
.name is the identifier you wrote in the class definition (a string), while .value is the assigned value (any type). For RED = 1, .name is 'RED' and .value is 1.
Can I change an enum member's value after definition?
No. Enum members are immutable; you cannot reassign .value or .name after creation.
How do I get a list of all names or values?
Use [m.name for m in Color] for names and [m.value for m in Color] for values.
Why does Color.RED == 1 return False?
Standard Enum members are not equal to their values. Use Color.RED.value == 1 or switch to IntEnum if you need that behavior.
What happens if two members have the same value?
The second becomes an alias for the first; iteration and list(Color) will only include the first. Use @unique to raise an error instead.
Should I store the name or the value in a database?
Store the name if you want readability and resilience to value changes; store the value if it matches an external code system. Be consistent and document your choice.