1
2
3
4
5
6
7
8
9 import sys
10 try:
11 from operator import itemgetter
12 except ImportError:
14 def getter(self): return self[i]
15 return getter
17 """ create and return a subclass of `tuple', with named attributes
18 Example:
19 >>> Point = supertuple.superTuple('Point','x','y')
20 >>> Point
21 <class 'supertuple.Point'>
22 >>> p = Point(1,2,3) # wrong number of fields
23 Traceback (most recent call last):
24 ...
25 TypeError: Point exactly 2 arguments (3 given)
26 >>> p = Point(1,2) # Do it right this time.
27 >>> p
28 Point(1,2)
29 >>> print p.x, p.y
30 1 2
31 """
32
33 nargs = len(attribute_names)
34 class supertup(tuple):
35 __slots__ = ()
36 def __new__(cls, *args):
37 if len(args) != nargs:
38 raise TypeError, '%s takes exactly %d arguments (%d given)' % (
39 typename, nargs, len(args))
40 return tuple.__new__(cls, args)
41 def __repr__(self):
42 return '%s(%s)' % (typename, ', '.join(map(repr, self)))
43
44 for index, attr_name in enumerate(attribute_names):
45 setattr(supertup, attr_name, property(itemgetter(index)))
46 supertup.__name__ = typename
47 return supertup
48
49
50
52 """ create and return a subclass of `tuple', with named attributes
53 Example:
54 >>> Point = supertuple.superTuplePlus('Point','x','y')
55 >>> Point
56 <class 'supertuple.Point'>
57 >>> p = Point(x=1,y=2,z=3) # wrong number of fields
58 Traceback (most recent call last):
59 ...
60 TypeError: Point exactly 2 arguments (3 given)
61 >>> p = Point(x=1,y=2) # Do it right this time.
62 >>> p
63 Point(1,2)
64 >>> print p.x, p.y
65 1 2
66 """
67 nargs = len(attribute_names)
68 class supertup(tuple):
69 __slots__ = ()
70 def __new__(cls, *args, **kwds):
71 args_copy = list(args)
72 if len(kwds) + len(args) != nargs:
73 raise TypeError, '%s takes exactly %d arguments (%d given)' % (
74 typename, nargs, len(args)+len(kwds))
75 errs =[]
76 for index in range(len(args),len(attribute_names)):
77 attr_name = attribute_names[index]
78 try:
79 args_copy.append(kwds[attr_name])
80 del kwds[attr_name]
81 except KeyError:
82 errs.append('Missing %s attribute: %s\n ' % (typename, attr_name))
83 if kwds:
84
85 if args:
86 errs.append('Type %s: %s filled by positional arguments\n ' % (typename,attribute_names[:len(args)]))
87 errs = ''.join(errs)
88 raise TypeError, errs+'Unknown or duplicate %s keyword arguments: %s' % (typename, kwds.keys())
89 else:
90 return tuple.__new__(cls, args_copy)
91 def __repr__(self):
92 return '%s(%s)' % (typename, ', '.join(map(repr, self)))
93 def display (self):
94 for attr_name in attribute_names:
95 print '%s: %s' % (attr_name, getattr(self, attr_name))
96
97 for index, attr_name in enumerate(attribute_names):
98 setattr(supertup, attr_name, property(itemgetter(index)))
99 supertup.__name__ = typename
100 return supertup
101