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.
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 employee.name # John
print employee.salary #100k
But you can’t reassign the values to namedtuple:
employee.name = '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:
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)
Animal.dept.name # returns 'dept' (inverse lookup)
Enum as class
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, Employee.name...
I hope this post will help you to understand the basic namedtuple and enum in python.