Named Tuple & Enum in Python

Python has two very nice data structure called namedtuple and enum which are not that much been use in day to day python coding considering their usefulness.

Let’s start with namedtuple:
namedtuple lib is part of collections package. As name suggest it’s kind of tuple which is immutable(unchangeable) with named arguments.

Let’s see the syntax to declare namedtuple two ways:

Usually it’s better practice to have namedtuple declare individually as any normal class declare and not part of function or class.

from collection import namedtuple
Employee = namedtuple('Employee', ['name','salary','dept','manager'])


Employee = namedtuple('Employee', 'name salary dept manager')

Here we are creating a Employee class with immutable properties as ‘name’, ‘salary’, ‘dept’ and ‘manager’.
These can be only assign once and changing value is not allowed. Let’s see the use of namedtuple:
employee = (name='John', salary=100k, dep=IT, manager='Doe')

To Access these values, you can use it as:

print # John
print employee.salary #100k

But you can’t reassign the values to namedtuple: = 'Kevin' # This will through exception

let’s talk about Enum now:
There are two version of enum as enum34 and aenum( which has more advance feature available):
enum34 => $ pip install enum34
aenum => $ pip install aenum

Enum are simple class which has properties but are mutable(changeable):
Here is the syntax:

Import Enum:
from enum import Enum # enum34
from aenum import Enum # aenum

Use of Enum
Employee = Enum('Employee', 'dept name salary manager')
Animal.dept # returns
Animal['dept'] # returns (string lookup) # returns 'dept' (inverse lookup)

Enum as class
class Employee(Enum):
dept = 1
name = 2
salary = 3
manager = 4

Enum helps to make code readble as you can define constant in the enum class and can use it with those self descriptive names as Employee.dept.

You can also have list comprehension like this:

for employee in Employee: print employee #Employee.dept,

I hope this post will help you to understand the basic namedtuple and enum in python.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s