index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
5,175
docutils.nodes
__add__
null
def __add__(self, other): return self.children + other
(self, other)
5,176
docutils.nodes
__bool__
Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length.
def __bool__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. """ return True
(self)
5,177
docutils.nodes
__contains__
null
def __contains__(self, key): # Test for both, children and attributes with operator ``in``. if isinstance(key, str): return key in self.attributes return key in self.children
(self, key)
5,178
docutils.nodes
__delitem__
null
def __delitem__(self, key): if isinstance(key, str): del self.attributes[key] elif isinstance(key, int): del self.children[key] elif isinstance(key, slice): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError('element index must be an integer, a simple ' 'slice, or an attribute name string')
(self, key)
5,179
releases.models
__eq__
null
def __eq__(self, other): for attr in self._cmp_keys: if getattr(self, attr, None) != getattr(other, attr, None): return False return True
(self, other)
5,180
docutils.nodes
__getitem__
null
def __getitem__(self, key): if isinstance(key, str): return self.attributes[key] elif isinstance(key, int): return self.children[key] elif isinstance(key, slice): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError('element index must be an integer, a slice, or ' 'an attribute name string')
(self, key)
5,181
releases.models
__hash__
null
def __hash__(self): return reduce(xor, [hash(getattr(self, x)) for x in self._cmp_keys])
(self)
5,182
docutils.nodes
__iadd__
Append a node or a list of nodes to `self.children`.
def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self
(self, other)
5,183
docutils.nodes
__init__
null
def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed. NOTE: some elements do not set this value (default ''). """ self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__
(self, rawsource='', *children, **attributes)
5,184
docutils.nodes
__len__
null
def __len__(self): return len(self.children)
(self)
5,185
docutils.nodes
__radd__
null
def __radd__(self, other): return other + self.children
(self, other)
5,186
releases.models
__repr__
null
def __repr__(self): flag = "" if self.backported: flag = "backported" elif self.major: flag = "major" elif self.spec: flag = self.spec if flag: flag = " ({})".format(flag) return "<{issue.type} #{issue.number}{flag}>".format( issue=self, flag=flag )
(self)
5,187
docutils.nodes
__setitem__
null
def __setitem__(self, key, item): if isinstance(key, str): self.attributes[str(key)] = item elif isinstance(key, int): self.setup_child(item) self.children[key] = item elif isinstance(key, slice): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError('element index must be an integer, a slice, or ' 'an attribute name string')
(self, key, item)
5,188
docutils.nodes
__str__
null
def __str__(self): if self.children: return '%s%s%s' % (self.starttag(), ''.join(str(c) for c in self.children), self.endtag()) else: return self.emptytag()
(self)
5,189
docutils.nodes
_dom_node
null
def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, list): value = ' '.join(serial_escape('%s' % (v,)) for v in value) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element
(self, domroot)
5,190
docutils.nodes
_fast_findall
Return iterator that only supports instance checks.
def _fast_findall(self, cls): """Return iterator that only supports instance checks.""" if isinstance(self, cls): yield self for child in self.children: yield from child._fast_findall(cls)
(self, cls)
5,191
docutils.nodes
_superfast_findall
Return iterator that doesn't check for a condition.
def _superfast_findall(self): """Return iterator that doesn't check for a condition.""" # This is different from ``iter(self)`` implemented via # __getitem__() and __len__() in the Element subclass, # which yields only the direct children. yield self for child in self.children: yield from child._superfast_findall()
(self)
5,192
releases.models
add_to_manager
Given a 'manager' structure, add self to one or more of its 'buckets'.
def add_to_manager(self, manager): """ Given a 'manager' structure, add self to one or more of its 'buckets'. """ # Derive version spec allowing us to filter against major/minor buckets spec = self.spec or self.default_spec(manager) # Only look in appropriate major version/family; if self is an issue # declared as living in e.g. >=2, this means we don't even bother # looking in the 1.x family. families = [Version(str(x)) for x in manager] versions = list(spec.filter(families)) for version in versions: family = version.major # Within each family, we further limit which bugfix lines match up # to what self cares about (ignoring 'unreleased' until later) candidates = [ Version(x) for x in manager[family] if not x.startswith("unreleased") ] # Select matching release lines (& stringify) buckets = [] bugfix_buckets = [str(x) for x in spec.filter(candidates)] # Add back in unreleased_* as appropriate # TODO: probably leverage Issue subclasses for this eventually? if self.is_buglike: buckets.extend(bugfix_buckets) # Don't put into JUST unreleased_bugfix; it implies that this # major release/family hasn't actually seen any releases yet # and only exists for features to go into. if bugfix_buckets: buckets.append("unreleased_bugfix") # Obtain list of minor releases to check for "haven't had ANY # releases yet" corner case, in which case ALL issues get thrown in # unreleased_feature for the first release to consume. # NOTE: assumes first release is a minor or major one, # but...really? why would your first release be a bugfix one?? no_releases = not self.minor_releases(manager) if self.is_featurelike or self.backported or no_releases: buckets.append("unreleased_feature") # Now that we know which buckets are appropriate, add ourself to # all of them. TODO: or just...do it above...instead... for bucket in buckets: manager[family][bucket].append(self)
(self, manager)
5,193
docutils.nodes
append
null
def append(self, item): self.setup_child(item) self.children.append(item)
(self, item)
5,194
docutils.nodes
append_attr_list
For each element in values, if it does not exist in self[attr], append it. NOTE: Requires self[attr] and values to be sequence type and the former should specifically be a list.
def append_attr_list(self, attr, values): """ For each element in values, if it does not exist in self[attr], append it. NOTE: Requires self[attr] and values to be sequence type and the former should specifically be a list. """ # List Concatenation for value in values: if value not in self[attr]: self[attr].append(value)
(self, attr, values)
5,195
docutils.nodes
asdom
Return a DOM **fragment** representation of this Node.
def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot)
(self, dom=None)
5,196
docutils.nodes
astext
null
def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children])
(self)
5,197
docutils.nodes
attlist
null
def attlist(self): return sorted(self.non_default_attributes().items())
(self)
5,198
docutils.nodes
clear
null
def clear(self): self.children = []
(self)
5,199
docutils.nodes
coerce_append_attr_list
First, convert both self[attr] and value to a non-string sequence type; if either is not already a sequence, convert it to a list of one element. Then call append_attr_list. NOTE: self[attr] and value both must not be None.
def coerce_append_attr_list(self, attr, value): """ First, convert both self[attr] and value to a non-string sequence type; if either is not already a sequence, convert it to a list of one element. Then call append_attr_list. NOTE: self[attr] and value both must not be None. """ # List Concatenation if not isinstance(self.get(attr), list): self[attr] = [self[attr]] if not isinstance(value, list): value = [value] self.append_attr_list(attr, value)
(self, attr, value)
5,200
docutils.nodes
copy
null
def copy(self): obj = self.__class__(rawsource=self.rawsource, **self.attributes) obj._document = self._document obj.source = self.source obj.line = self.line return obj
(self)
5,201
docutils.nodes
copy_attr_coerce
If attr is an attribute of self and either self[attr] or value is a list, convert all non-sequence values to a sequence of 1 element and then concatenate the two sequence, setting the result to self[attr]. If both self[attr] and value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing.
def copy_attr_coerce(self, attr, value, replace): """ If attr is an attribute of self and either self[attr] or value is a list, convert all non-sequence values to a sequence of 1 element and then concatenate the two sequence, setting the result to self[attr]. If both self[attr] and value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing. """ if self.get(attr) is not value: if isinstance(self.get(attr), list) or \ isinstance(value, list): self.coerce_append_attr_list(attr, value) else: self.replace_attr(attr, value, replace)
(self, attr, value, replace)
5,202
docutils.nodes
copy_attr_concatenate
If attr is an attribute of self and both self[attr] and value are lists, concatenate the two sequences, setting the result to self[attr]. If either self[attr] or value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing.
def copy_attr_concatenate(self, attr, value, replace): """ If attr is an attribute of self and both self[attr] and value are lists, concatenate the two sequences, setting the result to self[attr]. If either self[attr] or value are non-sequences and replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing. """ if self.get(attr) is not value: if isinstance(self.get(attr), list) and \ isinstance(value, list): self.append_attr_list(attr, value) else: self.replace_attr(attr, value, replace)
(self, attr, value, replace)
5,203
docutils.nodes
copy_attr_consistent
If replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing.
def copy_attr_consistent(self, attr, value, replace): """ If replace is True or self[attr] is None, replace self[attr] with value. Otherwise, do nothing. """ if self.get(attr) is not value: self.replace_attr(attr, value, replace)
(self, attr, value, replace)
5,204
docutils.nodes
copy_attr_convert
If attr is an attribute of self, set self[attr] to [self[attr], value], otherwise set self[attr] to value. NOTE: replace is not used by this function and is kept only for compatibility with the other copy functions.
def copy_attr_convert(self, attr, value, replace=True): """ If attr is an attribute of self, set self[attr] to [self[attr], value], otherwise set self[attr] to value. NOTE: replace is not used by this function and is kept only for compatibility with the other copy functions. """ if self.get(attr) is not value: self.coerce_append_attr_list(attr, value)
(self, attr, value, replace=True)
5,205
docutils.nodes
deepcopy
null
def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy
(self)
5,206
releases.models
default_spec
Given the current release-lines structure, return a default Spec. Specifics: * For feature-like issues, only the highest major release is used, so given a ``manager`` with top level keys of ``[1, 2]``, this would return ``Spec(">=2")``. * When ``releases_always_forwardport_features`` is ``True``, that behavior is nullified, and this function always returns the empty ``Spec`` (which matches any and all versions/lines). * For bugfix-like issues, we only consider major release families which have actual releases already. * Thus the core difference here is that features are 'consumed' by upcoming major releases, and bugfixes are not. * When the ``unstable_prehistory`` setting is ``True``, the default spec starts at the oldest non-zero release line. (Otherwise, issues posted after prehistory ends would try being added to the 0.x part of the tree, which makes no sense in unstable-prehistory mode.)
def default_spec(self, manager): """ Given the current release-lines structure, return a default Spec. Specifics: * For feature-like issues, only the highest major release is used, so given a ``manager`` with top level keys of ``[1, 2]``, this would return ``Spec(">=2")``. * When ``releases_always_forwardport_features`` is ``True``, that behavior is nullified, and this function always returns the empty ``Spec`` (which matches any and all versions/lines). * For bugfix-like issues, we only consider major release families which have actual releases already. * Thus the core difference here is that features are 'consumed' by upcoming major releases, and bugfixes are not. * When the ``unstable_prehistory`` setting is ``True``, the default spec starts at the oldest non-zero release line. (Otherwise, issues posted after prehistory ends would try being added to the 0.x part of the tree, which makes no sense in unstable-prehistory mode.) """ # TODO: I feel like this + the surrounding bits in add_to_manager() # could be consolidated & simplified... specstr = "" # Make sure truly-default spec skips 0.x if prehistory was unstable. stable_families = manager.stable_families if manager.config.releases_unstable_prehistory and stable_families: specstr = ">={}".format(min(stable_families)) if self.is_featurelike: # TODO: if app->config-><releases_always_forwardport_features or # w/e if True: specstr = ">={}".format(max(manager.keys())) else: # Can only meaningfully limit to minor release buckets if they # actually exist yet. buckets = self.minor_releases(manager) if buckets: specstr = ">={}".format(max(buckets)) return Spec(specstr) if specstr else Spec()
(self, manager)
5,207
docutils.nodes
delattr
null
def delattr(self, attr): if attr in self.attributes: del self.attributes[attr]
(self, attr)
5,208
docutils.nodes
emptytag
null
def emptytag(self): attributes = ('%s="%s"' % (n, v) for n, v in self.attlist()) return '<%s/>' % ' '.join((self.tagname, *attributes))
(self)
5,209
docutils.nodes
endtag
null
def endtag(self): return '</%s>' % self.tagname
(self)
5,210
docutils.nodes
extend
null
def extend(self, item): for node in item: self.append(node)
(self, item)
5,211
docutils.nodes
findall
Return an iterator yielding nodes following `self`: * self (if `include_self` is true) * all descendants in tree traversal order (if `descend` is true) * the following siblings (if `siblings` is true) and their descendants (if also `descend` is true) * the following siblings of the parent (if `ascend` is true) and their descendants (if also `descend` is true), and so on. If `condition` is not None, the iterator yields only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If `ascend` is true, assume `siblings` to be true as well. If the tree structure is modified during iteration, the result is undefined. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then tuple(emphasis.traverse()) equals :: (<emphasis>, <strong>, <#text: Foo>, <#text: Bar>) and list(strong.traverse(ascend=True) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>]
def findall(self, condition=None, include_self=True, descend=True, siblings=False, ascend=False): """ Return an iterator yielding nodes following `self`: * self (if `include_self` is true) * all descendants in tree traversal order (if `descend` is true) * the following siblings (if `siblings` is true) and their descendants (if also `descend` is true) * the following siblings of the parent (if `ascend` is true) and their descendants (if also `descend` is true), and so on. If `condition` is not None, the iterator yields only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If `ascend` is true, assume `siblings` to be true as well. If the tree structure is modified during iteration, the result is undefined. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then tuple(emphasis.traverse()) equals :: (<emphasis>, <strong>, <#text: Foo>, <#text: Bar>) and list(strong.traverse(ascend=True) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ if ascend: siblings = True # Check for special argument combinations that allow using an # optimized version of traverse() if include_self and descend and not siblings: if condition is None: yield from self._superfast_findall() return elif isinstance(condition, type): yield from self._fast_findall(condition) return # Check if `condition` is a class (check for TypeType for Python # implementations that use only new-style classes, like PyPy). if isinstance(condition, type): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) if include_self and (condition is None or condition(self)): yield self if descend and len(self.children): for child in self: yield from child.findall(condition=condition, include_self=True, descend=True, siblings=False, ascend=False) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) # extra check since Text nodes have value-equality while node.parent[index] is not node: index = node.parent.index(node, index + 1) for sibling in node.parent[index+1:]: yield from sibling.findall( condition=condition, include_self=True, descend=descend, siblings=False, ascend=False) if not ascend: break else: node = node.parent
(self, condition=None, include_self=True, descend=True, siblings=False, ascend=False)
5,212
docutils.nodes
first_child_matching_class
Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check.
def first_child_matching_class(self, childclass, start=0, end=sys.maxsize): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None
(self, childclass, start=0, end=9223372036854775807)
5,213
docutils.nodes
first_child_not_matching_class
Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check.
def first_child_not_matching_class(self, childclass, start=0, end=sys.maxsize): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, tuple): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None
(self, childclass, start=0, end=9223372036854775807)
5,214
docutils.nodes
get
null
def get(self, key, failobj=None): return self.attributes.get(key, failobj)
(self, key, failobj=None)
5,215
docutils.nodes
get_language_code
Return node's language tag. Look iteratively in self and parents for a class argument starting with ``language-`` and return the remainder of it (which should be a `BCP49` language tag) or the `fallback`.
def get_language_code(self, fallback=''): """Return node's language tag. Look iteratively in self and parents for a class argument starting with ``language-`` and return the remainder of it (which should be a `BCP49` language tag) or the `fallback`. """ for cls in self.get('classes', []): if cls.startswith('language-'): return cls[9:] try: return self.parent.get_language(fallback) except AttributeError: return fallback
(self, fallback='')
5,216
docutils.nodes
hasattr
null
def hasattr(self, attr): return attr in self.attributes
(self, attr)
5,218
docutils.nodes
index
null
def index(self, item, start=0, stop=sys.maxsize): return self.children.index(item, start, stop)
(self, item, start=0, stop=9223372036854775807)
5,219
docutils.nodes
insert
null
def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item
(self, index, item)
5,220
docutils.nodes
is_not_default
null
def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1
(self, key)
5,221
releases.models
minor_releases
Return all minor release line labels found in ``manager``.
def minor_releases(self, manager): """ Return all minor release line labels found in ``manager``. """ # TODO: yea deffo need a real object for 'manager', heh. E.g. we do a # very similar test for "do you have any actual releases yet?" # elsewhere. (This may be fodder for changing how we roll up # pre-major-release features though...?) return [ key for key, value in manager.items() if any(x for x in value if not x.startswith("unreleased")) ]
(self, manager)
5,222
docutils.nodes
next_node
Return the first node in the iterator returned by findall(), or None if the iterable is empty. Parameter list is the same as of `findall()`. Note that `include_self` defaults to False, though.
def next_node(self, condition=None, include_self=False, descend=True, siblings=False, ascend=False): """ Return the first node in the iterator returned by findall(), or None if the iterable is empty. Parameter list is the same as of `findall()`. Note that `include_self` defaults to False, though. """ try: return next(self.findall(condition, include_self, descend, siblings, ascend)) except StopIteration: return None
(self, condition=None, include_self=False, descend=True, siblings=False, ascend=False)
5,223
docutils.nodes
non_default_attributes
null
def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts
(self)
5,224
docutils.nodes
note_referenced_by
Note that this Element has been referenced by its name `name` or id `id`.
def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = True # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = True if by_id: assert id is not None by_id.referenced = True
(self, name=None, id=None)
5,225
docutils.nodes
pformat
null
def pformat(self, indent=' ', level=0): tagline = '%s%s\n' % (indent*level, self.starttag()) childreps = (c.pformat(indent, level+1) for c in self.children) return ''.join((tagline, *childreps))
(self, indent=' ', level=0)
5,226
docutils.nodes
pop
null
def pop(self, i=-1): return self.children.pop(i)
(self, i=-1)
5,227
docutils.nodes
previous_sibling
Return preceding sibling node or ``None``.
def previous_sibling(self): """Return preceding sibling node or ``None``.""" try: i = self.parent.index(self) except (AttributeError): return None return self.parent[i-1] if i > 0 else None
(self)
5,228
docutils.nodes
remove
null
def remove(self, item): self.children.remove(item)
(self, item)
5,229
docutils.nodes
replace
Replace one child `Node` with another child or children.
def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new
(self, old, new)
5,230
docutils.nodes
replace_attr
If self[attr] does not exist or force is True or omitted, set self[attr] to value, otherwise do nothing.
def replace_attr(self, attr, value, force=True): """ If self[attr] does not exist or force is True or omitted, set self[attr] to value, otherwise do nothing. """ # One or the other if force or self.get(attr) is None: self[attr] = value
(self, attr, value, force=True)
5,231
docutils.nodes
replace_self
Replace `self` node with `new`, where `new` is a node or a list of nodes.
def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in self.basic_attributes: assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new)
(self, new)
5,232
docutils.nodes
set_class
Add a new class to the "classes" attribute.
def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class() is deprecated; ' ' and will be removed in Docutils 0.21 or later.' "Append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower())
(self, name)
5,233
docutils.nodes
setdefault
null
def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj)
(self, key, failobj=None)
5,234
docutils.nodes
setup_child
null
def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line
(self, child)
5,235
docutils.nodes
shortrepr
null
def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname
(self)
5,236
docutils.nodes
starttag
null
def starttag(self, quoteattr=None): # the optional arg is used by the docutils_xml writer if quoteattr is None: quoteattr = pseudo_quoteattr parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append('%s="True"' % name) continue if isinstance(value, list): values = [serial_escape('%s' % (v,)) for v in value] value = ' '.join(values) else: value = str(value) value = quoteattr(value) parts.append('%s=%s' % (name, value)) return '<%s>' % ' '.join(parts)
(self, quoteattr=None)
5,237
docutils.nodes
traverse
Return list of nodes following `self`. For looping, Node.findall() is faster and more memory efficient.
def traverse(self, condition=None, include_self=True, descend=True, siblings=False, ascend=False): """Return list of nodes following `self`. For looping, Node.findall() is faster and more memory efficient. """ # traverse() may be eventually removed: warnings.warn('nodes.Node.traverse() is obsoleted by Node.findall().', PendingDeprecationWarning, stacklevel=2) return list(self.findall(condition, include_self, descend, siblings, ascend))
(self, condition=None, include_self=True, descend=True, siblings=False, ascend=False)
5,238
docutils.nodes
update_all_atts
Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_, the two values are merged based on the value of update_fun. Generally, when replace is True, the values in self are replaced or merged with the values in dict_; otherwise, the values in self may be preserved or merged. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun. NOTE: It is easier to call the update-specific methods then to pass the update_fun method to this function.
def update_all_atts(self, dict_, update_fun=copy_attr_consistent, replace=True, and_source=False): """ Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_, the two values are merged based on the value of update_fun. Generally, when replace is True, the values in self are replaced or merged with the values in dict_; otherwise, the values in self may be preserved or merged. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun. NOTE: It is easier to call the update-specific methods then to pass the update_fun method to this function. """ if isinstance(dict_, Node): dict_ = dict_.attributes # Include the source attribute when copying? if and_source: filter_fun = self.is_not_list_attribute else: filter_fun = self.is_not_known_attribute # Copy the basic attributes self.update_basic_atts(dict_) # Grab other attributes in dict_ not in self except the # (All basic attributes should be copied already) for att in filter(filter_fun, dict_): update_fun(self, att, dict_[att], replace)
(self, dict_, update_fun=<function Element.copy_attr_consistent at 0x7fc41c59f760>, replace=True, and_source=False)
5,239
docutils.nodes
update_all_atts_coercion
Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ whose values are both not lists and replace is True, the values in self are replaced with the values in dict_; if either of the values from self and dict_ for the given identifier are of list type, then first any non-lists are converted to 1-element lists and then the two lists are concatenated and the result stored in self; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun.
def update_all_atts_coercion(self, dict_, replace=True, and_source=False): """ Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ whose values are both not lists and replace is True, the values in self are replaced with the values in dict_; if either of the values from self and dict_ for the given identifier are of list type, then first any non-lists are converted to 1-element lists and then the two lists are concatenated and the result stored in self; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun. """ self.update_all_atts(dict_, Element.copy_attr_coerce, replace, and_source)
(self, dict_, replace=True, and_source=False)
5,240
docutils.nodes
update_all_atts_concatenating
Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ whose values aren't each lists and replace is True, the values in self are replaced with the values in dict_; if the values from self and dict_ for the given identifier are both of list type, then the two lists are concatenated and the result stored in self; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun.
def update_all_atts_concatenating(self, dict_, replace=True, and_source=False): """ Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ whose values aren't each lists and replace is True, the values in self are replaced with the values in dict_; if the values from self and dict_ for the given identifier are both of list type, then the two lists are concatenated and the result stored in self; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun. """ self.update_all_atts(dict_, Element.copy_attr_concatenate, replace, and_source)
(self, dict_, replace=True, and_source=False)
5,241
docutils.nodes
update_all_atts_consistantly
Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ and replace is True, the values in self are replaced with the values in dict_; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun.
def update_all_atts_consistantly(self, dict_, replace=True, and_source=False): """ Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ and replace is True, the values in self are replaced with the values in dict_; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun. """ self.update_all_atts(dict_, Element.copy_attr_consistent, replace, and_source)
(self, dict_, replace=True, and_source=False)
5,242
docutils.nodes
update_all_atts_convert
Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ then first any non-lists are converted to 1-element lists and then the two lists are concatenated and the result stored in self; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun.
def update_all_atts_convert(self, dict_, and_source=False): """ Updates all attributes from node or dictionary `dict_`. Appends the basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') and then, for all other attributes in dict_, updates the same attribute in self. When attributes with the same identifier appear in both self and dict_ then first any non-lists are converted to 1-element lists and then the two lists are concatenated and the result stored in self; otherwise, the values in self are preserved. When and_source is True, the 'source' attribute is included in the copy. NOTE: When replace is False, and self contains a 'source' attribute, 'source' is not replaced even when dict_ has a 'source' attribute, though it may still be merged into a list depending on the value of update_fun. """ self.update_all_atts(dict_, Element.copy_attr_convert, and_source=and_source)
(self, dict_, and_source=False)
5,243
docutils.nodes
update_basic_atts
Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict_`.
def update_basic_atts(self, dict_): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict_`. """ if isinstance(dict_, Node): dict_ = dict_.attributes for att in self.basic_attributes: self.append_attr_list(att, dict_.get(att, []))
(self, dict_)
5,244
docutils.nodes
walk
Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal.
def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ stop = False visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return stop except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: if child.walk(visitor): stop = True break except SkipSiblings: pass except StopTraversal: stop = True return stop
(self, visitor)
5,245
docutils.nodes
walkabout
Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal.
def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. Return true if we should stop the traversal. """ call_depart = True stop = False visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return stop except SkipDeparture: call_depart = False children = self.children try: for child in children[:]: if child.walkabout(visitor): stop = True break except SkipSiblings: pass except SkipChildren: pass except StopTraversal: stop = True if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) return stop
(self, visitor)
5,246
releases.line_manager
LineManager
Manages multiple release lines/families as well as related config state.
class LineManager(dict): """ Manages multiple release lines/families as well as related config state. """ def __init__(self, app): """ Initialize new line manager dict. :param app: The core Sphinx app object. Mostly used for config. """ super().__init__() self.app = app @property def config(self): """ Return Sphinx config object. """ return self.app.config def add_family(self, major_number): """ Expand to a new release line with given ``major_number``. This will flesh out mandatory buckets like ``unreleased_bugfix`` and do other necessary bookkeeping. """ # Normally, we have separate buckets for bugfixes vs features keys = ["unreleased_bugfix", "unreleased_feature"] # But unstable prehistorical releases roll all up into just # 'unreleased' if major_number == 0 and self.config.releases_unstable_prehistory: keys = ["unreleased"] # Either way, the buckets default to an empty list self[major_number] = {key: [] for key in keys} @property def unstable_prehistory(self): """ Returns True if 'unstable prehistory' behavior should be applied. Specifically, checks config & whether any non-0.x releases exist. """ return ( self.config.releases_unstable_prehistory and not self.has_stable_releases ) @property def stable_families(self): """ Returns release family numbers which aren't 0 (i.e. prehistory). """ return [x for x in self if x != 0] @property def has_stable_releases(self): """ Returns whether stable (post-0.x) releases seem to exist. """ nonzeroes = self.stable_families # Nothing but 0.x releases -> yup we're prehistory if not nonzeroes: return False # Presumably, if there's >1 major family besides 0.x, we're at least # one release into the 1.0 (or w/e) line. if len(nonzeroes) > 1: return True # If there's only one, we may still be in the space before its N.0.0 as # well; we can check by testing for existence of bugfix buckets return any( x for x in self[nonzeroes[0]] if not x.startswith("unreleased") )
(app)
5,247
releases.line_manager
__init__
Initialize new line manager dict. :param app: The core Sphinx app object. Mostly used for config.
def __init__(self, app): """ Initialize new line manager dict. :param app: The core Sphinx app object. Mostly used for config. """ super().__init__() self.app = app
(self, app)
5,248
releases.line_manager
add_family
Expand to a new release line with given ``major_number``. This will flesh out mandatory buckets like ``unreleased_bugfix`` and do other necessary bookkeeping.
def add_family(self, major_number): """ Expand to a new release line with given ``major_number``. This will flesh out mandatory buckets like ``unreleased_bugfix`` and do other necessary bookkeeping. """ # Normally, we have separate buckets for bugfixes vs features keys = ["unreleased_bugfix", "unreleased_feature"] # But unstable prehistorical releases roll all up into just # 'unreleased' if major_number == 0 and self.config.releases_unstable_prehistory: keys = ["unreleased"] # Either way, the buckets default to an empty list self[major_number] = {key: [] for key in keys}
(self, major_number)
5,249
releases.models
Release
null
class Release(nodes.Element): @property def number(self): return self["number"] @property def minor(self): # TODO: use Version return ".".join(self.number.split(".")[:-1]) @property def family(self): # TODO: use Version.major # TODO: and probs just rename to .major, 'family' is dumb tbh return int(self.number.split(".")[0]) def __repr__(self): return "<release {}>".format(self.number)
(rawsource='', *children, **attributes)
5,259
releases.models
__repr__
null
def __repr__(self): return "<release {}>".format(self.number)
(self)
5,316
semantic_version.base
Spec
null
class Spec(object): def __init__(self, *specs_strings): subspecs = [self.parse(spec) for spec in specs_strings] self.specs = sum(subspecs, ()) @classmethod def parse(self, specs_string): spec_texts = specs_string.split(',') return tuple(SpecItem(spec_text) for spec_text in spec_texts) def match(self, version): """Check whether a Version satisfies the Spec.""" return all(spec.match(version) for spec in self.specs) def filter(self, versions): """Filter an iterable of versions satisfying the Spec.""" for version in versions: if self.match(version): yield version def select(self, versions): """Select the best compatible version among an iterable of options.""" options = list(self.filter(versions)) if options: return max(options) return None def __contains__(self, version): if isinstance(version, Version): return self.match(version) return False def __iter__(self): return iter(self.specs) def __str__(self): return ','.join(str(spec) for spec in self.specs) def __repr__(self): return '<Spec: %r>' % (self.specs,) def __eq__(self, other): if not isinstance(other, Spec): return NotImplemented return set(self.specs) == set(other.specs) def __hash__(self): return hash(self.specs)
(*specs_strings)
5,317
semantic_version.base
__contains__
null
def __contains__(self, version): if isinstance(version, Version): return self.match(version) return False
(self, version)
5,318
semantic_version.base
__eq__
null
def __eq__(self, other): if not isinstance(other, Spec): return NotImplemented return set(self.specs) == set(other.specs)
(self, other)
5,319
semantic_version.base
__hash__
null
def __hash__(self): return hash(self.specs)
(self)
5,320
semantic_version.base
__init__
null
def __init__(self, *specs_strings): subspecs = [self.parse(spec) for spec in specs_strings] self.specs = sum(subspecs, ())
(self, *specs_strings)
5,321
semantic_version.base
__iter__
null
def __iter__(self): return iter(self.specs)
(self)
5,322
semantic_version.base
__repr__
null
def __repr__(self): return '<Spec: %r>' % (self.specs,)
(self)
5,323
semantic_version.base
__str__
null
def __str__(self): return ','.join(str(spec) for spec in self.specs)
(self)
5,324
semantic_version.base
filter
Filter an iterable of versions satisfying the Spec.
def filter(self, versions): """Filter an iterable of versions satisfying the Spec.""" for version in versions: if self.match(version): yield version
(self, versions)
5,325
semantic_version.base
match
Check whether a Version satisfies the Spec.
def match(self, version): """Check whether a Version satisfies the Spec.""" return all(spec.match(version) for spec in self.specs)
(self, version)
5,326
semantic_version.base
select
Select the best compatible version among an iterable of options.
def select(self, versions): """Select the best compatible version among an iterable of options.""" options = list(self.filter(versions)) if options: return max(options) return None
(self, versions)
5,327
releases.models
Version
Version subclass toggling ``partial=True`` by default.
class Version(StrictVersion): """ Version subclass toggling ``partial=True`` by default. """ def __init__(self, version_string, partial=True): super().__init__(version_string, partial)
(version_string, partial=True)
5,328
semantic_version.base
__compare
null
def __compare(self, other): comparison_functions = self._comparison_functions(partial=self.partial or other.partial) comparisons = zip(comparison_functions, self, other) for cmp_fun, self_field, other_field in comparisons: cmp_res = cmp_fun(self_field, other_field) if cmp_res != 0: return cmp_res return 0
(self, other)
5,329
semantic_version.base
__compare_helper
Helper for comparison. Allows the caller to provide: - The condition - The return value if the comparison is meaningless (ie versions with build metadata).
def __compare_helper(self, other, condition, notimpl_target): """Helper for comparison. Allows the caller to provide: - The condition - The return value if the comparison is meaningless (ie versions with build metadata). """ if not isinstance(other, self.__class__): return NotImplemented cmp_res = self.__cmp__(other) if cmp_res is NotImplemented: return notimpl_target return condition(cmp_res)
(self, other, condition, notimpl_target)
5,330
semantic_version.base
__cmp__
null
def __cmp__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.__compare(other)
(self, other)
5,331
semantic_version.base
__eq__
null
def __eq__(self, other): return self.__compare_helper(other, lambda x: x == 0, notimpl_target=False)
(self, other)
5,332
semantic_version.base
__ge__
null
def __ge__(self, other): return self.__compare_helper(other, lambda x: x >= 0, notimpl_target=False)
(self, other)
5,333
semantic_version.base
__gt__
null
def __gt__(self, other): return self.__compare_helper(other, lambda x: x > 0, notimpl_target=False)
(self, other)
5,334
semantic_version.base
__hash__
null
def __hash__(self): return hash((self.major, self.minor, self.patch, self.prerelease, self.build))
(self)
5,335
releases.models
__init__
null
def __init__(self, version_string, partial=True): super().__init__(version_string, partial)
(self, version_string, partial=True)
5,336
semantic_version.base
__iter__
null
def __iter__(self): return iter((self.major, self.minor, self.patch, self.prerelease, self.build))
(self)
5,337
semantic_version.base
__le__
null
def __le__(self, other): return self.__compare_helper(other, lambda x: x <= 0, notimpl_target=False)
(self, other)
5,338
semantic_version.base
__lt__
null
def __lt__(self, other): return self.__compare_helper(other, lambda x: x < 0, notimpl_target=False)
(self, other)
5,339
semantic_version.base
__ne__
null
def __ne__(self, other): return self.__compare_helper(other, lambda x: x != 0, notimpl_target=True)
(self, other)
5,340
semantic_version.base
__repr__
null
def __repr__(self): return 'Version(%r%s)' % ( str(self), ', partial=True' if self.partial else '', )
(self)