desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'In the usual case, use ParseResponse (or ParseFile) to create new
HTMLForm objects.
action: full (absolute URI) form action
method: "GET" or "POST"
enctype: form transfer encoding MIME type
name: name of form
attrs: dictionary mapping original HTML form attributes to their values'
| def __init__(self, action, method='GET', enctype=None, name=None, attrs=None, request_class=urllib2.Request, forms=None, labels=None, id_to_labels=None, backwards_compat=True):
| self.action = action
self.method = method
self.enctype = (enctype or 'application/x-www-form-urlencoded')
self.name = name
if (attrs is not None):
self.attrs = attrs.copy()
else:
self.attrs = {}
self.controls = []
self._request_class = request_class
self._forms = forms
self._labels = labels
self._id_to_labels = id_to_labels
self.backwards_compat = backwards_compat
self._urlunparse = urlparse.urlunparse
self._urlparse = urlparse.urlparse
|
'Adds a new control to the form.
This is usually called by ParseFile and ParseResponse. Don\'t call it
youself unless you\'re building your own Control instances.
Note that controls representing lists of items are built up from
controls holding only a single list item. See ListControl.__doc__ for
further information.
type: type of control (see Control.__doc__ for a list)
attrs: HTML attributes of control
ignore_unknown: if true, use a dummy Control instance for controls of
unknown type; otherwise, use a TextControl
select_default: for RADIO and multiple-selection SELECT controls, pick
the first item as the default if no \'selected\' HTML attribute is
present (this defaulting happens when the HTMLForm.fixup method is
called)
index: index of corresponding element in HTML (see
MoreFormTests.test_interspersed_controls for motivation)'
| def new_control(self, type, name, attrs, ignore_unknown=False, select_default=False, index=None):
| type = type.lower()
klass = self.type2class.get(type)
if (klass is None):
if ignore_unknown:
klass = IgnoreControl
else:
klass = TextControl
a = attrs.copy()
if issubclass(klass, ListControl):
control = klass(type, name, a, select_default, index)
else:
control = klass(type, name, a, index)
if ((type == 'select') and (len(attrs) == 1)):
for ii in xrange((len(self.controls) - 1), (-1), (-1)):
ctl = self.controls[ii]
if (ctl.type == 'select'):
ctl.close_control()
break
control.add_to_form(self)
control._urlparse = self._urlparse
control._urlunparse = self._urlunparse
|
'Normalise form after all controls have been added.
This is usually called by ParseFile and ParseResponse. Don\'t call it
youself unless you\'re building your own Control instances.
This method should only be called once, after all controls have been
added to the form.'
| def fixup(self):
| for control in self.controls:
control.fixup()
self.backwards_compat = self._backwards_compat
|
'Return value of control.
If only name and value arguments are supplied, equivalent to
form[name]'
| def get_value(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| if by_label:
deprecation('form.get_value_by_label(...)')
c = self.find_control(name, type, kind, id, label=label, nr=nr)
if by_label:
try:
meth = c.get_value_by_label
except AttributeError:
raise NotImplementedError(("control '%s' does not yet support by_label" % c.name))
else:
return meth()
else:
return c.value
|
'Set value of control.
If only name and value arguments are supplied, equivalent to
form[name] = value'
| def set_value(self, value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| if by_label:
deprecation('form.get_value_by_label(...)')
c = self.find_control(name, type, kind, id, label=label, nr=nr)
if by_label:
try:
meth = c.set_value_by_label
except AttributeError:
raise NotImplementedError(("control '%s' does not yet support by_label" % c.name))
else:
meth(value)
else:
c.value = value
|
'All arguments should be passed by name.'
| def get_value_by_label(self, name=None, type=None, kind=None, id=None, label=None, nr=None):
| c = self.find_control(name, type, kind, id, label=label, nr=nr)
return c.get_value_by_label()
|
'All arguments should be passed by name.'
| def set_value_by_label(self, value, name=None, type=None, kind=None, id=None, label=None, nr=None):
| c = self.find_control(name, type, kind, id, label=label, nr=nr)
c.set_value_by_label(value)
|
'Clear the value attributes of all controls in the form.
See HTMLForm.clear.__doc__.'
| def clear_all(self):
| for control in self.controls:
control.clear()
|
'Clear the value attribute of a control.
As a result, the affected control will not be successful until a value
is subsequently set. AttributeError is raised on readonly controls.'
| def clear(self, name=None, type=None, kind=None, id=None, nr=None, label=None):
| c = self.find_control(name, type, kind, id, label=label, nr=nr)
c.clear()
|
'Return a list of all values that the specified control can take.'
| def possible_items(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| c = self._find_list_control(name, type, kind, id, label, nr)
return c.possible_items(by_label)
|
'Select / deselect named list item.
selected: boolean selected state'
| def set(self, selected, item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| self._find_list_control(name, type, kind, id, label, nr).set(selected, item_name, by_label)
|
'Toggle selected state of named list item.'
| def toggle(self, item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None):
| self._find_list_control(name, type, kind, id, label, nr).toggle(item_name, by_label)
|
'Select / deselect list item in a control having only one item.
If the control has multiple list items, ItemCountError is raised.
This is just a convenience method, so you don\'t need to know the item\'s
name -- the item name in these single-item controls is usually
something meaningless like "1" or "on".
For example, if a checkbox has a single item named "on", the following
two calls are equivalent:
control.toggle("on")
control.toggle_single()'
| def set_single(self, selected, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None):
| self._find_list_control(name, type, kind, id, label, nr).set_single(selected)
|
'Toggle selected state of list item in control having only one item.
The rest is as for HTMLForm.set_single.__doc__.'
| def toggle_single(self, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None):
| self._find_list_control(name, type, kind, id, label, nr).toggle_single()
|
'Add a file to be uploaded.
file_object: file-like object (with read method) from which to read
data to upload
content_type: MIME content type of data to upload
filename: filename to pass to server
If filename is None, no filename is sent to the server.
If content_type is None, the content type is guessed based on the
filename and the data from read from the file object.
XXX
At the moment, guessed content type is always application/octet-stream.
Use sndhdr, imghdr modules. Should also try to guess HTML, XML, and
plain text.
Note the following useful HTML attributes of file upload controls (see
HTML 4.01 spec, section 17):
accept: comma-separated list of content types that the server will
handle correctly; you can use this to filter out non-conforming files
size: XXX IIRC, this is indicative of whether form wants multiple or
single files
maxlength: XXX hint of max content length in bytes?'
| def add_file(self, file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None):
| self.find_control(name, 'file', id=id, label=label, nr=nr).add_file(file_object, content_type, filename)
|
'Return request that would result from clicking on a control.
The request object is a urllib2.Request instance, which you can pass to
urllib2.urlopen (or ClientCookie.urlopen).
Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and
IMAGEs) can be clicked.
Will click on the first clickable control, subject to the name, type
and nr arguments (as for find_control). If no name, type, id or number
is specified and there are no clickable controls, a request will be
returned for the form in its current, un-clicked, state.
IndexError is raised if any of name, type, id or nr is specified but no
matching control is found. ValueError is raised if the HTMLForm has an
enctype attribute that is not recognised.
You can optionally specify a coordinate to click at, which only makes a
difference if you clicked on an image.'
| def click(self, name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=urllib2.Request, label=None):
| return self._click(name, type, id, label, nr, coord, 'request', self._request_class)
|
'As for click method, but return a tuple (url, data, headers).
You can use this data to send a request to the server. This is useful
if you\'re using httplib or urllib rather than urllib2. Otherwise, use
the click method.
# Untested. Have to subclass to add headers, I think -- so use urllib2
# instead!
import urllib
url, data, hdrs = form.click_request_data()
r = urllib.urlopen(url, data)
# Untested. I don\'t know of any reason to use httplib -- you can get
# just as much control with urllib2.
import httplib, urlparse
url, data, hdrs = form.click_request_data()
tup = urlparse(url)
host, path = tup[1], urlparse.urlunparse((None, None)+tup[2:])
conn = httplib.HTTPConnection(host)
if data:
httplib.request("POST", path, data, hdrs)
else:
httplib.request("GET", path, headers=hdrs)
r = conn.getresponse()'
| def click_request_data(self, name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=urllib2.Request, label=None):
| return self._click(name, type, id, label, nr, coord, 'request_data', self._request_class)
|
'As for click_request_data, but returns a list of (key, value) pairs.
You can use this list as an argument to ClientForm.urlencode. This is
usually only useful if you\'re using httplib or urllib rather than
urllib2 or ClientCookie. It may also be useful if you want to manually
tweak the keys and/or values, but this should not be necessary.
Otherwise, use the click method.
Note that this method is only useful for forms of MIME type
x-www-form-urlencoded. In particular, it does not return the
information required for file upload. If you need file upload and are
not using urllib2, use click_request_data.
Also note that Python 2.0\'s urllib.urlencode is slightly broken: it
only accepts a mapping, not a sequence of pairs, as an argument. This
messes up any ordering in the argument. Use ClientForm.urlencode
instead.'
| def click_pairs(self, name=None, type=None, id=None, nr=0, coord=(1, 1), label=None):
| return self._click(name, type, id, label, nr, coord, 'pairs', self._request_class)
|
'Locate and return some specific control within the form.
At least one of the name, type, kind, predicate and nr arguments must
be supplied. If no matching control is found, ControlNotFoundError is
raised.
If name is specified, then the control must have the indicated name.
If type is specified then the control must have the specified type (in
addition to the types possible for <input> HTML tags: "text",
"password", "hidden", "submit", "image", "button", "radio", "checkbox",
"file" we also have "reset", "buttonbutton", "submitbutton",
"resetbutton", "textarea", "select" and "isindex").
If kind is specified, then the control must fall into the specified
group, each of which satisfies a particular interface. The types are
"text", "list", "multilist", "singlelist", "clickable" and "file".
If id is specified, then the control must have the indicated id.
If predicate is specified, then the control must match that function.
The predicate function is passed the control as its single argument,
and should return a boolean value indicating whether the control
matched.
nr, if supplied, is the sequence number of the control (where 0 is the
first). Note that control 0 is the first control matching all the
other arguments (if supplied); it is not necessarily the first control
in the form. If no nr is supplied, AmbiguityError is raised if
multiple controls match the other arguments (unless the
.backwards-compat attribute is true).
If label is specified, then the control must have this label. Note
that radio controls and checkboxes never have labels: their items do.'
| def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None):
| if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (predicate is None) and (nr is None)):
raise ValueError('at least one argument must be supplied to specify control')
return self._find_control(name, type, kind, id, label, predicate, nr)
|
'Return sequence of (key, value) pairs suitable for urlencoding.'
| def _pairs(self):
| return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()]
|
'Return sequence of (index, key, value, control_index)
of totally ordered pairs suitable for urlencoding.
control_index is the index of the control in self.controls'
| def _pairs_and_controls(self):
| pairs = []
for control_index in xrange(len(self.controls)):
control = self.controls[control_index]
for (ii, key, val) in control._totally_ordered_pairs():
pairs.append((ii, key, val, control_index))
pairs.sort()
return pairs
|
'Return a tuple (url, data, headers).'
| def _request_data(self):
| method = self.method.upper()
parts = self._urlparse(self.action)
(rest, (query, frag)) = (parts[:(-2)], parts[(-2):])
if (method == 'GET'):
self.enctype = 'application/x-www-form-urlencoded'
parts = (rest + (urlencode(self._pairs()), None))
uri = self._urlunparse(parts)
return (uri, None, [])
elif (method == 'POST'):
parts = (rest + (query, None))
uri = self._urlunparse(parts)
if (self.enctype == 'application/x-www-form-urlencoded'):
return (uri, urlencode(self._pairs()), [('Content-Type', self.enctype)])
elif (self.enctype == 'text/plain'):
return (uri, self._pairs(), [('Content-Type', self.enctype)])
elif (self.enctype == 'multipart/form-data'):
data = StringIO()
http_hdrs = []
mw = MimeWriter(data, http_hdrs)
f = mw.startmultipartbody('form-data', add_to_http_hdrs=True, prefix=0)
for (ii, k, v, control_index) in self._pairs_and_controls():
self.controls[control_index]._write_mime_data(mw, k, v)
mw.lastpart()
return (uri, data.getvalue(), http_hdrs)
else:
raise ValueError(("unknown POST form encoding type '%s'" % self.enctype))
else:
raise ValueError(("Unknown method '%s'" % method))
|
'Aggregate two event values.'
| def aggregate(self, val1, val2):
| assert (val1 is not None)
assert (val2 is not None)
return self._aggregator(val1, val2)
|
'Format an event value.'
| def format(self, val):
| assert (val is not None)
return self._formatter(val)
|
'Validate the edges.'
| def validate(self):
| for function in self.functions.itervalues():
for callee_id in function.calls.keys():
assert (function.calls[callee_id].callee_id == callee_id)
if (callee_id not in self.functions):
sys.stderr.write(('warning: call to undefined function %s from function %s\n' % (str(callee_id), function.name)))
del function.calls[callee_id]
|
'Find cycles using Tarjan\'s strongly connected components algorithm.'
| def find_cycles(self):
| visited = set()
for function in self.functions.itervalues():
if (function not in visited):
self._tarjan(function, 0, [], {}, {}, visited)
cycles = []
for function in self.functions.itervalues():
if ((function.cycle is not None) and (function.cycle not in cycles)):
cycles.append(function.cycle)
self.cycles = cycles
if 0:
for cycle in cycles:
sys.stderr.write('Cycle:\n')
for member in cycle.functions:
sys.stderr.write((' DCTB Function %s\n' % member.name))
|
'Tarjan\'s strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan\'s_strongly_connected_components_algorithm'
| def _tarjan(self, function, order, stack, orders, lowlinks, visited):
| visited.add(function)
orders[function] = order
lowlinks[function] = order
order += 1
pos = len(stack)
stack.append(function)
for call in function.calls.itervalues():
callee = self.functions[call.callee_id]
if (callee not in orders):
order = self._tarjan(callee, order, stack, orders, lowlinks, visited)
lowlinks[function] = min(lowlinks[function], lowlinks[callee])
elif (callee in stack):
lowlinks[function] = min(lowlinks[function], orders[callee])
if (lowlinks[function] == orders[function]):
members = stack[pos:]
del stack[pos:]
if (len(members) > 1):
cycle = Cycle()
for member in members:
cycle.add_function(member)
return order
|
'Propagate function time ratio allong the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html'
| def integrate(self, outevent, inevent):
| assert (outevent not in self)
for function in self.functions.itervalues():
assert (outevent not in function)
assert (inevent in function)
for call in function.calls.itervalues():
assert (outevent not in call)
if (call.callee_id != function.id):
assert (call.ratio is not None)
for cycle in self.cycles:
total = inevent.null()
for function in self.functions.itervalues():
total = inevent.aggregate(total, function[inevent])
self[inevent] = total
total = inevent.null()
for function in self.functions.itervalues():
total = inevent.aggregate(total, function[inevent])
self._integrate_function(function, outevent, inevent)
self[outevent] = total
|
'Aggregate an event for the whole profile.'
| def aggregate(self, event):
| total = event.null()
for function in self.functions.itervalues():
try:
total = event.aggregate(total, function[event])
except UndefinedEvent:
return
self[event] = total
|
'Prune the profile'
| def prune(self, node_thres, edge_thres):
| for function in self.functions.itervalues():
try:
function.weight = function[TOTAL_TIME_RATIO]
except UndefinedEvent:
pass
for call in function.calls.itervalues():
callee = self.functions[call.callee_id]
if (TOTAL_TIME_RATIO in call):
call.weight = call[TOTAL_TIME_RATIO]
else:
try:
call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO])
except UndefinedEvent:
pass
for function_id in self.functions.keys():
function = self.functions[function_id]
if (function.weight is not None):
if (function.weight < node_thres):
del self.functions[function_id]
for function in self.functions.itervalues():
for callee_id in function.calls.keys():
call = function.calls[callee_id]
if ((callee_id not in self.functions) or ((call.weight is not None) and (call.weight < edge_thres))):
del function.calls[callee_id]
|
'Extract a structure from a match object, while translating the types in the process.'
| def translate(self, mo):
| attrs = {}
groupdict = mo.groupdict()
for (name, value) in groupdict.iteritems():
if (value is None):
value = None
elif self._int_re.match(value):
value = int(value)
elif self._float_re.match(value):
value = float(value)
attrs[name] = value
return Struct(attrs)
|
'Parse the call graph.'
| def parse_cg(self):
| while (not self._cg_header_re.match(self.readline())):
pass
line = self.readline()
while self._cg_header_re.match(line):
line = self.readline()
entry_lines = []
while (line != '\x0c'):
if (line and (not line.isspace())):
if self._cg_sep_re.match(line):
self.parse_cg_entry(entry_lines)
entry_lines = []
else:
entry_lines.append(line)
line = self.readline()
|
'Convert a color from HSL color-model to RGB.
See also:
- http://www.w3.org/TR/css3-color/#hsl-color'
| def hsl_to_rgb(self, h, s, l):
| h = (h % 1.0)
s = min(max(s, 0.0), 1.0)
l = min(max(l, 0.0), 1.0)
if (l <= 0.5):
m2 = (l * (s + 1.0))
else:
m2 = ((l + s) - (l * s))
m1 = ((l * 2.0) - m2)
r = self._hue_to_rgb(m1, m2, (h + (1.0 / 3.0)))
g = self._hue_to_rgb(m1, m2, h)
b = self._hue_to_rgb(m1, m2, (h - (1.0 / 3.0)))
r **= self.gamma
g **= self.gamma
b **= self.gamma
return (r, g, b)
|
'Main program.'
| def main(self):
| parser = optparse.OptionParser(usage='\n DCTB %prog [options] [file] ...', version=('%%prog %s' % __version__))
parser.add_option('-o', '--output', metavar='FILE', type='string', dest='output', help='output filename [stdout]')
parser.add_option('-n', '--node-thres', metavar='PERCENTAGE', type='float', dest='node_thres', default=0.5, help='eliminate nodes below this threshold [default: %default]')
parser.add_option('-e', '--edge-thres', metavar='PERCENTAGE', type='float', dest='edge_thres', default=0.1, help='eliminate edges below this threshold [default: %default]')
parser.add_option('-f', '--format', type='choice', choices=('prof', 'callgrind', 'oprofile', 'sysprof', 'pstats', 'shark', 'sleepy', 'aqtime', 'xperf'), dest='format', default='prof', help='profile format: prof, callgrind, oprofile, sysprof, shark, sleepy, aqtime, pstats, or xperf [default: %default]')
parser.add_option('-c', '--colormap', type='choice', choices=('color', 'pink', 'gray', 'bw'), dest='theme', default='color', help='color map: color, pink, gray, or bw [default: %default]')
parser.add_option('-s', '--strip', action='store_true', dest='strip', default=False, help='strip function parameters, template parameters, and const modifiers from demangled C++ function names')
parser.add_option('-w', '--wrap', action='store_true', dest='wrap', default=False, help='wrap function names')
parser.add_option('--skew', type='float', dest='theme_skew', default=1.0, help='skew the colorization curve. Values < 1.0 give more variety to lower percentages. Value > 1.0 give less variety to lower percentages')
(self.options, self.args) = parser.parse_args(sys.argv[1:])
if ((len(self.args) > 1) and (self.options.format != 'pstats')):
parser.error('incorrect number of arguments')
try:
self.theme = self.themes[self.options.theme]
except KeyError:
parser.error(("invalid colormap '%s'" % self.options.theme))
if self.options.theme_skew:
self.theme.skew = self.options.theme_skew
if (self.options.format == 'prof'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = GprofParser(fp)
elif (self.options.format == 'callgrind'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = CallgrindParser(fp)
elif (self.options.format == 'oprofile'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = OprofileParser(fp)
elif (self.options.format == 'sysprof'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = SysprofParser(fp)
elif (self.options.format == 'pstats'):
if (not self.args):
parser.error('at least a file must be specified for pstats input')
parser = PstatsParser(*self.args)
elif (self.options.format == 'xperf'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = XPerfParser(fp)
elif (self.options.format == 'shark'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = SharkParser(fp)
elif (self.options.format == 'sleepy'):
if (len(self.args) != 1):
parser.error('exactly one file must be specified for sleepy input')
parser = SleepyParser(self.args[0])
elif (self.options.format == 'aqtime'):
if (not self.args):
fp = sys.stdin
else:
fp = open(self.args[0], 'rt')
parser = AQtimeParser(fp)
else:
parser.error(("invalid format '%s'" % self.options.format))
self.profile = parser.parse()
if (self.options.output is None):
self.output = sys.stdout
else:
self.output = open(self.options.output, 'wt')
self.write_graph()
|
'Remove extraneous information from C++ demangled function names.'
| def strip_function_name(self, name):
| while True:
(name, n) = self._parenthesis_re.subn('', name)
if (not n):
break
name = self._const_re.sub('', name)
while True:
(name, n) = self._angles_re.subn('', name)
if (not n):
break
return name
|
'Split the function name on multiple lines.'
| def wrap_function_name(self, name):
| if (len(name) > 32):
ratio = (2.0 / 3.0)
height = max(int(((len(name) / (1.0 - ratio)) + 0.5)), 1)
width = max((len(name) / height), 32)
name = textwrap.fill(name, width, break_long_words=False)
name = name.replace(', ', ',')
name = name.replace('> >', '>>')
name = name.replace('> >', '>>')
return name
|
'Compress function name according to the user preferences.'
| def compress_function_name(self, name):
| if self.options.strip:
name = self.strip_function_name(name)
if self.options.wrap:
name = self.wrap_function_name(name)
return name
|
'Register a virtual subclass of an ABC.'
| def register(cls, subclass):
| if (not isinstance(subclass, (type, types.ClassType))):
raise TypeError('Can only register classes')
if issubclass(subclass, cls):
return
if issubclass(cls, subclass):
raise RuntimeError('Refusing to create an inheritance cycle')
cls._abc_registry.add(subclass)
ABCMeta._abc_invalidation_counter += 1
|
'Debug helper to print the ABC registry.'
| def _dump_registry(cls, file=None):
| print >>file, ('Class: %s.%s' % (cls.__module__, cls.__name__))
print >>file, ('Inv.counter: %s' % ABCMeta._abc_invalidation_counter)
for name in sorted(cls.__dict__.keys()):
if name.startswith('_abc_'):
value = getattr(cls, name)
print >>file, ('%s: %r' % (name, value))
|
'Override for isinstance(instance, cls).'
| def __instancecheck__(cls, instance):
| subclass = getattr(instance, '__class__', None)
if (subclass in cls._abc_cache):
return True
subtype = type(instance)
if (subtype is _InstanceType):
subtype = subclass
if ((subtype is subclass) or (subclass is None)):
if ((cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter) and (subtype in cls._abc_negative_cache)):
return False
return cls.__subclasscheck__(subtype)
return (cls.__subclasscheck__(subclass) or cls.__subclasscheck__(subtype))
|
'Override for issubclass(subclass, cls).'
| def __subclasscheck__(cls, subclass):
| if (subclass in cls._abc_cache):
return True
if (cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter):
cls._abc_negative_cache = set()
cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
elif (subclass in cls._abc_negative_cache):
return False
ok = cls.__subclasshook__(subclass)
if (ok is not NotImplemented):
assert isinstance(ok, bool)
if ok:
cls._abc_cache.add(subclass)
else:
cls._abc_negative_cache.add(subclass)
return ok
if (cls in getattr(subclass, '__mro__', ())):
cls._abc_cache.add(subclass)
return True
for rcls in cls._abc_registry:
if issubclass(subclass, rcls):
cls._abc_cache.add(subclass)
return True
for scls in cls.__subclasses__():
if issubclass(subclass, scls):
cls._abc_cache.add(subclass)
return True
cls._abc_negative_cache.add(subclass)
return False
|
'Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.'
| @classmethod
def _from_iterable(cls, it):
| return cls(it)
|
'Compute the hash value of a set.
Note that we don\'t define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there\'s not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.'
| def _hash(self):
| MAX = sys.maxint
MASK = ((2 * MAX) + 1)
n = len(self)
h = (1927868237 * (n + 1))
h &= MASK
for x in self:
hx = hash(x)
h ^= (((hx ^ (hx << 16)) ^ 89869747) * 3644798167)
h &= MASK
h = ((h * 69069) + 907133923)
h &= MASK
if (h > MAX):
h -= (MASK + 1)
if (h == (-1)):
h = 590923713
return h
|
'Add an element.'
| @abstractmethod
def add(self, value):
| raise NotImplementedError
|
'Remove an element. Do not raise an exception if absent.'
| @abstractmethod
def discard(self, value):
| raise NotImplementedError
|
'Remove an element. If not a member, raise a KeyError.'
| def remove(self, value):
| if (value not in self):
raise KeyError(value)
self.discard(value)
|
'Return the popped value. Raise KeyError if empty.'
| def pop(self):
| it = iter(self)
try:
value = it.next()
except StopIteration:
raise KeyError
self.discard(value)
return value
|
'This is slow (creates N new iterators!) but effective.'
| def clear(self):
| try:
while True:
self.pop()
except KeyError:
pass
|
'return a list of connected hosts and the number of connections
to each. [(\'foo.com:80\', 2), (\'bar.org\', 1)]'
| def open_connections(self):
| return [(host, len(li)) for (host, li) in self._cm.get_all().items()]
|
'close connection(s) to <host>
host is the host:port spec, as in \'www.cnn.com:8080\' as passed in.
no error occurs if there is no connection to that host.'
| def close_connection(self, host):
| for h in self._cm.get_all(host):
self._cm.remove(h)
h.close()
|
'close all open connections'
| def close_all(self):
| for (host, conns) in self._cm.get_all().items():
for h in conns:
self._cm.remove(h)
h.close()
|
'tells us that this request is now closed and the the
connection is ready for another request'
| def _request_closed(self, request, host, connection):
| self._cm.set_ready(connection, 1)
|
'start the transaction with a re-used connection
return a response object (r) upon success or None on failure.
This DOES not close or remove bad connections in cases where
it returns. However, if an unexpected exception occurs, it
will close and remove the connection before re-raising.'
| def _reuse_connection(self, h, req, host):
| try:
self._start_transaction(h, req)
r = h.getresponse()
except (socket.error, httplib.HTTPException):
r = None
except:
if DEBUG:
DEBUG.error(('unexpected exception - closing ' + 'connection to %s (%d)'), host, id(h))
self._cm.remove(h)
h.close()
raise
if ((r is None) or (r.version == 9)):
if DEBUG:
DEBUG.info('failed to re-use connection to %s (%d)', host, id(h))
r = None
elif DEBUG:
DEBUG.info('re-using connection to %s (%d)', host, id(h))
return r
|
'Create a new ordered dictionary. Cannot init from a normal dict,
nor from kwargs, since items order is undefined in those cases.
If the ``strict`` keyword argument is ``True`` (``False`` is the
default) then when doing slice assignment - the ``OrderedDict`` you are
assigning from *must not* contain any keys in the remaining dict.
>>> OrderedDict()
OrderedDict([])
>>> OrderedDict({1: 1})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
>>> OrderedDict({1: 1}.items())
OrderedDict([(1, 1)])
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1)])
>>> OrderedDict(d)
OrderedDict([(1, 3), (3, 2), (2, 1)])'
| def __init__(self, init_val=(), strict=False):
| self.strict = strict
dict.__init__(self)
if isinstance(init_val, OrderedDict):
self._sequence = init_val.keys()
dict.update(self, init_val)
elif isinstance(init_val, dict):
raise TypeError('undefined order, cannot get items from dict')
else:
self._sequence = []
self.update(init_val)
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> del d[3]
>>> d
OrderedDict([(1, 3), (2, 1)])
>>> del d[3]
Traceback (most recent call last):
KeyError: 3
>>> d[3] = 2
>>> d
OrderedDict([(1, 3), (2, 1), (3, 2)])
>>> del d[0:1]
>>> d
OrderedDict([(2, 1), (3, 2)])'
| def __delitem__(self, key):
| if isinstance(key, types.SliceType):
keys = self._sequence[key]
for entry in keys:
dict.__delitem__(self, entry)
del self._sequence[key]
else:
dict.__delitem__(self, key)
self._sequence.remove(key)
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d == OrderedDict(d)
True
>>> d == OrderedDict(((1, 3), (2, 1), (3, 2)))
False
>>> d == OrderedDict(((1, 0), (3, 2), (2, 1)))
False
>>> d == OrderedDict(((0, 3), (3, 2), (2, 1)))
False
>>> d == dict(d)
False
>>> d == False
False'
| def __eq__(self, other):
| if isinstance(other, OrderedDict):
return (self.items() == other.items())
else:
return False
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> c < d
True
>>> d < c
False
>>> d < dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts'
| def __lt__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() < other.items())
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> e = OrderedDict(d)
>>> c <= d
True
>>> d <= c
False
>>> d <= dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
>>> d <= e
True'
| def __le__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() <= other.items())
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d != OrderedDict(d)
False
>>> d != OrderedDict(((1, 3), (2, 1), (3, 2)))
True
>>> d != OrderedDict(((1, 0), (3, 2), (2, 1)))
True
>>> d == OrderedDict(((0, 3), (3, 2), (2, 1)))
False
>>> d != dict(d)
True
>>> d != False
True'
| def __ne__(self, other):
| if isinstance(other, OrderedDict):
return (not (self.items() == other.items()))
else:
return True
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> d > c
True
>>> c > d
False
>>> d > dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts'
| def __gt__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() > other.items())
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> c = OrderedDict(((0, 3), (3, 2), (2, 1)))
>>> e = OrderedDict(d)
>>> c >= d
False
>>> d >= c
True
>>> d >= dict(c)
Traceback (most recent call last):
TypeError: Can only compare with other OrderedDicts
>>> e >= d
True'
| def __ge__(self, other):
| if (not isinstance(other, OrderedDict)):
raise TypeError('Can only compare with other OrderedDicts')
return (self.items() >= other.items())
|
'Used for __repr__ and __str__
>>> r1 = repr(OrderedDict(((\'a\', \'b\'), (\'c\', \'d\'), (\'e\', \'f\'))))
>>> r1
"OrderedDict([(\'a\', \'b\'), (\'c\', \'d\'), (\'e\', \'f\')])"
>>> r2 = repr(OrderedDict(((\'a\', \'b\'), (\'e\', \'f\'), (\'c\', \'d\'))))
>>> r2
"OrderedDict([(\'a\', \'b\'), (\'e\', \'f\'), (\'c\', \'d\')])"
>>> r1 == str(OrderedDict(((\'a\', \'b\'), (\'c\', \'d\'), (\'e\', \'f\'))))
True
>>> r2 == str(OrderedDict(((\'a\', \'b\'), (\'e\', \'f\'), (\'c\', \'d\'))))
True'
| def __repr__(self):
| return ('%s([%s])' % (self.__class__.__name__, ', '.join([('(%r, %r)' % (key, self[key])) for key in self._sequence])))
|
'Allows slice assignment, so long as the slice is an OrderedDict
>>> d = OrderedDict()
>>> d[\'a\'] = \'b\'
>>> d[\'b\'] = \'a\'
>>> d[3] = 12
>>> d
OrderedDict([(\'a\', \'b\'), (\'b\', \'a\'), (3, 12)])
>>> d[:] = OrderedDict(((1, 2), (2, 3), (3, 4)))
>>> d
OrderedDict([(1, 2), (2, 3), (3, 4)])
>>> d[::2] = OrderedDict(((7, 8), (9, 10)))
>>> d
OrderedDict([(7, 8), (2, 3), (9, 10)])
>>> d = OrderedDict(((0, 1), (1, 2), (2, 3), (3, 4)))
>>> d[1:3] = OrderedDict(((1, 2), (5, 6), (7, 8)))
>>> d
OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)])
>>> d = OrderedDict(((0, 1), (1, 2), (2, 3), (3, 4)), strict=True)
>>> d[1:3] = OrderedDict(((1, 2), (5, 6), (7, 8)))
>>> d
OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)])
>>> a = OrderedDict(((0, 1), (1, 2), (2, 3)), strict=True)
>>> a[3] = 4
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[::1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[:2] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)])
Traceback (most recent call last):
ValueError: slice assignment must be from unique keys
>>> a = OrderedDict(((0, 1), (1, 2), (2, 3)))
>>> a[3] = 4
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[::1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[:2] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a[::-1] = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> a
OrderedDict([(3, 4), (2, 3), (1, 2), (0, 1)])
>>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> d[:1] = 3
Traceback (most recent call last):
TypeError: slice assignment requires an OrderedDict
>>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)])
>>> d[:1] = OrderedDict([(9, 8)])
>>> d
OrderedDict([(9, 8), (1, 2), (2, 3), (3, 4)])'
| def __setitem__(self, key, val):
| if isinstance(key, types.SliceType):
if (not isinstance(val, OrderedDict)):
raise TypeError('slice assignment requires an OrderedDict')
keys = self._sequence[key]
indexes = range(len(self._sequence))[key]
if (key.step is None):
pos = (key.start or 0)
del self[key]
newkeys = val.keys()
for k in newkeys:
if (k in self):
if self.strict:
raise ValueError('slice assignment must be from unique keys')
else:
del self[k]
self._sequence = ((self._sequence[:pos] + newkeys) + self._sequence[pos:])
dict.update(self, val)
else:
if (len(keys) != len(val)):
raise ValueError(('attempt to assign sequence of size %s to extended slice of size %s' % (len(val), len(keys))))
del self[key]
item_list = zip(indexes, val.items())
item_list.sort()
for (pos, (newkey, newval)) in item_list:
if (self.strict and (newkey in self)):
raise ValueError('slice assignment must be from unique keys')
self.insert(pos, newkey, newval)
else:
if (key not in self):
self._sequence.append(key)
dict.__setitem__(self, key, val)
|
'Allows slicing. Returns an OrderedDict if you slice.
>>> b = OrderedDict([(7, 0), (6, 1), (5, 2), (4, 3), (3, 4), (2, 5), (1, 6)])
>>> b[::-1]
OrderedDict([(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1), (7, 0)])
>>> b[2:5]
OrderedDict([(5, 2), (4, 3), (3, 4)])
>>> type(b[2:4])
<class \'__main__.OrderedDict\'>'
| def __getitem__(self, key):
| if isinstance(key, types.SliceType):
keys = self._sequence[key]
return OrderedDict([(entry, self[entry]) for entry in keys])
else:
return dict.__getitem__(self, key)
|
'Implemented so that accesses to ``sequence`` raise a warning and are
diverted to the new ``setkeys`` method.'
| def __setattr__(self, name, value):
| if (name == 'sequence'):
warnings.warn('Use of the sequence attribute is deprecated. Use the keys method instead.', DeprecationWarning)
self.setkeys(value)
else:
object.__setattr__(self, name, value)
|
'Implemented so that access to ``sequence`` raises a warning.
>>> d = OrderedDict()
>>> d.sequence'
| def __getattr__(self, name):
| if (name == 'sequence'):
warnings.warn('Use of the sequence attribute is deprecated. Use the keys method instead.', DeprecationWarning)
return self._sequence
else:
raise AttributeError(("OrderedDict has no '%s' attribute" % name))
|
'To allow deepcopy to work with OrderedDict.
>>> from copy import deepcopy
>>> a = OrderedDict([(1, 1), (2, 2), (3, 3)])
>>> a[\'test\'] = {}
>>> b = deepcopy(a)
>>> b == a
True
>>> b is a
False
>>> a[\'test\'] is b[\'test\']
False'
| def __deepcopy__(self, memo):
| from copy import deepcopy
return self.__class__(deepcopy(self.items(), memo), self.strict)
|
'>>> OrderedDict(((1, 3), (3, 2), (2, 1))).copy()
OrderedDict([(1, 3), (3, 2), (2, 1)])'
| def copy(self):
| return OrderedDict(self)
|
'``items`` returns a list of tuples representing all the
``(key, value)`` pairs in the dictionary.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.items()
[(1, 3), (3, 2), (2, 1)]
>>> d.clear()
>>> d.items()'
| def items(self):
| return zip(self._sequence, self.values())
|
'Return a list of keys in the ``OrderedDict``.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.keys()
[1, 3, 2]'
| def keys(self):
| return self._sequence[:]
|
'Return a list of all the values in the OrderedDict.
Optionally you can pass in a list of values, which will replace the
current list. The value list must be the same len as the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.values()
[3, 2, 1]'
| def values(self, values=None):
| return [self[key] for key in self._sequence]
|
'>>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iteritems()
>>> ii.next()
(1, 3)
>>> ii.next()
(3, 2)
>>> ii.next()
(2, 1)
>>> ii.next()
Traceback (most recent call last):
StopIteration'
| def iteritems(self):
| def make_iter(self=self):
keys = self.iterkeys()
while True:
key = keys.next()
(yield (key, self[key]))
return make_iter()
|
'>>> ii = OrderedDict(((1, 3), (3, 2), (2, 1))).iterkeys()
>>> ii.next()
1
>>> ii.next()
3
>>> ii.next()
2
>>> ii.next()
Traceback (most recent call last):
StopIteration'
| def iterkeys(self):
| return iter(self._sequence)
|
'>>> iv = OrderedDict(((1, 3), (3, 2), (2, 1))).itervalues()
>>> iv.next()
3
>>> iv.next()
2
>>> iv.next()
1
>>> iv.next()
Traceback (most recent call last):
StopIteration'
| def itervalues(self):
| def make_iter(self=self):
keys = self.iterkeys()
while True:
(yield self[keys.next()])
return make_iter()
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.clear()
>>> d
OrderedDict([])'
| def clear(self):
| dict.clear(self)
self._sequence = []
|
'No dict.pop in Python 2.2, gotta reimplement it
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.pop(3)
2
>>> d
OrderedDict([(1, 3), (2, 1)])
>>> d.pop(4)
Traceback (most recent call last):
KeyError: 4
>>> d.pop(4, 0)
0
>>> d.pop(4, 0, 1)
Traceback (most recent call last):
TypeError: pop expected at most 2 arguments, got 3'
| def pop(self, key, *args):
| if (len(args) > 1):
raise TypeError, ('pop expected at most 2 arguments, got %s' % (len(args) + 1))
if (key in self):
val = self[key]
del self[key]
else:
try:
val = args[0]
except IndexError:
raise KeyError(key)
return val
|
'Delete and return an item specified by index, not a random one as in
dict. The index is -1 by default (the last item).
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.popitem()
(2, 1)
>>> d
OrderedDict([(1, 3), (3, 2)])
>>> d.popitem(0)
(1, 3)
>>> OrderedDict().popitem()
Traceback (most recent call last):
KeyError: \'popitem(): dictionary is empty\'
>>> d.popitem(2)
Traceback (most recent call last):
IndexError: popitem(): index 2 not valid'
| def popitem(self, i=(-1)):
| if (not self._sequence):
raise KeyError('popitem(): dictionary is empty')
try:
key = self._sequence[i]
except IndexError:
raise IndexError(('popitem(): index %s not valid' % i))
return (key, self.pop(key))
|
'>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.setdefault(1)
3
>>> d.setdefault(4) is None
True
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1), (4, None)])
>>> d.setdefault(5, 0)
0
>>> d
OrderedDict([(1, 3), (3, 2), (2, 1), (4, None), (5, 0)])'
| def setdefault(self, key, defval=None):
| if (key in self):
return self[key]
else:
self[key] = defval
return defval
|
'Update from another OrderedDict or sequence of (key, value) pairs
>>> d = OrderedDict(((1, 0), (0, 1)))
>>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1))))
>>> d
OrderedDict([(1, 3), (0, 1), (3, 2), (2, 1)])
>>> d.update({4: 4})
Traceback (most recent call last):
TypeError: undefined order, cannot get items from dict
>>> d.update((4, 4))
Traceback (most recent call last):
TypeError: cannot convert dictionary update sequence element "4" to a 2-item sequence'
| def update(self, from_od):
| if isinstance(from_od, OrderedDict):
for (key, val) in from_od.items():
self[key] = val
elif isinstance(from_od, dict):
raise TypeError('undefined order, cannot get items from dict')
else:
for item in from_od:
try:
(key, val) = item
except TypeError:
raise TypeError(('cannot convert dictionary update sequence element "%s" to a 2-item sequence' % item))
self[key] = val
|
'Rename the key for a given value, without modifying sequence order.
For the case where new_key already exists this raise an exception,
since if new_key exists, it is ambiguous as to what happens to the
associated values, and the position of new_key in the sequence.
>>> od = OrderedDict()
>>> od[\'a\'] = 1
>>> od[\'b\'] = 2
>>> od.items()
[(\'a\', 1), (\'b\', 2)]
>>> od.rename(\'b\', \'c\')
>>> od.items()
[(\'a\', 1), (\'c\', 2)]
>>> od.rename(\'c\', \'a\')
Traceback (most recent call last):
ValueError: New key already exists: \'a\'
>>> od.rename(\'d\', \'b\')
Traceback (most recent call last):
KeyError: \'d\''
| def rename(self, old_key, new_key):
| if (new_key == old_key):
return
if (new_key in self):
raise ValueError(('New key already exists: %r' % new_key))
value = self[old_key]
old_idx = self._sequence.index(old_key)
self._sequence[old_idx] = new_key
dict.__delitem__(self, old_key)
dict.__setitem__(self, new_key, value)
|
'This method allows you to set the items in the dict.
It takes a list of tuples - of the same sort returned by the ``items``
method.
>>> d = OrderedDict()
>>> d.setitems(((3, 1), (2, 3), (1, 2)))
>>> d
OrderedDict([(3, 1), (2, 3), (1, 2)])'
| def setitems(self, items):
| self.clear()
self.update(items)
|
'``setkeys`` all ows you to pass in a new list of keys which will
replace the current set. This must contain the same set of keys, but
need not be in the same order.
If you pass in new keys that don\'t match, a ``KeyError`` will be
raised.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.keys()
[1, 3, 2]
>>> d.setkeys((1, 2, 3))
>>> d
OrderedDict([(1, 3), (2, 1), (3, 2)])
>>> d.setkeys([\'a\', \'b\', \'c\'])
Traceback (most recent call last):
KeyError: \'Keylist is not the same as current keylist.\''
| def setkeys(self, keys):
| kcopy = list(keys)
kcopy.sort()
self._sequence.sort()
if (kcopy != self._sequence):
raise KeyError('Keylist is not the same as current keylist.')
self._sequence = list(keys)
|
'You can pass in a list of values, which will replace the
current list. The value list must be the same len as the OrderedDict.
(Or a ``ValueError`` is raised.)
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.setvalues((1, 2, 3))
>>> d
OrderedDict([(1, 1), (3, 2), (2, 3)])
>>> d.setvalues([6])
Traceback (most recent call last):
ValueError: Value list is not the same length as the OrderedDict.'
| def setvalues(self, values):
| if (len(values) != len(self)):
raise ValueError('Value list is not the same length as the OrderedDict.')
self.update(zip(self, values))
|
'Return the position of the specified key in the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.index(3)
1
>>> d.index(4)
Traceback (most recent call last):
ValueError: list.index(x): x not in list'
| def index(self, key):
| return self._sequence.index(key)
|
'Takes ``index``, ``key``, and ``value`` as arguments.
Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in
the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.insert(0, 4, 0)
>>> d
OrderedDict([(4, 0), (1, 3), (3, 2), (2, 1)])
>>> d.insert(0, 2, 1)
>>> d
OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2)])
>>> d.insert(8, 8, 1)
>>> d
OrderedDict([(2, 1), (4, 0), (1, 3), (3, 2), (8, 1)])'
| def insert(self, index, key, value):
| if (key in self):
del self[key]
self._sequence.insert(index, key)
dict.__setitem__(self, key, value)
|
'Reverse the order of the OrderedDict.
>>> d = OrderedDict(((1, 3), (3, 2), (2, 1)))
>>> d.reverse()
>>> d
OrderedDict([(2, 1), (3, 2), (1, 3)])'
| def reverse(self):
| self._sequence.reverse()
|
'Sort the key order in the OrderedDict.
This method takes the same arguments as the ``list.sort`` method on
your version of Python.
>>> d = OrderedDict(((4, 1), (2, 2), (3, 3), (1, 4)))
>>> d.sort()
>>> d
OrderedDict([(1, 4), (2, 2), (3, 3), (4, 1)])'
| def sort(self, *args, **kwargs):
| self._sequence.sort(*args, **kwargs)
|
'Pretend to be the keys method.'
| def __call__(self):
| return self._main._keys()
|
'Fetch the key at position i.'
| def __getitem__(self, index):
| return self._main._sequence[index]
|
'You cannot assign to keys, but you can do slice assignment to re-order
them.
You can only do slice assignment if the new set of keys is a reordering
of the original set.'
| def __setitem__(self, index, name):
| if isinstance(index, types.SliceType):
indexes = range(len(self._main._sequence))[index]
if (len(indexes) != len(name)):
raise ValueError(('attempt to assign sequence of size %s to slice of size %s' % (len(name), len(indexes))))
old_keys = self._main._sequence[index]
new_keys = list(name)
old_keys.sort()
new_keys.sort()
if (old_keys != new_keys):
raise KeyError('Keylist is not the same as current keylist.')
orig_vals = [self._main[k] for k in name]
del self._main[index]
vals = zip(indexes, name, orig_vals)
vals.sort()
for (i, k, v) in vals:
if (self._main.strict and (k in self._main)):
raise ValueError('slice assignment must be from unique keys')
self._main.insert(i, k, v)
else:
raise ValueError('Cannot assign to keys')
|
'Pretend to be the items method.'
| def __call__(self):
| return self._main._items()
|
'Fetch the item at position i.'
| def __getitem__(self, index):
| if isinstance(index, types.SliceType):
return self._main[index].items()
key = self._main._sequence[index]
return (key, self._main[key])
|
'Set item at position i to item.'
| def __setitem__(self, index, item):
| if isinstance(index, types.SliceType):
self._main[index] = OrderedDict(item)
else:
orig = self._main.keys[index]
(key, value) = item
if (self._main.strict and (key in self) and (key != orig)):
raise ValueError('slice assignment must be from unique keys')
del self._main[self._main._sequence[index]]
self._main.insert(index, key, value)
|
'Delete the item at position i.'
| def __delitem__(self, i):
| key = self._main._sequence[i]
if isinstance(i, types.SliceType):
for k in key:
del self._main[k]
else:
del self._main[key]
|
'Add an item to the end.'
| def append(self, item):
| (key, value) = item
self._main[key] = value
|
'Pretend to be the values method.'
| def __call__(self):
| return self._main._values()
|
'Fetch the value at position i.'
| def __getitem__(self, index):
| if isinstance(index, types.SliceType):
return [self._main[key] for key in self._main._sequence[index]]
else:
return self._main[self._main._sequence[index]]
|
'Set the value at position i to value.
You can only do slice assignment to values if you supply a sequence of
equal length to the slice you are replacing.'
| def __setitem__(self, index, value):
| if isinstance(index, types.SliceType):
keys = self._main._sequence[index]
if (len(keys) != len(value)):
raise ValueError(('attempt to assign sequence of size %s to slice of size %s' % (len(name), len(keys))))
for (key, val) in zip(keys, value):
self._main[key] = val
else:
self._main[self._main._sequence[index]] = value
|
'Reverse the values'
| def reverse(self):
| vals = self._main.values()
vals.reverse()
self[:] = vals
|
'Sort the values.'
| def sort(self, *args, **kwds):
| vals = self._main.values()
vals.sort(*args, **kwds)
self[:] = vals
|