Skip to content

Instantly share code, notes, and snippets.

@estebistec
Last active August 29, 2015 14:08
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 estebistec/9c062e8c93ac851e8056 to your computer and use it in GitHub Desktop.
Save estebistec/9c062e8c93ac851e8056 to your computer and use it in GitHub Desktop.
Methods for namedtuple instantiation that don't require all fields to be provided
from collections import namedtuple
PersonTuple = namedtuple('PersonTuple', ['formal_name', 'preferred_name'])
from base import PersonTuple
class Person(PersonTuple):
@classmethod
def create(cls, **kwargs):
return cls(**{
field_name: kwargs.get(field_name, None)
for field_name in cls._fields
})
print Person.create(formal_name='John Smith III')
from base import PersonTuple
class Person(PersonTuple):
def __new__(cls, **kwargs):
for field_name in cls._fields:
kwargs.setdefault(field_name, None)
return super(Person, cls).__new__(cls, **kwargs)
print Person(formal_name='John Smith III')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment