Merge remote-tracking branch 'origin/encukou'
[zzz-pokedex.git] / pokedex / util.py
1 """Functions missing from Python 2.5"""
2
3 try:
4 from itertools import permutations
5 except ImportError:
6 # From the itertools documentation
7 def permutations(iterable, r=None):
8 # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
9 # permutations(range(3)) --> 012 021 102 120 201 210
10 pool = tuple(iterable)
11 n = len(pool)
12 r = n if r is None else r
13 if r > n:
14 return
15 indices = range(n)
16 cycles = range(n, n-r, -1)
17 yield tuple(pool[i] for i in indices[:r])
18 while n:
19 for i in reversed(range(r)):
20 cycles[i] -= 1
21 if cycles[i] == 0:
22 indices[i:] = indices[i+1:] + indices[i:i+1]
23 cycles[i] = n - i
24 else:
25 j = cycles[i]
26 indices[i], indices[-j] = indices[-j], indices[i]
27 yield tuple(pool[i] for i in indices[:r])
28 break
29 else:
30 return
31
32 try:
33 from collections import namedtuple
34 except ImportError:
35 # http://code.activestate.com/recipes/500261-named-tuples/
36 from operator import itemgetter as _itemgetter
37 from keyword import iskeyword as _iskeyword
38 import sys as _sys
39
40 def namedtuple(typename, field_names, verbose=False, rename=False):
41 """Returns a new subclass of tuple with named fields.
42
43 >>> Point = namedtuple('Point', 'x y')
44 >>> Point.__doc__ # docstring for the new class
45 'Point(x, y)'
46 >>> p = Point(11, y=22) # instantiate with positional args or keywords
47 >>> p[0] + p[1] # indexable like a plain tuple
48 33
49 >>> x, y = p # unpack like a regular tuple
50 >>> x, y
51 (11, 22)
52 >>> p.x + p.y # fields also accessable by name
53 33
54 >>> d = p._asdict() # convert to a dictionary
55 >>> d['x']
56 11
57 >>> Point(**d) # convert from a dictionary
58 Point(x=11, y=22)
59 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
60 Point(x=100, y=22)
61
62 """
63
64 # Parse and validate the field names. Validation serves two purposes,
65 # generating informative error messages and preventing template injection attacks.
66 if isinstance(field_names, basestring):
67 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
68 field_names = tuple(map(str, field_names))
69 if rename:
70 names = list(field_names)
71 seen = set()
72 for i, name in enumerate(names):
73 if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
74 or not name or name[0].isdigit() or name.startswith('_')
75 or name in seen):
76 names[i] = '_%d' % i
77 seen.add(name)
78 field_names = tuple(names)
79 for name in (typename,) + field_names:
80 if not min(c.isalnum() or c=='_' for c in name):
81 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
82 if _iskeyword(name):
83 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
84 if name[0].isdigit():
85 raise ValueError('Type names and field names cannot start with a number: %r' % name)
86 seen_names = set()
87 for name in field_names:
88 if name.startswith('_') and not rename:
89 raise ValueError('Field names cannot start with an underscore: %r' % name)
90 if name in seen_names:
91 raise ValueError('Encountered duplicate field name: %r' % name)
92 seen_names.add(name)
93
94 # Create and fill-in the class template
95 numfields = len(field_names)
96 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
97 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
98 template = '''class %(typename)s(tuple):
99 '%(typename)s(%(argtxt)s)' \n
100 __slots__ = () \n
101 _fields = %(field_names)r \n
102 def __new__(_cls, %(argtxt)s):
103 return _tuple.__new__(_cls, (%(argtxt)s)) \n
104 @classmethod
105 def _make(cls, iterable, new=tuple.__new__, len=len):
106 'Make a new %(typename)s object from a sequence or iterable'
107 result = new(cls, iterable)
108 if len(result) != %(numfields)d:
109 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
110 return result \n
111 def __repr__(self):
112 return '%(typename)s(%(reprtxt)s)' %% self \n
113 def _asdict(self):
114 'Return a new dict which maps field names to their values'
115 return dict(zip(self._fields, self)) \n
116 def _replace(_self, **kwds):
117 'Return a new %(typename)s object replacing specified fields with new values'
118 result = _self._make(map(kwds.pop, %(field_names)r, _self))
119 if kwds:
120 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
121 return result \n
122 def __getnewargs__(self):
123 return tuple(self) \n\n''' % locals()
124 for i, name in enumerate(field_names):
125 template += ' %s = _property(_itemgetter(%d))\n' % (name, i)
126 if verbose:
127 print template
128
129 # Execute the template string in a temporary namespace
130 namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
131 _property=property, _tuple=tuple)
132 try:
133 exec template in namespace
134 except SyntaxError, e:
135 raise SyntaxError(e.message + ':\n' + template)
136 result = namespace[typename]
137
138 # For pickling to work, the __module__ variable needs to be set to the frame
139 # where the named tuple is created. Bypass this step in enviroments where
140 # sys._getframe is not defined (Jython for example) or sys._getframe is not
141 # defined for arguments greater than 0 (IronPython).
142 try:
143 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
144 except (AttributeError, ValueError):
145 pass
146
147 return result
148