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?
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 .
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.
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).
Data classes advantages over NamedTuplemutable objects. inheritance support. property decorators, manageable attributes. generated method definitions out of the box or customizable method definitions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With