I would like to know what are the differences between enum and namedtuple and when one should use one over the other.
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, enum
s 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 enum
s 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 namedtuple
s 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.