Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the name and the reference of a named tuple be different?

While reading fmark's answer to the question What are "named tuples" in Python? I saw that the example given there had the same name and reference, i.e. the word Point appears twice in the following statement:

Point = namedtuple('Point', 'x y')

So I went to the original reference:
https://docs.python.org/2/library/collections.html#collections.namedtuple
And here too I found two more examples:

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Color = namedtuple('Color', 'red green blue')

Ideally words are not repeated in Python. For instance the whole line (for the the Point example) could be replaced by the following:

namedtuple('Point', 'x y')

OR

Point = namedtuple('x y')

Of course, that's assuming that the named tuple has to have the same name and reference. So my question is: when is it advisable (if at all it is permitted) that a named tuple should have a different name and reference? I am yet to come across an example.

like image 673
Shashank Sawant Avatar asked Mar 31 '15 00:03

Shashank Sawant


1 Answers

You can do it, it will just annoy you.

In [1]: import collections

In [2]: Point = collections.namedtuple('Rectangle', 'x y')

In [3]: Point(1, 2)
Out[3]: Rectangle(x=1, y=2)

This is confusing, don't do it unless you have a very good reason.

The reason why this happens is because namedtuple() is just a function, it has no special knowledge about how it is being used as a declaration. In languages with macros, namedtuple() would be a macro which expands to a declaration instead. So, rather than tack on a macro system or walk the call stack for the name, you have to specify name twice.

So it is one of Python's "warts", or a design compromise, depending on how you feel about it.

like image 92
Dietrich Epp Avatar answered Nov 06 '22 07:11

Dietrich Epp