7 Jun 2018

On the fly: namedtuple

Python has a namedtuple from collections module.  It is interesting to look how it got created because it is created for user defined name.


namedtuple(typenamefield_names, verbose=False, rename=False)
for example:
point_obj = namedtupe('Point', ['x', 'y'])


I would like to share few observations about namedtuple after going through the source code of same.

1. a class definition is stored as a string literal which is to be executed.

2. A subclass of tuple is created with name as a typename. i.e.: point
     class Point(tuple):
        pass

3. property and operator.itemgetter applied on field_names. the Point will have x and y as a property
x and y will be attributes of point.

4. A class definition is created which involves 2. and 3. which looks like this.

5. exec() executes the class definition which returns object of Point.


You can have look at this code,  thanks for reading.

No comments:

Post a Comment