Ordered lists with named fields for PythonI periodically find myself dealing with structures that are basically ordered lists with named fields, where elements 0, 1, and 2 are naturally named 'a', 'b', and 'c' and sometimes you want to refer to them by name instead of having to remember their position. This pattern even crops up in the standard Python library, often with functions that started out just returning an ordered list and grew the named fields portion later as people discovered how annoying it was to have to remember that the hour was field 3. This being Python, I've built myself some general code to add named
fields on top of sequence types like
class GetMixin(object):
fields = {}
def _mapslice(self, key):
s, e, step = key.start, key.stop, key.step
if s in self.fields:
s = self.fields[s]
if e in self.fields:
e = self.fields[e]
return slice(s, e, step)
def _mapkey(self, key):
if isinstance(key, tuple):
pass
elif isinstance(key, slice):
key = self._mapslice(key)
elif key in self.fields:
key = self.fields[key]
return key
def __getitem__(self, key):
key = self._mapkey(key)
return super(GetMixin, self).__getitem__(key)
def __getattr__(self, name):
if name in self.fields:
return self[self.fields[name]]
raise AttributeError, \
"object has no attribute '%s'" % name
class SetMixin(GetMixin):
def __setitem__(self, key, value):
key = self._mapkey(key)
super(SetMixin, self).__setitem__(key, value)
def __setattr__(self, name, value):
if name in self.fields:
o = self.fields[name]
self[o] = value
else:
self.__dict__[name] = value
class Example(SetMixin, list):
fields = {'a': 0, 'b': 1, 'c': 2}
The
(If you're going to do this a lot, make a version of Inheriting from list, tuple, etc does have one practical wart: you
probably want to avoid using field names that are the names of methods
that you want to use, because you won't be able to use the (This code is not quite neurotically complete; truly neurotically
complete code would make the available fields appear in |
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |