Search code examples
pythonpython-2.7namedtuple

Python namedlist FACTORY default with values


The namedlist package in Python is similar to collections.namedtuple and allows for mutable instances.

Declaring mutable default values requires the use of FACTORY, ex:

from namedlist import namedlist, FACTORY
A = namedlist('A', [('x', FACTORY(list))])

I now need to that list to have defaults, but the code below doesn't work:

A = namedlist('A', [('x', FACTORY(list([1, 2])))])

The code below creates a list with defaults, but every instance of A will point to the same object, which is the reason we need factories in the first place:

A = namedlist('A', [('x', [1, 2])])

How do I create a namedlist field with a factory with values?


Solution

  • You need to provide a function to FACTORY that creates a new object when called.

    A = namedlist('A', [('x', FACTORY(lambda: [1, 2]))])