Named tuples
graham__fawcett at hotmail.com
graham__fawcett at hotmail.com
Fri Nov 19 10:21:50 EST 2004
Oops, let's try that again:
| class namedtuplewrapper(tuple):
| """
| wraps an existing tuple, providing names.
| """
|
| _names_ = []
|
| def __getattr__(self, name):
| try:
| x = self._names_.index(name)
| except ValueError:
| raise AttributeError, 'no such field: %s' % name
| if x >= 0:
| return self[x]
|
| class namedtuple(namedtuplewrapper):
| """
| Sugar for a class that constructs named tuples from
| positional arguments.
| """
|
| def __new__(cls, *args):
| return tuple.__new__(cls, args)
|
|
| if __name__ == '__main__':
|
| # namedtuple example
|
| class foo(namedtuple):
| _names_ = ['one', 'two', 'three', 'four', 'five']
|
| f = foo(1, 2, 3, 4, 5)
| assert f.one + f.four == f.five
|
|
| # wrapper example
|
| class loctime(namedtuplewrapper):
| _names_ = [
| 'year', 'month', 'day',
| 'hour', 'min', 'sec',
| 'wday', 'yday', 'isdst'
| ]
|
| import time
| print time.localtime()
| loc = loctime(time.localtime())
| print loc.year, loc.month, loc.day
|
| # arbitrary naming...
| loc._names_ = ['a', 'b', 'c']
| print loc.a
-- Graham
More information about the Python-list
mailing list