Last active
August 29, 2015 14:08
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
PersonTuple = namedtuple('PersonTuple', ['formal_name', 'preferred_name']) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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