summaryrefslogtreecommitdiff
path: root/pypers/oxford/namedtuple.py
diff options
context:
space:
mode:
Diffstat (limited to 'pypers/oxford/namedtuple.py')
-rwxr-xr-xpypers/oxford/namedtuple.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/pypers/oxford/namedtuple.py b/pypers/oxford/namedtuple.py
new file mode 100755
index 0000000..aea1049
--- /dev/null
+++ b/pypers/oxford/namedtuple.py
@@ -0,0 +1,31 @@
+# use operator.itemgetter if we're in 2.4, roll our own if we're in 2.3
+try:
+ from operator import itemgetter
+except ImportError:
+ def itemgetter(i):
+ def getter(self): return self[i]
+ return getter
+def superTuple(typename, *attribute_names):
+ " create and return a subclass of `tuple', with named attributes "
+ # make the subclass with appropriate __new__ and __repr__ specials
+ nargs = len(attribute_names)
+ class supertup(tuple):
+ __slots__ = () # save memory, we don't need per-instance dict
+ def __new__(cls, *args):
+ if len(args) != nargs:
+ raise TypeError, \
+ '%s takes exactly %d arguments (%d given)' % (
+ typename, nargs, len(args))
+ return tuple.__new__(cls, args)
+ def __repr__(self):
+ return '%s(%s)' % (typename, ', '.join(map(repr, self)))
+ # add a few key touches to our new subclass of `tuple'
+ for index, attr_name in enumerate(attribute_names):
+ setattr(supertup, attr_name, property(itemgetter(index)))
+ supertup.__name__ = typename
+ return supertup
+
+Point = superTuple('Point', 'x', 'y')
+p = Point(1,2)
+print p
+print p.x,p.y