Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Enum: Name vs Value Explained

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 enum module 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

  1. Import the Enum class. At the top of your file, write from enum import Enum. This gives you the base class for creating enumerations.
  2. Define an enum with explicit values. Create a class that inherits from Enum and assign each member a value. For example:
    class Color(Enum):
        RED = 1
        GREEN = 2
        BLUE = 3
    The names are RED, GREEN, BLUE; the values are 1, 2, 3.
  3. Access a member and inspect its name and value. Use Color.RED.name to get 'RED' and Color.RED.value to get 1. Print both to see the difference: print(Color.RED.name, Color.RED.value) outputs RED 1.
  4. Look up a member by name. Use square brackets with the name string: Color['RED'] returns the member Color.RED. This is useful when you have a name from user input or a config file.
  5. Look up a member by value. Call the enum class with the value: Color(1) returns Color.RED. If the value does not exist, it raises ValueError.
  6. Iterate over members. A for loop over the enum class yields members in definition order: for c in Color: print(c.name, c.value). You can also use list(Color) to get all members.
  7. Compare members correctly. Always compare enum members to other members, not to their names or values. Color.RED == Color.RED is True; Color.RED == 1 is False (unless you use IntEnum). Use Color.RED.value == 1 if you need to compare the underlying value.
  8. 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"}.
  9. Deserialize back to a member. If you stored the name, use Color['RED']; if you stored the value, use Color(1). Wrap in a try/except to handle invalid data gracefully.
  10. Use auto() for automatic values. If you don't care about specific values, import auto from enum and write RED = 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 .value when you need a string label. If you print Color.RED.value expecting 'RED', you'll get 1. Use .name for the identifier.
  • Comparing an enum member to its value. Color.RED == 1 is False for a standard Enum. Use Color.RED.value == 1 or define an IntEnum if 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 @unique decorator to prevent duplicates.
  • Using .name for JSON keys without considering case. Names are case-sensitive; ensure consistency across your codebase.

Tips

  • Prefer .name for display and logging; it's more readable and stable if you later change values.
  • Prefer .value when 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 .name on the class itself, not a member. Use Color.RED.name.
  • ValueError when calling Color(5) — the value 5 is not defined. Check available values with list(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 @unique to enforce uniqueness, or access aliases via Color.__members__.
  • JSON serialization fails — enum members are not JSON serializable by default. Convert to .name or .value before 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.