Convert python mutable namedlist to immutable namedtuple

1.4k views Asked by At

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
1

There are 1 answers

5
cco On BEST ANSWER

If you mean the package installed by pip install namedlist, then if you have a namedlist defined like this:

from namedlist import namedlist
nl = namedlist('myList', 'a b c d')

You can make a corresponding namedtuple:

from collections import namedtuple
nt = namedtuple('myTuple', 'a b c d')
# or, you if you want to copy the names
nt = namedtuple('myTuple', nl._fields)

An example of use might look like this:

l = nl(1,2,3,4)      # myList(a=1, b=2, c=3, d=4)
t = nt(*l)           # myTuple(a=1, b=2, c=3, d=4)