How to cast tuple into namedtuple?

PythonPython 3.xNamedtuple

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam RyczkowskiView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow