Can a different name and link of a named tuple be different?

When reading fmark answer the question What is "named tuples" in Python? I saw that the example here has the same name and link, that is, the word Point appears twice in the following expression:

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

So, I went to the original link:
https://docs.python.org/2/library/collections.html#collections.namedtuple
And here I also 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 example, the entire line (for the Point example) can be replaced by the following:

 namedtuple('Point', 'x y') 

OR

 Point = namedtuple('x y') 

Of course, it is assumed that a named tuple must have the same name and reference. Therefore, my question is: when is it appropriate (if at all permitted) that a named tuple should have a different name and link? I have yet to meet an example.

+6
source share
1 answer

You can do it, it just annoys 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; do not do this unless you have a good reason.

The reason this happens is because namedtuple() is just a function, it does not have special knowledge of how it is used as an declaration. In languages ​​with macros, namedtuple() will be a macro that will expand to the declaration instead. Thus, instead of sticking to the macro system or going to the call stack for the name, you need to specify the name twice.

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

+10
source

Source: https://habr.com/ru/post/984470/


All Articles