1 """Things missing from older versions of Python
3 Currently these are functions missing from Python 2.5.
7 from itertools
import permutations
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
)
15 r
= n
if r
is None else r
19 cycles
= range(n
, n
-r
, -1)
20 yield tuple(pool
[i
] for i
in indices
[:r
])
22 for i
in reversed(range(r
)):
25 indices
[i
:] = indices
[i
+1:] + indices
[i
:i
+1]
29 indices
[i
], indices
[-j
] = indices
[-j
], indices
[i
]
30 yield tuple(pool
[i
] for i
in indices
[:r
])
36 from collections
import namedtuple
38 # http://code.activestate.com/recipes/500261-named-tuples/
39 from operator
import itemgetter
as _itemgetter
40 from keyword
import iskeyword
as _iskeyword
43 def namedtuple(typename
, field_names
, verbose
=False, rename
=False):
44 """Returns a new subclass of tuple with named fields.
46 >>> Point = namedtuple('Point', 'x y')
47 >>> Point.__doc__ # docstring for the new class
49 >>> p = Point(11, y=22) # instantiate with positional args or keywords
50 >>> p[0] + p[1] # indexable like a plain tuple
52 >>> x, y = p # unpack like a regular tuple
55 >>> p.x + p.y # fields also accessable by name
57 >>> d = p._asdict() # convert to a dictionary
60 >>> Point(**d) # convert from a dictionary
62 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
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
))
73 names
= list(field_names
)
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('_')
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
)
86 raise ValueError('Type names and field names cannot be a keyword: %r' % name
)
88 raise ValueError('Type names and field names cannot start with a number: %r' % name
)
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
)
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
104 _fields = %(field_names)r \n
105 def __new__(_cls, %(argtxt)s):
106 return _tuple.__new__(_cls, (%(argtxt)s)) \n
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))
115 return '%(typename)s(%(reprtxt)s)' %% self \n
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))
123 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
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
)
132 # Execute the template string in a temporary namespace
133 namespace
= dict(_itemgetter
=_itemgetter
, __name__
='namedtuple_%s' % typename
,
134 _property
=property, _tuple
=tuple)
136 exec template
in namespace
137 except SyntaxError, e
:
138 raise SyntaxError(e
.message
+ ':\n' + template
)
139 result
= namespace
[typename
]
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).
146 result
.__module__
= _sys
._getframe(1).f_globals
.get('__name__', '__main__')
147 except (AttributeError, ValueError):