6x2KYqRT
6x2KYqRT

Reputation: 37

Function to set namedtuple attributes?

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

Answers (1)

user2357112
user2357112

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

Related Questions