Here is some simplified code that I don't understand why it does not work.
from collections import namedtuple
MyStruct = namedtuple('MyStruct', 'ThreadInstance ThreadName Mnemonic IpAddr IpGW Status Mode')
Node = MyStruct(None, '', '', '', '', -1, 0)
NodeDb = []
for id in range(4):
NodeDb.append(Node)
NodeDb[2]._replace(ThreadName='T2')
NodeDb[2]._replace(Mnemonic='ABCD')
NodeDb[2]._replace(IpAddr='192.0.1.2')
NodeDb[2]._replace(IpGW='192.0.1.3')
NodeDb[2]._replace(Status=0)
NodeDb[2]._replace(Mode=2)
print(NodeDb)
Here is the output
'>>>
[MyStruct(ThreadInstance=None, ThreadName='', Mnemonic='', IpAddr='', IpGW='', Status=-1, Mode=0),
MyStruct(ThreadInstance=None, ThreadName='', Mnemonic='', IpAddr='', IpGW='', Status=-1, Mode=0),
MyStruct(ThreadInstance=None, ThreadName='', Mnemonic='', IpAddr='', IpGW='', Status=-1, Mode=0),
MyStruct(ThreadInstance=None, ThreadName='', Mnemonic='', IpAddr='', IpGW='', Status=-1, Mode=0)]'
_replace
does not do what you think it does. From the docs:You're calling
_replace
but you never store the newNode
it returns. The reason it returns a new object instead of altering the object 'in-place' is thatnamedtuples
are by definition immutable, i.e. they can't be altered after you created them.Be aware your
for
loop creates a list of four references to the sameNode
. In this case this isn't really a problem since the objects you are creating are all the same andnamedtuple
is immutable, but in general be aware of this.So in summary: