-2

What's the shortest way to copy all despite of one attribute/field from one to another namedtuple? It's possible to do it like follows.

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

new_age = 31

modified_person = Person(name=initial_person.name,
                         age=new_age,
                         gender=initial_person.gender,
                  )

However I have a lot more fields and would prefer a shorter implementation. This question is related to Python: Copying named tuples with same attributes / fields.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
thinwybk
  • 4,193
  • 2
  • 40
  • 76
  • You mean like https://stackoverflow.com/a/22562687/3001761? – jonrsharpe Sep 25 '19 at 12:22
  • Please clarify what you are asking. Add an example input and output along with some code you have tried. As it sits your question is confusing and I have no clue what you are even asking, nor do I know how to reword it in such a way to make understandable. – Error - Syntactical Remorse Sep 25 '19 at 12:24
  • 1
    Then yes, you can absolutely use [`_replace`](https://docs.python.org/3/library/collections.html#collections.somenamedtuple._replace): `modified_person = initial_person._replace(age=new_age)` – jonrsharpe Sep 25 '19 at 21:19
  • @jonrsharpe That's exactly what I was looking for! Thx. – thinwybk Sep 29 '19 at 08:12

1 Answers1

0

Use _replace()

initial_person = Person(name='Bob', age=30, gender='male')
modified_person = initial_person._replace(age=31)

Note that this is a little hack, theoretically you shouldn't use methods with a underscore at the beginning.

bb1950328
  • 1,403
  • 11
  • 18