Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active October 10, 2018 18:36
Show Gist options
  • Save SpotlightKid/943abfd17cfc89d7e197 to your computer and use it in GitHub Desktop.
Save SpotlightKid/943abfd17cfc89d7e197 to your computer and use it in GitHub Desktop.
Python namedtuple with default attribute values
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)
@JoshuaEnglish
Copy link

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?

@SpotlightKid
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment