Skip to content

Instantly share code, notes, and snippets.

@Cediddi
Created September 26, 2016 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cediddi/00e14038f4e2190726dc18b7b3cf5bc8 to your computer and use it in GitHub Desktop.
Save Cediddi/00e14038f4e2190726dc18b7b3cf5bc8 to your computer and use it in GitHub Desktop.
Factory for creating namedtuples with keyword arguments.
def namedtuple_with_defaults(typename, args=None, kwargs=None, verbose=False, rename=False):
"""
Factory for creating namedtuples with keyword arguments.
:type typename: str
:type args: tuple
:type kwargs: tuple
:type verbose: bool
:type rename: bool
:rtype: namedtuple
"""
from collections import namedtuple
if args is None:
args = ()
else:
args = tuple(args)
if kwargs is None:
kwargs = tuple()
else:
kwargs = tuple(kwargs)
keys, values = zip(*kwargs)
args += tuple(keys)
nt = namedtuple(typename, args, verbose, rename)
nt.__new__.__defaults__ = tuple(values)
return nt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment