Reputation: 37
I have a namedtuple that's a private property of a class instance. I want to create a new tuple based off an instance's namedtuple, but tuples are immutable, so I create a new one and just insert what I want. Is there a better way of doing this? It's extremely redundant, and I would like a specific function or so that would just take a namedtuple as a parameter and as the other parameter the attribute you want to change and it returns the new namedtuple. What would this look like?
Upvotes: 0
Views: 486
Reputation: 280456
There's a _replace
method for that:
new_namedtuple = old_namedtuple._replace(field_name=new_value)
Plus, it'll avoid the bug in your current code, where if two fields share the same value, your code might end up replacing the wrong one.
Upvotes: 1