Skip to content

Instantly share code, notes, and snippets.

@seanjensengrey
Created July 18, 2015 20:33
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 seanjensengrey/9b27a241e26bae445950 to your computer and use it in GitHub Desktop.
Save seanjensengrey/9b27a241e26bae445950 to your computer and use it in GitHub Desktop.
In [1]: from collections import namedtuple
In [2]: T = namedtuple("T","a b c",verbose=True)
class T(tuple):
'T(a, b, c)'
__slots__ = ()
_fields = ('a', 'b', 'c')
def __new__(_cls, a, b, c):
'Create new instance of T(a, b, c)'
return _tuple.__new__(_cls, (a, b, c))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new T object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 3:
raise TypeError('Expected 3 arguments, got %d' % len(result))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return 'T(a=%r, b=%r, c=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
def _replace(_self, **kwds):
'Return a new T object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('a', 'b', 'c'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
__dict__ = _property(_asdict)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
pass
a = _property(_itemgetter(0), doc='Alias for field number 0')
b = _property(_itemgetter(1), doc='Alias for field number 1')
c = _property(_itemgetter(2), doc='Alias for field number 2')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment