Output 1:
T(foo='bar', spamm='eggs', ham=None) T(foo='bar', spamm='eggs', ham='bacon')
Output 2:
T(foo=1, spamm=2) T(foo=3, spamm=2)
| from collections import namedtuple, OrderedDict | |
| from functools import partial | |
| # important: pass (name, value) pairs as a tuple/sequence not as keyword args! | |
| # otherwise, order will not be preserved. | |
| fields = OrderedDict((('foo', "bar"), ('spamm', "eggs"), ('ham', None))) | |
| T = partial(namedtuple("T", fields), **fields) | |
| t1 = T() | |
| print(t1) | |
| t2 = T(ham="bacon") | |
| print(t2) |
| import collections as c,functools as ft | |
| f = 'foo','spamm' | |
| v = 1,2 | |
| T = ft.partial(c.namedtuple("T",f), **dict(zip(f,v))) | |
| print(T(), T(foo=3)) |
Output 1:
T(foo='bar', spamm='eggs', ham=None) T(foo='bar', spamm='eggs', ham='bacon')
Output 2:
T(foo=1, spamm=2) T(foo=3, spamm=2)
The partial function is essentially only a wrapper around the T namedtuple class constructor, which pre-populates some keyword arguments. A factory function for the T class, if you will.
This is cool. I was worried that this method would create multiple duplicate classes, each with a single instance, but they seem to be the same. Is this because functools.partial stores the namedtuple class and reuses it?