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