1 """Functions missing from Python 2.5"""
4 from itertools
import permutations
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
)
12 r
= n
if r
is None else r
16 cycles
= range(n
, n
-r
, -1)
17 yield tuple(pool
[i
] for i
in indices
[:r
])
19 for i
in reversed(range(r
)):
22 indices
[i
:] = indices
[i
+1:] + indices
[i
:i
+1]
26 indices
[i
], indices
[-j
] = indices
[-j
], indices
[i
]
27 yield tuple(pool
[i
] for i
in indices
[:r
])
33 from collections
import namedtuple
35 # http://code.activestate.com/recipes/500261-named-tuples/
36 from operator
import itemgetter
as _itemgetter
37 from keyword
import iskeyword
as _iskeyword
40 def namedtuple(typename
, field_names
, verbose
=False, rename
=False):
41 """Returns a new subclass of tuple with named fields.
43 >>> Point = namedtuple('Point', 'x y')
44 >>> Point.__doc__ # docstring for the new class
46 >>> p = Point(11, y=22) # instantiate with positional args or keywords
47 >>> p[0] + p[1] # indexable like a plain tuple
49 >>> x, y = p # unpack like a regular tuple
52 >>> p.x + p.y # fields also accessable by name
54 >>> d = p._asdict() # convert to a dictionary
57 >>> Point(**d) # convert from a dictionary
59 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
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
))
70 names
= list(field_names
)
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('_')
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
)
83 raise ValueError('Type names and field names cannot be a keyword: %r' % name
)
85 raise ValueError('Type names and field names cannot start with a number: %r' % name
)
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
)
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
101 _fields = %(field_names)r \n
102 def __new__(_cls, %(argtxt)s):
103 return _tuple.__new__(_cls, (%(argtxt)s)) \n
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))
112 return '%(typename)s(%(reprtxt)s)' %% self \n
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))
120 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
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
)
129 # Execute the template string in a temporary namespace
130 namespace
= dict(_itemgetter
=_itemgetter
, __name__
='namedtuple_%s' % typename
,
131 _property
=property, _tuple
=tuple)
133 exec template
in namespace
134 except SyntaxError, e
:
135 raise SyntaxError(e
.message
+ ':\n' + template
)
136 result
= namespace
[typename
]
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).
143 result
.__module__
= _sys
._getframe(1).f_globals
.get('__name__', '__main__')
144 except (AttributeError, ValueError):