0

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
Phiplex
  • 139
  • 1
  • 13

1 Answers1

0

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)
cco
  • 5,873
  • 1
  • 16
  • 21
  • l = ['A', 'B', 'C', 'D'] – Phiplex Dec 19 '16 at 01:43
  • That's a list with four elements, not a `namedlist`. Converting this list to a (standard) tuple can be done as simply as `t = tuple(l)`, but that's not a namedtuple. – cco Dec 19 '16 at 01:46
  • Sorry for my first comment. I'm not used to the 'comment editor' from namedlist import namedlist nl = namedlist('myList', 'a b c d') from collections import namedtuple nt = namedtuple('myTuple', nl._fields) # I can set values in the namedlist like this: L = ['A', 'B', 'C', 'D'] D = dict(zip(nl._fields,L)) NL = nl(**D) NL # This namedlist NL can also be changed like this: NL.a = 'X' NL #Is it possible to create a namedtuple NT with filled values based on values in the namedlist NL – Phiplex Dec 19 '16 at 02:09
  • I still don't understand the 'comment editor', sorry – Phiplex Dec 19 '16 at 02:13
  • If I correctly understand what you put in your comment, the answer is `NT=nt(*NL)` – cco Dec 19 '16 at 02:28