Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python namedtuple T._make(iterable) vs T(* iterable)

Minor question: I don't understand why Python's namedtuple types have a _make() function. As far as I can tell, if T is a type created with namedtuple, then

T._make(iterable)    and    T(* iterable)

are the same thing. So why have a _make() function? Is there something I'm missing?

like image 929
walrus Avatar asked Aug 25 '13 21:08

walrus


People also ask

What is the use of NamedTuple in Python?

Python's namedtuple() is a factory function available in collections . It allows you to create tuple subclasses with named fields. You can access the values in a given named tuple using the dot notation and the field names, like in obj. attr .

What does NamedTuple Python return?

The return value of the call to "namedtuple" will be a class. We need to assign that class to a variable name in our code so we can use it to construct instances. In general, we use the same name as the name of the class that was generated.

Is NamedTuple fast?

NamedTuple is the faster one while creating data objects (2.01 µs). An object is slower than DataClass but faster than NamedTuple while creating data objects (2.34 µs).

What is one advantage of classes over NamedTuple?

Data classes advantages over NamedTuplemutable objects. inheritance support. property decorators, manageable attributes. generated method definitions out of the box or customizable method definitions.


1 Answers

It may be useful to have a function that does the same as T(*iterable). Consider this:

a = namedtuple('a', 'x, y')
b = [(x, x) for x in xrange(10)]
map(a._make, b)

Sure, you could also do:

[a(*x) for x in b]

but this correspondence to functions happens in other places, like the operator module. This is just speculation though, I don't know if that is the rationale for _make.

EDIT: I found some more information on this; following a link in a previous Stack Overflow question, regarding the reason for the underscore in namedtuple methods, I read a page that states:

The inspiration for the _make() classmethod came from Robin Becker and Giovanni Bajo who pointed-out an important class of use cases where existing sequences need to be cast to named tuples.

like image 127
Paulo Almeida Avatar answered Oct 19 '22 10:10

Paulo Almeida