Python: Copying named tuples with same attributes / fields

Brian Crafton picture Brian Crafton · Dec 5, 2016 · Viewed 8.1k times · Source

I am writing a function that takes a named tuple and must return a super set of that tuple.

For example if I was to receive a named tuple like this:

Person(name='Bob', age=30, gender='male')

I want to return a tuple that looks like this:

Person(name='Bob', age=30, gender='male', x=0)

Currently I am doing this:

tuple_fields = other_tuple[0]._fields
tuple_fields = tuple_fields + ('x')
new_tuple = namedtuple('new_tuple', tuple_fields)

Which is fine, but I do not want to have to copy each field like this:

tuple = new_tuple(name=other_tuple.name, 
                  age=other_tuple.age, 
                  gender=other_tuple.gender, 
                  x=0)

I would like to be able to just iterate through each object in the FIRST object and copy those over. My actual tuple is 30 fields.

Answer

user3030010 picture user3030010 · Dec 5, 2016

You could try utilizing dict unpacking to make it shorter, eg:

tuple = new_tuple(x=0, **other_tuple._asdict())