Named Tuples

Navaneethan
2 min readDec 8, 2015

--

What…???

How many tuples do we have in python?

:)

don’t worry..just a single tuple only.

Tuples meant in python are,

  1. immutable

2. ordered

Why immutable is important in programming?

Programmers aren’t compilers. Because they make errors in silent unlike compilers(compilers enforce the errors). So, we need some alarm stuff..

Mutable will change the behavior of the data that you would not even realized.

for example,

def test_mutable(_default_list=[]):   _default_list.append(‘navaneethan’)  print _default_list

Just try with this snippet in your python shell.

and do call like

>>>l = [‘hai’]
# See the output in your python shell
>>>test_mutable(l)
# See the output in your python shell
>>>test_mutable()
# See the output in your python shell
>>>test_mutable()
# See the output in your python shell
>>>test_mutable(l)
# See the output in your python shell

wonder what happens? :)

So, to escape from this bug, your goto button is ‘immutability’.

Tuples

>>> t = (1, 2, )>>> t[0] = 5— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
TypeError Traceback (most recent call last)
<ipython-input-153–8d3d8637cb4b> in <module>() — → 1 t[0] = 5
TypeError: ‘tuple’ object does not support item assignment

This will enforce you to get avoided from the mutability trap.

Even if you are into sleep while programming, it is the night watchman for your customer’s data :)

at last you came to know the beauty of functional programming. :)

Named Tuples

Sometimes you want the class behavior approach, but you don’t want the class to get the crappy side effects. Then, you are under right title :)

watch the example and perceive it fruitfulness under that.

In [154]: from collections import namedtupleIn [155]: T = namedtuple(‘T’, ‘technology experience’)In [156]: obj = T(technology=’python’, experience=5)In [157]: obj.technology
Out[157]: ‘python’
In [158]: obj.experience
Out[158]: 5
In [159]: obj.experience = 6 — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
AttributeError Traceback (most recent call last)
<ipython-input-159–73953b612f83> in <module>() — → 1 obj.experience = 6
AttributeError: can’t set attribute

Points to be noticed above:

  • You can access the attributes in dotted notation
  • It takes two arguments as input 1.name 2. attribute list delimited by space.
  • Of course, you can’t override the attribute value

So, If you use class for just sack of accessing the attribute in dotted notation, it would do some massaging on the attributes by creating the dictionary etc..

The namedtuple factory function memory efficient than the class — refer

Use case points:

Wherever you want to mimic the behavior of class-attribute relationship and want to consume the goodies of tuple,

way to go for namedtuples.

bye..bye.. :)

--

--

Navaneethan

Learning is my passion,we love the mistakes always,we usually get a lot of success in dream...,