How to cast tuple into namedtuple?
13,574
You can use the *args
call syntax:
named_pi = Record(*tuple_pi)
This passes in each element of the tuple_pi
sequence as a separate argument.
You can also use the namedtuple._make()
class method to turn any sequence into an instance:
named_pi = Record._make(tuple_pi)
Demo:
>>> from collections import namedtuple
>>> Record = namedtuple("Record", ["ID", "Value", "Name"])
>>> tuple_pi = (1, 3.14, "pi")
>>> Record(*tuple_pi)
Record(ID=1, Value=3.14, Name='pi')
>>> Record._make(tuple_pi)
Record(ID=1, Value=3.14, Name='pi')
Related videos on Youtube
![Adam Ryczkowski](https://i.stack.imgur.com/5KqGB.jpg?s=256&g=1)
Author by
Adam Ryczkowski
Updated on June 04, 2022Comments
-
Adam Ryczkowski about 2 years
I'd like to use namedtuples internally, but I want to preserve compatibility with users that feed me ordinary tuples.
from collections import namedtuple tuple_pi = (1, 3.14, "pi") #Normal tuple Record = namedtuple("Record", ["ID", "Value", "Name"]) named_e = Record(2, 2.79, "e") #Named tuple named_pi = Record(tuple_pi) #Error TypeError: __new__() missing 2 required positional arguments: 'Value' and 'Name' tuple_pi.__class__ = Record TypeError: __class__ assignment: only for heap types
-
Adam Ryczkowski almost 10 yearsShort and to-the-point. I cannot understand how did you manage to answer the question so quickly.
-
jurgispods about 8 yearsNice. You can also use the keyword args syntax to hand over a dict: MyNamedTuple(**mydict). Of course the dict needs to contain the tuple fields as keys.
-
thinwybk about 6 yearsW.r.t. to memory consumption: I can get rid of
tuplePi
after converting it withnamedPi = Record(*tuplePi)
or withnamedPi = Record._make(tuplePi)
, right? -
Martijn Pieters about 6 years@thinwybk: yes, the namedtuple instance now references the same values contained, so you don't need
tuplePi
anymore. -
ofo about 3 years
-
Martijn Pieters about 3 years@ofo: yes, because
Record.__new__
is itself a paper-thin wrapper aroundtuple.__new__(Record, ...)
. It is simpler and more efficient to then re-use that sametuple_new
reference than it is to usecls.__new__(cls, iterable)
, which then creates a new function frame in the interpreter call stack before callingtuple_new()
anyway.