I am learning about namedtuple. I would like to find a way, using the ._replace
method, to update all the appearances of a namedtuple
wherever they are.
Say I have a list of nodes, and lists of elements (two-node beams, four-node quads) and boundaries ("one node" elements) defined by these nodes.
I am playing around with doing this:
from collections import namedtuple as nt
Node = nt('Node', 'x y')
Beam = nt('Beam', 'i j')
Quad = nt('Quad', 'i j k l')
Boundary = nt('Boundary', 'b')
#Define some nodes:
n1 = Node(0,0)
n2 = Node(0,1)
n3 = Node(1,1)
n4 = Node(1,0)
#And some other things using those nodes:
q1 = Quad(n1,n2,n3,n4)
b1 = Boundary(n1)
be1 = Beam(n1,n4)
Now, if I replace n1
with a new Node
:
n1 = n1._replace(x=0.5,y=0.5)
print(n1) # Node(x=0.5,y=0.5)
None of the other items are updated:
print(b1) # Boundary(b=Node(x=0, y=0))
I understand the Python naming and object model and the why behind this: b1.b
has been set to the object Node(0,0)
, not the name n1
. So when n1
is changed, the other namedtuples still contain the same object as before, while n1
gets a new object.
What I would like to do is change this behavior so that when I change n1
, the changes are "felt" in b1
, be1
, q1
, etc. How can I do this?