SHARE
TWEET

Untitled

a guest Jul 12th, 2013 37 Never
  1. from collections import namedtuple
  2.  
  3. def LenientNamedTuple(name, fields):
  4.     class Wrapper(namedtuple(name, fields)):
  5.         __slots__ = ()
  6.         def __new__(cls, *args, **kwargs):
  7.             kwargs = dict((k, v) for k, v in kwargs.items() if k in fields)
  8.             return super(Wrapper, cls).__new__(cls, *args, **kwargs)
  9.     return Wrapper
  10.  
  11. class Foo(LenientNamedTuple('Foo', ['id', 'name', 'age'])):
  12.     def __init__(self, *args, **kwargs):
  13.         super(Foo, self).__init__()#*args, **kwargs)
  14.  
  15. print(Foo(1, 2, 3))
  16. print(Foo(id=1, name=2, age=3))
  17. print(Foo(1, age=3, name=2))
  18. print(Foo(id=1, name=2, age=3, spam=4))
  19. print(Foo(1, 2, 3, spam=4))
  20. print(Foo(1, 2, spam=4, age=3))
RAW Paste Data
Top