What's the difference between enum and namedtuple?

Carlos Afonso picture Carlos Afonso · Nov 16, 2016 · Viewed 12.3k times · Source

I would like to know what are the differences between enum and namedtuple and when one should use one over the other.

Answer

Billy picture Billy · Nov 16, 2016

As an analogy (albeit an imperfect one), you can think of enum.Enum and namedtuple in python as enum and struct in C. In other words, enums are a way of aliasing values, while namedtuple is a way of encapsulating data by name. The two are not really interchangeable, and you can use enums as the named values in a namedtuple.

I think this example illustrates the difference.

from collections import namedtuple
from enum import Enum

class HairColor(Enum):
    blonde = 1
    brown = 2
    black = 3
    red = 4

Person = namedtuple('Person', ['name','age','hair_color'])
bert = Person('Bert', 5, HairColor.black)

You can access the named "attributes" of the person the same way you would a regular object.

>>> print(bert.name)
Bert
>>> print(bert.age)
5
>>> print(bert.hair_color)
HairColor.black
>>> print(bert.hair_color.value)
3

You often don't see namedtuples like this because the same essential concept can be accomplished by using the more widely known class declaration. The class definition below behaves almost identically to the namedtuple definition above.

class Person:
    def __init__(self, name, age, hair_color):
        self.name = name
        self.age = age
        self.hair_color = hair_color

However, a major difference between a namedtuple and a class object is that the attributes of a namedtuple cannot be changed after its creation.