10

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.

Brian Crafton
  • 438
  • 2
  • 6
  • 15
  • Possible duplicate of [Inherit namedtuple from a base class in python](http://stackoverflow.com/questions/39098452/inherit-namedtuple-from-a-base-class-in-python) – Jean-François Fabre Dec 05 '16 at 18:26

1 Answers1

19

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

tuple = new_tuple(x=0, **other_tuple._asdict())
user3030010
  • 1,767
  • 14
  • 19
  • Whether namedtuples have a `__dict__` and how it works is rather inconsistent across Python versions. I don't think the latest 3.5 revision has it. Having a `__dict__` for namedtuples was a bad idea in the first place, and it caused some nasty bugs. – user2357112 Dec 05 '16 at 18:49
  • 4
    If you want a dict representation of a namedtuple, there's the `_asdict` method. – user2357112 Dec 05 '16 at 18:50
  • @user2357112 Thanks, I'll update my answer for that. `__dict__` worked fine for me, but I'm stuck on Python 3.4. – user3030010 Dec 05 '16 at 18:51