Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast tuple into namedtuple?

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 
like image 707
Adam Ryczkowski Avatar asked Jul 28 '14 16:07

Adam Ryczkowski


People also ask

What is difference between Namedtuple and tuple?

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.

How do you value a named tuple?

The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

How do you use a named tuple in Python?

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.


1 Answers

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') 
like image 132
Martijn Pieters Avatar answered Oct 17 '22 05:10

Martijn Pieters