Is there a way to convert or make a copy of a python mutable namedlist to an immutable namedtuple?
EDIT based on the comments:
I have a namedlist filled with values
>>> from namedlist import namedlist
>>> nl = namedlist('myList', 'a b c d')
>>> L = ['A', 'B', 'C', 'D']
>>> D = dict(zip(nl._fields,L))
>>> NL = nl(**D)
>>> NL
myList(a='A', b='B', c='C', d='D')
This mutable namedlist NL can be changed like this:
>>> NL.a = 'X'
>>> NL
myList(a='X', b='B', c='C', d='D')
Then I also create a nametuple with same fields
from collections import namedtuple
nt = namedtuple('myTuple', nl._fields)
Question
Is it now possible to create an immutable namedtuple NT with filled values based on values in the namedlist NL ?
ANSWER from the comments:
Use:
>>> NT = nt(*NL)
>>> NT
myTuple(a='X', b='B', c='C', d='D')
This immutable namedtuple cannot be changed:
>>> NT.a = 'Y'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
If you mean the package installed by
pip install namedlist
, then if you have a namedlist defined like this:You can make a corresponding namedtuple:
An example of use might look like this: