How to cast tuple into namedtuple?

2020-05-24 20:13发布

问题:

I'd like to use namedtuples internally, but I want to preserve compatibility with users that feed me a ordinary tuple.

from collections import namedtuple

tuplePi=(1,3.14,"pi") #Normal tuple 

Record=namedtuple("MyNamedTuple", ["ID", "Value", "Name"])

namedE=Record(2, 2.79, "e") #Named tuple

namedPi=Record(tuplePi) #Error
TypeError: __new__() missing 2 required positional arguments: 'Value' and 'Name'

tuplePi.__class__=Record
TypeError: __class__ assignment: only for heap types

回答1:

You can use the *args call syntax:

namedPi = Record(*tuplePi)

This passes in each element of the tuplePi sequence as a separate argument.

You can also use the namedtuple._make() class method to turn any sequence into an instance:

namedPi = Record._make(tuplePi)

Demo:

>>> from collections import namedtuple
>>> Record = namedtuple("MyNamedTuple", ["ID", "Value", "Name"])
>>> tuplePi = (1, 3.14, "pi")
>>> Record(*tuplePi)
MyNamedTuple(ID=1, Value=3.14, Name='pi')
>>> Record._make(tuplePi)
MyNamedTuple(ID=1, Value=3.14, Name='pi')