4 ms·
This is, in fact, the exact reason for the _source attribute which is being discussed in this article - you can use namedtuple to easily create a structure, get
by hchasestevens 9y ago
This is, in fact, the exact reason for the _source attribute which is being discussed in this article - you can use namedtuple to easily create a structure, get its source, and then edit it to suit your individual project needs. E.g.:
>>> from collections import namedtuple
>>> FullName = namedtuple("FullName", "forename surname")
>>> print(FullName._source)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class FullName(tuple):
'FullName(forename, surname)'
__slots__ = ()
_fields = ('forename', 'surname')
def __new__(_cls, forename, surname):
'Create new instance of FullName(forename, surname)'
return _tuple.__new__(_cls, (forename, surname))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new FullName object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new FullName object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('forename', 'surname'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(forename=%r, surname=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return OrderedDict(zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
forename = _property(_itemgetter(0), doc='Alias for field number 0')
surname = _property(_itemgetter(1), doc='Alias for field number 1')
You can then pretty simply remove the inheritance from tuple and change the properties to get the behavior you describe.
- nerdponx 9y agoThis is a nice touch but insisting that it should be part of the stock functionality for a basic data structure makes no sense to me.
- eesmith 9y agoI do not think it's simple to remove the __getitem__ lookup behavior from this template. To start with, forename depends on _itemgetter(0). I might as well re-write it as: class FullName(object): __slots__ = ("_forename", "_surname") def __init__(self, forename, surname): self._forename = forename self._surname = surname def __repr__(self): return "%s(forename=%r, surname=%r)" % ( self.__class__.__name__, self._forename, self._surname) @property def forename(self): return self._forename @property def surname(self): return self._surname That took about two minutes to write. How long does it take you to rewrite the _source so it doesn't support __getitem__ or __len__?