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
β |
---|---|---|---|---|---|
22,873 | pyglottolog.api | newick_tree |
Returns the Newick representation of a (set of) Glottolog classification tree(s).
:param start: Root languoid of the tree (or `None` to return the complete classification).
:param template: Python format string accepting the `Languoid` instance as single variable named `l`, used to format node labels.
| def newick_tree(
self,
start: typing.Union[None, str, lls.Languoid] = None,
template: str = None,
nodes=None,
maxlevel: typing.Union[int, config.LanguoidLevel] = None
) -> str:
"""
Returns the Newick representation of a (set of) Glottolog classification tree(s).
:param start: Root languoid of the tree (or `None` to return the complete classification).
:param template: Python format string accepting the `Languoid` instance as single \
variable named `l`, used to format node labels.
"""
template = template or lls.Languoid._newick_default_template
if start:
return self.languoid(start).newick_node(
template=template, nodes=nodes, maxlevel=maxlevel, level=1).newick + ';'
if nodes is None:
nodes = collections.OrderedDict((lang.id, lang) for lang in self.languoids())
trees = []
for lang in nodes.values():
if not lang.lineage and not lang.category.startswith('Pseudo '):
ns = lang.newick_node(
nodes=nodes, template=template, maxlevel=maxlevel, level=1).newick
if lang.level == self.languoid_levels.language:
# An isolate: we wrap it in a pseudo-family with the same name and ID.
fam = lls.Languoid.from_name_id_level(
lang.dir.parent, lang.name, lang.id, 'family', _api=self)
ns = '({0}){1}:1'.format(ns, template.format(l=fam)) # noqa: E741
trees.append('{0};'.format(ns))
return '\n'.join(trees)
| (self, start: Union[NoneType, str, pyglottolog.languoids.languoid.Languoid] = None, template: Optional[str] = None, nodes=None, maxlevel: Union[int, pyglottolog.config.LanguoidLevel, NoneType] = None) -> str |
22,874 | clldutils.apilib | path |
A path within the repository.
:param comps: path components relative to `self.repos`.
| def path(self, *comps: str) -> pathlib.Path:
"""
A path within the repository.
:param comps: path components relative to `self.repos`.
"""
return self.repos.joinpath(*comps)
| (self, *comps: str) -> pathlib.Path |
22,875 | pyglottolog.api | references_path |
Path within the `references` directory of the repos.
| def references_path(self, *comps: str):
"""
Path within the `references` directory of the repos.
"""
return self.repos.joinpath('references', *comps)
| (self, *comps: str) |
22,876 | pyglottolog.api | refs_by_languoid | null | def refs_by_languoid(self, *bibfiles, **kw):
nodes = kw.get('nodes')
if bibfiles:
bibfiles = [
bib if isinstance(bib, references.BibFile) else self.bibfiles[bib]
for bib in bibfiles]
else:
bibfiles = self.bibfiles
all_ = {}
languoids_by_code = self.languoids_by_code(
nodes or {lang.id: lang for lang in self.languoids()})
res = collections.defaultdict(list)
for bib in tqdm(bibfiles):
for entry in bib.iterentries():
all_[entry.id] = entry
for lang in entry.languoids(languoids_by_code)[0]:
res[lang.id].append(entry)
return res, all_
| (self, *bibfiles, **kw) |
22,877 | pyglottolog.api | write_languoids_table | null | def write_languoids_table(self, outdir, version=None):
version = version or self.describe()
out = outdir / 'glottolog-languoids-{0}.csv'.format(version)
md = outdir / (out.name + '-metadata.json')
tg = TableGroup.fromvalue({
"@context": "http://www.w3.org/ns/csvw",
"dc:version": version,
"dc:bibliographicCitation":
"{0}. "
"{1} [Data set]. "
"Zenodo. https://doi.org/{2}".format(
' & '.join([e.name for e in self.current_editors]),
self.publication.zenodo.title_format.format('(Version {0})'.format(version)),
self.publication.zenodo.doi,
),
"tables": [load(pycldf.util.pkg_path('components', 'LanguageTable-metadata.json'))],
})
tg.tables[0].url = out.name
for col in [
dict(name='LL_Code'),
dict(name='Classification', separator='/'),
dict(name='Family_Glottocode'),
dict(name='Family_Name'),
dict(name='Language_Glottocode'),
dict(name='Language_Name'),
dict(name='Level', datatype=dict(base='string', format='family|language|dialect')),
dict(name='Status'),
]:
tg.tables[0].tableSchema.columns.append(Column.fromvalue(col))
langs = []
for lang in self.languoids():
lid, lname = None, None
if lang.level == self.languoid_levels.language:
lid, lname = lang.id, lang.name
elif lang.level == self.languoid_levels.dialect:
for lname, lid, level in reversed(lang.lineage):
if level == self.languoid_levels.language:
break
else: # pragma: no cover
raise ValueError
langs.append(dict(
ID=lang.id,
Name=lang.name,
Macroarea=lang.macroareas[0].name if lang.macroareas else None,
Latitude=lang.latitude,
Longitude=lang.longitude,
Glottocode=lang.id,
ISO639P3code=lang.iso,
LL_Code=lang.identifier.get('multitree'),
Classification=[c[1] for c in lang.lineage],
Language_Glottocode=lid,
Language_Name=lname,
Family_Name=lang.lineage[0][0] if lang.lineage else None,
Family_Glottocode=lang.lineage[0][1] if lang.lineage else None,
Level=lang.level.name,
Status=lang.endangerment.status.name if lang.endangerment else None,
))
tg.to_file(md)
tg.tables[0].write(langs, fname=out)
return md, out
| (self, outdir, version=None) |
22,884 | anytree.render | AbstractStyle |
Tree Render Style.
Args:
vertical: Sign for vertical line.
cont: Chars for a continued branch.
end: Chars for the last branch.
| class AbstractStyle:
"""
Tree Render Style.
Args:
vertical: Sign for vertical line.
cont: Chars for a continued branch.
end: Chars for the last branch.
"""
def __init__(self, vertical, cont, end):
super(AbstractStyle, self).__init__()
self.vertical = vertical
self.cont = cont
self.end = end
if ASSERTIONS: # pragma: no branch
assert len(cont) == len(vertical) == len(end), "'%s', '%s' and '%s' need to have equal length" % (
vertical,
cont,
end,
)
@property
def empty(self):
"""Empty string as placeholder."""
return " " * len(self.end)
def __repr__(self):
classname = self.__class__.__name__
return "%s()" % classname
| (vertical, cont, end) |
22,885 | anytree.render | __init__ | null | def __init__(self, vertical, cont, end):
super(AbstractStyle, self).__init__()
self.vertical = vertical
self.cont = cont
self.end = end
if ASSERTIONS: # pragma: no branch
assert len(cont) == len(vertical) == len(end), "'%s', '%s' and '%s' need to have equal length" % (
vertical,
cont,
end,
)
| (self, vertical, cont, end) |
22,886 | anytree.render | __repr__ | null | def __repr__(self):
classname = self.__class__.__name__
return "%s()" % classname
| (self) |
22,887 | anytree.node.anynode | AnyNode |
A generic tree node with any `kwargs`.
Keyword Args:
parent: Reference to parent node.
children: Iterable with child nodes.
*: Any other given attribute is just stored as object attribute.
Other than :any:`Node` this class has no default identifier.
It is up to the user to use other attributes for identification.
The `parent` attribute refers the parent node:
>>> from anytree import AnyNode, RenderTree
>>> root = AnyNode(id="root")
>>> s0 = AnyNode(id="sub0", parent=root)
>>> s0b = AnyNode(id="sub0B", parent=s0, foo=4, bar=109)
>>> s0a = AnyNode(id="sub0A", parent=s0)
>>> s1 = AnyNode(id="sub1", parent=root)
>>> s1a = AnyNode(id="sub1A", parent=s1)
>>> s1b = AnyNode(id="sub1B", parent=s1, bar=8)
>>> s1c = AnyNode(id="sub1C", parent=s1)
>>> s1ca = AnyNode(id="sub1Ca", parent=s1c)
>>> root
AnyNode(id='root')
>>> s0
AnyNode(id='sub0')
>>> print(RenderTree(root))
AnyNode(id='root')
βββ AnyNode(id='sub0')
β βββ AnyNode(bar=109, foo=4, id='sub0B')
β βββ AnyNode(id='sub0A')
βββ AnyNode(id='sub1')
βββ AnyNode(id='sub1A')
βββ AnyNode(bar=8, id='sub1B')
βββ AnyNode(id='sub1C')
βββ AnyNode(id='sub1Ca')
>>> print(RenderTree(root))
AnyNode(id='root')
βββ AnyNode(id='sub0')
β βββ AnyNode(bar=109, foo=4, id='sub0B')
β βββ AnyNode(id='sub0A')
βββ AnyNode(id='sub1')
βββ AnyNode(id='sub1A')
βββ AnyNode(bar=8, id='sub1B')
βββ AnyNode(id='sub1C')
βββ AnyNode(id='sub1Ca')
Node attributes can be added, modified and deleted the pythonic way:
>>> root.new = 'a new attribute'
>>> s0b
AnyNode(bar=109, foo=4, id='sub0B')
>>> s0b.bar = 110 # modified
>>> s0b
AnyNode(bar=110, foo=4, id='sub0B')
>>> del s1b.bar
>>> print(RenderTree(root))
AnyNode(id='root', new='a new attribute')
βββ AnyNode(id='sub0')
β βββ AnyNode(bar=110, foo=4, id='sub0B')
β βββ AnyNode(id='sub0A')
βββ AnyNode(id='sub1')
βββ AnyNode(id='sub1A')
βββ AnyNode(id='sub1B')
βββ AnyNode(id='sub1C')
βββ AnyNode(id='sub1Ca')
The same tree can be constructed by using the `children` attribute:
>>> root = AnyNode(id="root", children=[
... AnyNode(id="sub0", children=[
... AnyNode(id="sub0B", foo=4, bar=109),
... AnyNode(id="sub0A"),
... ]),
... AnyNode(id="sub1", children=[
... AnyNode(id="sub1A"),
... AnyNode(id="sub1B", bar=8),
... AnyNode(id="sub1C", children=[
... AnyNode(id="sub1Ca"),
... ]),
... ]),
... ])
| class AnyNode(NodeMixin):
"""
A generic tree node with any `kwargs`.
Keyword Args:
parent: Reference to parent node.
children: Iterable with child nodes.
*: Any other given attribute is just stored as object attribute.
Other than :any:`Node` this class has no default identifier.
It is up to the user to use other attributes for identification.
The `parent` attribute refers the parent node:
>>> from anytree import AnyNode, RenderTree
>>> root = AnyNode(id="root")
>>> s0 = AnyNode(id="sub0", parent=root)
>>> s0b = AnyNode(id="sub0B", parent=s0, foo=4, bar=109)
>>> s0a = AnyNode(id="sub0A", parent=s0)
>>> s1 = AnyNode(id="sub1", parent=root)
>>> s1a = AnyNode(id="sub1A", parent=s1)
>>> s1b = AnyNode(id="sub1B", parent=s1, bar=8)
>>> s1c = AnyNode(id="sub1C", parent=s1)
>>> s1ca = AnyNode(id="sub1Ca", parent=s1c)
>>> root
AnyNode(id='root')
>>> s0
AnyNode(id='sub0')
>>> print(RenderTree(root))
AnyNode(id='root')
βββ AnyNode(id='sub0')
β βββ AnyNode(bar=109, foo=4, id='sub0B')
β βββ AnyNode(id='sub0A')
βββ AnyNode(id='sub1')
βββ AnyNode(id='sub1A')
βββ AnyNode(bar=8, id='sub1B')
βββ AnyNode(id='sub1C')
βββ AnyNode(id='sub1Ca')
>>> print(RenderTree(root))
AnyNode(id='root')
βββ AnyNode(id='sub0')
β βββ AnyNode(bar=109, foo=4, id='sub0B')
β βββ AnyNode(id='sub0A')
βββ AnyNode(id='sub1')
βββ AnyNode(id='sub1A')
βββ AnyNode(bar=8, id='sub1B')
βββ AnyNode(id='sub1C')
βββ AnyNode(id='sub1Ca')
Node attributes can be added, modified and deleted the pythonic way:
>>> root.new = 'a new attribute'
>>> s0b
AnyNode(bar=109, foo=4, id='sub0B')
>>> s0b.bar = 110 # modified
>>> s0b
AnyNode(bar=110, foo=4, id='sub0B')
>>> del s1b.bar
>>> print(RenderTree(root))
AnyNode(id='root', new='a new attribute')
βββ AnyNode(id='sub0')
β βββ AnyNode(bar=110, foo=4, id='sub0B')
β βββ AnyNode(id='sub0A')
βββ AnyNode(id='sub1')
βββ AnyNode(id='sub1A')
βββ AnyNode(id='sub1B')
βββ AnyNode(id='sub1C')
βββ AnyNode(id='sub1Ca')
The same tree can be constructed by using the `children` attribute:
>>> root = AnyNode(id="root", children=[
... AnyNode(id="sub0", children=[
... AnyNode(id="sub0B", foo=4, bar=109),
... AnyNode(id="sub0A"),
... ]),
... AnyNode(id="sub1", children=[
... AnyNode(id="sub1A"),
... AnyNode(id="sub1B", bar=8),
... AnyNode(id="sub1C", children=[
... AnyNode(id="sub1Ca"),
... ]),
... ]),
... ])
"""
def __init__(self, parent=None, children=None, **kwargs):
self.__dict__.update(kwargs)
self.parent = parent
if children:
self.children = children
def __repr__(self):
return _repr(self)
| (parent=None, children=None, **kwargs) |
22,888 | anytree.node.nodemixin | __attach | null | def __attach(self, parent):
# pylint: disable=W0212
if parent is not None:
self._pre_attach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert not any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parentchildren.append(self)
self.__parent = parent
# ATOMIC END
self._post_attach(parent)
| (self, parent) |
22,889 | anytree.node.nodemixin | __check_children | null | @staticmethod
def __check_children(children):
seen = set()
for child in children:
if not isinstance(child, (NodeMixin, LightNodeMixin)):
msg = "Cannot add non-node object %r. It is not a subclass of 'NodeMixin'." % (child,)
raise TreeError(msg)
childid = id(child)
if childid not in seen:
seen.add(childid)
else:
msg = "Cannot add node %r multiple times as child." % (child,)
raise TreeError(msg)
| (children) |
22,890 | anytree.node.nodemixin | __check_loop | null | def __check_loop(self, node):
if node is not None:
if node is self:
msg = "Cannot set parent. %r cannot be parent of itself."
raise LoopError(msg % (self,))
if any(child is self for child in node.iter_path_reverse()):
msg = "Cannot set parent. %r is parent of %r."
raise LoopError(msg % (self, node))
| (self, node) |
22,891 | anytree.node.nodemixin | __detach | null | def __detach(self, parent):
# pylint: disable=W0212,W0238
if parent is not None:
self._pre_detach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parent.__children = [child for child in parentchildren if child is not self]
self.__parent = None
# ATOMIC END
self._post_detach(parent)
| (self, parent) |
22,892 | anytree.node.anynode | __init__ | null | def __init__(self, parent=None, children=None, **kwargs):
self.__dict__.update(kwargs)
self.parent = parent
if children:
self.children = children
| (self, parent=None, children=None, **kwargs) |
22,893 | anytree.node.anynode | __repr__ | null | def __repr__(self):
return _repr(self)
| (self) |
22,894 | anytree.node.nodemixin | _post_attach | Method call after attaching to `parent`. | def _post_attach(self, parent):
"""Method call after attaching to `parent`."""
| (self, parent) |
22,895 | anytree.node.nodemixin | _post_attach_children | Method call after attaching `children`. | def _post_attach_children(self, children):
"""Method call after attaching `children`."""
| (self, children) |
22,896 | anytree.node.nodemixin | _post_detach | Method call after detaching from `parent`. | def _post_detach(self, parent):
"""Method call after detaching from `parent`."""
| (self, parent) |
22,897 | anytree.node.nodemixin | _post_detach_children | Method call after detaching `children`. | def _post_detach_children(self, children):
"""Method call after detaching `children`."""
| (self, children) |
22,898 | anytree.node.nodemixin | _pre_attach | Method call before attaching to `parent`. | def _pre_attach(self, parent):
"""Method call before attaching to `parent`."""
| (self, parent) |
22,899 | anytree.node.nodemixin | _pre_attach_children | Method call before attaching `children`. | def _pre_attach_children(self, children):
"""Method call before attaching `children`."""
| (self, children) |
22,900 | anytree.node.nodemixin | _pre_detach | Method call before detaching from `parent`. | def _pre_detach(self, parent):
"""Method call before detaching from `parent`."""
| (self, parent) |
22,901 | anytree.node.nodemixin | _pre_detach_children | Method call before detaching `children`. | def _pre_detach_children(self, children):
"""Method call before detaching `children`."""
| (self, children) |
22,902 | anytree.node.nodemixin | iter_path_reverse |
Iterate up the tree from the current node to the root node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> for node in udo.iter_path_reverse():
... print(node)
Node('/Udo')
>>> for node in marc.iter_path_reverse():
... print(node)
Node('/Udo/Marc')
Node('/Udo')
>>> for node in lian.iter_path_reverse():
... print(node)
Node('/Udo/Marc/Lian')
Node('/Udo/Marc')
Node('/Udo')
| def iter_path_reverse(self):
"""
Iterate up the tree from the current node to the root node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> for node in udo.iter_path_reverse():
... print(node)
Node('/Udo')
>>> for node in marc.iter_path_reverse():
... print(node)
Node('/Udo/Marc')
Node('/Udo')
>>> for node in lian.iter_path_reverse():
... print(node)
Node('/Udo/Marc/Lian')
Node('/Udo/Marc')
Node('/Udo')
"""
node = self
while node is not None:
yield node
node = node.parent
| (self) |
22,903 | anytree.render | AsciiStyle |
Ascii style.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=AsciiStyle()))
Node('/root')
|-- Node('/root/sub0')
| |-- Node('/root/sub0/sub0B')
| +-- Node('/root/sub0/sub0A')
+-- Node('/root/sub1')
| class AsciiStyle(AbstractStyle):
"""
Ascii style.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=AsciiStyle()))
Node('/root')
|-- Node('/root/sub0')
| |-- Node('/root/sub0/sub0B')
| +-- Node('/root/sub0/sub0A')
+-- Node('/root/sub1')
"""
def __init__(self):
super(AsciiStyle, self).__init__("| ", "|-- ", "+-- ")
| () |
22,904 | anytree.render | __init__ | null | def __init__(self):
super(AsciiStyle, self).__init__("| ", "|-- ", "+-- ")
| (self) |
22,906 | anytree.resolver | ChildResolverError | null | class ChildResolverError(ResolverError):
def __init__(self, node, child, pathattr):
"""Child Resolve Error at `node` handling `child`."""
names = [repr(_getattr(c, pathattr)) for c in node.children]
msg = "%r has no child %s. Children are: %s." % (node, child, ", ".join(names))
super(ChildResolverError, self).__init__(node, child, msg)
| (node, child, pathattr) |
22,907 | anytree.resolver | __init__ | Child Resolve Error at `node` handling `child`. | def __init__(self, node, child, pathattr):
"""Child Resolve Error at `node` handling `child`."""
names = [repr(_getattr(c, pathattr)) for c in node.children]
msg = "%r has no child %s. Children are: %s." % (node, child, ", ".join(names))
super(ChildResolverError, self).__init__(node, child, msg)
| (self, node, child, pathattr) |
22,908 | anytree.render | ContRoundStyle |
Continued style, without gaps, round edges.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=ContRoundStyle()))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B')
β β°ββ Node('/root/sub0/sub0A')
β°ββ Node('/root/sub1')
| class ContRoundStyle(AbstractStyle):
"""
Continued style, without gaps, round edges.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=ContRoundStyle()))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B')
β β°ββ Node('/root/sub0/sub0A')
β°ββ Node('/root/sub1')
"""
def __init__(self):
super(ContRoundStyle, self).__init__("\u2502 ", "\u251c\u2500\u2500 ", "\u2570\u2500\u2500 ")
| () |
22,909 | anytree.render | __init__ | null | def __init__(self):
super(ContRoundStyle, self).__init__("\u2502 ", "\u251c\u2500\u2500 ", "\u2570\u2500\u2500 ")
| (self) |
22,911 | anytree.render | ContStyle |
Continued style, without gaps.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=ContStyle()))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B')
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
| class ContStyle(AbstractStyle):
"""
Continued style, without gaps.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=ContStyle()))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B')
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
"""
def __init__(self):
super(ContStyle, self).__init__("\u2502 ", "\u251c\u2500\u2500 ", "\u2514\u2500\u2500 ")
| () |
22,912 | anytree.render | __init__ | null | def __init__(self):
super(ContStyle, self).__init__("\u2502 ", "\u251c\u2500\u2500 ", "\u2514\u2500\u2500 ")
| (self) |
22,914 | anytree.search | CountError | null | class CountError(RuntimeError):
def __init__(self, msg, result):
"""Error raised on `mincount` or `maxcount` mismatch."""
if result:
msg += " " + repr(result)
super(CountError, self).__init__(msg)
| (msg, result) |
22,915 | anytree.search | __init__ | Error raised on `mincount` or `maxcount` mismatch. | def __init__(self, msg, result):
"""Error raised on `mincount` or `maxcount` mismatch."""
if result:
msg += " " + repr(result)
super(CountError, self).__init__(msg)
| (self, msg, result) |
22,916 | anytree.render | DoubleStyle |
Double line style, without gaps.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=DoubleStyle))
Node('/root')
β ββ Node('/root/sub0')
β β ββ Node('/root/sub0/sub0B')
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
| class DoubleStyle(AbstractStyle):
"""
Double line style, without gaps.
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> print(RenderTree(root, style=DoubleStyle))
Node('/root')
β ββ Node('/root/sub0')
β β ββ Node('/root/sub0/sub0B')
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
"""
def __init__(self):
super(DoubleStyle, self).__init__("\u2551 ", "\u2560\u2550\u2550 ", "\u255a\u2550\u2550 ")
| () |
22,917 | anytree.render | __init__ | null | def __init__(self):
super(DoubleStyle, self).__init__("\u2551 ", "\u2560\u2550\u2550 ", "\u255a\u2550\u2550 ")
| (self) |
22,919 | anytree.iterators.levelordergroupiter | LevelOrderGroupIter |
Iterate over tree applying level-order strategy with grouping starting at `node`.
Return a tuple of nodes for each level. The first tuple contains the
nodes at level 0 (always `node`). The second tuple contains the nodes at level 1
(children of `node`). The next level contains the children of the children, and so on.
>>> from anytree import Node, RenderTree, AsciiStyle, LevelOrderGroupIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [[node.name for node in children] for children in LevelOrderGroupIter(f)]
[['f'], ['b', 'g'], ['a', 'd', 'i'], ['c', 'e', 'h']]
>>> [[node.name for node in children] for children in LevelOrderGroupIter(f, maxlevel=3)]
[['f'], ['b', 'g'], ['a', 'd', 'i']]
>>> [[node.name for node in children]
... for children in LevelOrderGroupIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
[['f'], ['b'], ['a', 'd', 'i'], ['c', 'h']]
>>> [[node.name for node in children]
... for children in LevelOrderGroupIter(f, stop=lambda n: n.name == 'd')]
[['f'], ['b', 'g'], ['a', 'i'], ['h']]
| class LevelOrderGroupIter(AbstractIter):
"""
Iterate over tree applying level-order strategy with grouping starting at `node`.
Return a tuple of nodes for each level. The first tuple contains the
nodes at level 0 (always `node`). The second tuple contains the nodes at level 1
(children of `node`). The next level contains the children of the children, and so on.
>>> from anytree import Node, RenderTree, AsciiStyle, LevelOrderGroupIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [[node.name for node in children] for children in LevelOrderGroupIter(f)]
[['f'], ['b', 'g'], ['a', 'd', 'i'], ['c', 'e', 'h']]
>>> [[node.name for node in children] for children in LevelOrderGroupIter(f, maxlevel=3)]
[['f'], ['b', 'g'], ['a', 'd', 'i']]
>>> [[node.name for node in children]
... for children in LevelOrderGroupIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
[['f'], ['b'], ['a', 'd', 'i'], ['c', 'h']]
>>> [[node.name for node in children]
... for children in LevelOrderGroupIter(f, stop=lambda n: n.name == 'd')]
[['f'], ['b', 'g'], ['a', 'i'], ['h']]
"""
@staticmethod
def _iter(children, filter_, stop, maxlevel):
level = 1
while children:
yield tuple(child for child in children if filter_(child))
level += 1
if AbstractIter._abort_at_level(level, maxlevel):
break
children = LevelOrderGroupIter._get_grandchildren(children, stop)
@staticmethod
def _get_grandchildren(children, stop):
next_children = []
for child in children:
next_children = next_children + AbstractIter._get_children(child.children, stop)
return next_children
| (node, filter_=None, stop=None, maxlevel=None) |
22,920 | anytree.iterators.abstractiter | __default_filter | null | @staticmethod
def __default_filter(node):
# pylint: disable=W0613
return True
| (node) |
22,921 | anytree.iterators.abstractiter | __default_stop | null | @staticmethod
def __default_stop(node):
# pylint: disable=W0613
return False
| (node) |
22,922 | anytree.iterators.abstractiter | __init | null | def __init(self):
node = self.node
maxlevel = self.maxlevel
filter_ = self.filter_ or AbstractIter.__default_filter
stop = self.stop or AbstractIter.__default_stop
children = [] if AbstractIter._abort_at_level(1, maxlevel) else AbstractIter._get_children([node], stop)
return self._iter(children, filter_, stop, maxlevel)
| (self) |
22,923 | anytree.iterators.abstractiter | __init__ | null | def __init__(self, node, filter_=None, stop=None, maxlevel=None):
self.node = node
self.filter_ = filter_
self.stop = stop
self.maxlevel = maxlevel
self.__iter = None
| (self, node, filter_=None, stop=None, maxlevel=None) |
22,925 | anytree.iterators.abstractiter | __next__ | null | def __next__(self):
if self.__iter is None:
self.__iter = self.__init()
return next(self.__iter)
| (self) |
22,926 | anytree.iterators.abstractiter | _abort_at_level | null | @staticmethod
def _abort_at_level(level, maxlevel):
return maxlevel is not None and level > maxlevel
| (level, maxlevel) |
22,927 | anytree.iterators.abstractiter | _get_children | null | @staticmethod
def _get_children(children, stop):
return [child for child in children if not stop(child)]
| (children, stop) |
22,928 | anytree.iterators.levelordergroupiter | _get_grandchildren | null | @staticmethod
def _get_grandchildren(children, stop):
next_children = []
for child in children:
next_children = next_children + AbstractIter._get_children(child.children, stop)
return next_children
| (children, stop) |
22,929 | anytree.iterators.levelordergroupiter | _iter | null | @staticmethod
def _iter(children, filter_, stop, maxlevel):
level = 1
while children:
yield tuple(child for child in children if filter_(child))
level += 1
if AbstractIter._abort_at_level(level, maxlevel):
break
children = LevelOrderGroupIter._get_grandchildren(children, stop)
| (children, filter_, stop, maxlevel) |
22,941 | anytree.iterators.levelorderiter | LevelOrderIter |
Iterate over tree applying level-order strategy starting at `node`.
>>> from anytree import Node, RenderTree, AsciiStyle, LevelOrderIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [node.name for node in LevelOrderIter(f)]
['f', 'b', 'g', 'a', 'd', 'i', 'c', 'e', 'h']
>>> [node.name for node in LevelOrderIter(f, maxlevel=3)]
['f', 'b', 'g', 'a', 'd', 'i']
>>> [node.name for node in LevelOrderIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
['f', 'b', 'a', 'd', 'i', 'c', 'h']
>>> [node.name for node in LevelOrderIter(f, stop=lambda n: n.name == 'd')]
['f', 'b', 'g', 'a', 'i', 'h']
| class LevelOrderIter(AbstractIter):
"""
Iterate over tree applying level-order strategy starting at `node`.
>>> from anytree import Node, RenderTree, AsciiStyle, LevelOrderIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [node.name for node in LevelOrderIter(f)]
['f', 'b', 'g', 'a', 'd', 'i', 'c', 'e', 'h']
>>> [node.name for node in LevelOrderIter(f, maxlevel=3)]
['f', 'b', 'g', 'a', 'd', 'i']
>>> [node.name for node in LevelOrderIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
['f', 'b', 'a', 'd', 'i', 'c', 'h']
>>> [node.name for node in LevelOrderIter(f, stop=lambda n: n.name == 'd')]
['f', 'b', 'g', 'a', 'i', 'h']
"""
@staticmethod
def _iter(children, filter_, stop, maxlevel):
level = 1
while children:
next_children = []
level += 1
if AbstractIter._abort_at_level(level, maxlevel):
for child in children:
if filter_(child):
yield child
else:
for child in children:
if filter_(child):
yield child
next_children += AbstractIter._get_children(child.children, stop)
children = next_children
| (node, filter_=None, stop=None, maxlevel=None) |
22,950 | anytree.iterators.levelorderiter | _iter | null | @staticmethod
def _iter(children, filter_, stop, maxlevel):
level = 1
while children:
next_children = []
level += 1
if AbstractIter._abort_at_level(level, maxlevel):
for child in children:
if filter_(child):
yield child
else:
for child in children:
if filter_(child):
yield child
next_children += AbstractIter._get_children(child.children, stop)
children = next_children
| (children, filter_, stop, maxlevel) |
22,951 | anytree.node.lightnodemixin | LightNodeMixin |
The :any:`LightNodeMixin` behaves identical to :any:`NodeMixin`, but uses `__slots__`.
There are some minor differences in the object behaviour.
See slots_ for any details.
.. _slots: https://docs.python.org/3/reference/datamodel.html#slots
The only tree relevant information is the `parent` attribute.
If `None` the :any:`LightNodeMixin` is root node.
If set to another node, the :any:`LightNodeMixin` becomes the child of it.
The `children` attribute can be used likewise.
If `None` the :any:`LightNodeMixin` has no children.
The `children` attribute can be set to any iterable of :any:`LightNodeMixin` instances.
These instances become children of the node.
>>> from anytree import LightNodeMixin, RenderTree
>>> class MyBaseClass(): # Just an example of a base class
... __slots__ = []
>>> class MyClass(MyBaseClass, LightNodeMixin): # Add Node feature
... __slots__ = ['name', 'length', 'width']
... def __init__(self, name, length, width, parent=None, children=None):
... super().__init__()
... self.name = name
... self.length = length
... self.width = width
... self.parent = parent
... if children:
... self.children = children
Construction via `parent`:
>>> my0 = MyClass('my0', 0, 0)
>>> my1 = MyClass('my1', 1, 0, parent=my0)
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Construction via `children`:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... MyClass('my2', 0, 2),
... ])
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Both approaches can be mixed:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... ])
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
| class LightNodeMixin:
"""
The :any:`LightNodeMixin` behaves identical to :any:`NodeMixin`, but uses `__slots__`.
There are some minor differences in the object behaviour.
See slots_ for any details.
.. _slots: https://docs.python.org/3/reference/datamodel.html#slots
The only tree relevant information is the `parent` attribute.
If `None` the :any:`LightNodeMixin` is root node.
If set to another node, the :any:`LightNodeMixin` becomes the child of it.
The `children` attribute can be used likewise.
If `None` the :any:`LightNodeMixin` has no children.
The `children` attribute can be set to any iterable of :any:`LightNodeMixin` instances.
These instances become children of the node.
>>> from anytree import LightNodeMixin, RenderTree
>>> class MyBaseClass(): # Just an example of a base class
... __slots__ = []
>>> class MyClass(MyBaseClass, LightNodeMixin): # Add Node feature
... __slots__ = ['name', 'length', 'width']
... def __init__(self, name, length, width, parent=None, children=None):
... super().__init__()
... self.name = name
... self.length = length
... self.width = width
... self.parent = parent
... if children:
... self.children = children
Construction via `parent`:
>>> my0 = MyClass('my0', 0, 0)
>>> my1 = MyClass('my1', 1, 0, parent=my0)
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Construction via `children`:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... MyClass('my2', 0, 2),
... ])
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Both approaches can be mixed:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... ])
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
"""
__slots__ = ["__parent", "__children"]
separator = "/"
@property
def parent(self):
"""
Parent Node.
On set, the node is detached from any previous parent node and attached
to the new node.
>>> from anytree import Node, RenderTree
>>> udo = Node("Udo")
>>> marc = Node("Marc")
>>> lian = Node("Lian", parent=marc)
>>> print(RenderTree(udo))
Node('/Udo')
>>> print(RenderTree(marc))
Node('/Marc')
βββ Node('/Marc/Lian')
**Attach**
>>> marc.parent = udo
>>> print(RenderTree(udo))
Node('/Udo')
βββ Node('/Udo/Marc')
βββ Node('/Udo/Marc/Lian')
**Detach**
To make a node to a root node, just set this attribute to `None`.
>>> marc.is_root
False
>>> marc.parent = None
>>> marc.is_root
True
"""
if hasattr(self, "_LightNodeMixin__parent"):
return self.__parent
return None
@parent.setter
def parent(self, value):
if hasattr(self, "_LightNodeMixin__parent"):
parent = self.__parent
else:
parent = None
if parent is not value:
self.__check_loop(value)
self.__detach(parent)
self.__attach(value)
def __check_loop(self, node):
if node is not None:
if node is self:
msg = "Cannot set parent. %r cannot be parent of itself."
raise LoopError(msg % (self,))
if any(child is self for child in node.iter_path_reverse()):
msg = "Cannot set parent. %r is parent of %r."
raise LoopError(msg % (self, node))
def __detach(self, parent):
# pylint: disable=W0212,W0238
if parent is not None:
self._pre_detach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parent.__children = [child for child in parentchildren if child is not self]
self.__parent = None
# ATOMIC END
self._post_detach(parent)
def __attach(self, parent):
# pylint: disable=W0212
if parent is not None:
self._pre_attach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert not any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parentchildren.append(self)
self.__parent = parent
# ATOMIC END
self._post_attach(parent)
@property
def __children_or_empty(self):
if not hasattr(self, "_LightNodeMixin__children"):
self.__children = []
return self.__children
@property
def children(self):
"""
All child nodes.
>>> from anytree import Node
>>> n = Node("n")
>>> a = Node("a", parent=n)
>>> b = Node("b", parent=n)
>>> c = Node("c", parent=n)
>>> n.children
(Node('/n/a'), Node('/n/b'), Node('/n/c'))
Modifying the children attribute modifies the tree.
**Detach**
The children attribute can be updated by setting to an iterable.
>>> n.children = [a, b]
>>> n.children
(Node('/n/a'), Node('/n/b'))
Node `c` is removed from the tree.
In case of an existing reference, the node `c` does not vanish and is the root of its own tree.
>>> c
Node('/c')
**Attach**
>>> d = Node("d")
>>> d
Node('/d')
>>> n.children = [a, b, d]
>>> n.children
(Node('/n/a'), Node('/n/b'), Node('/n/d'))
>>> d
Node('/n/d')
**Duplicate**
A node can just be the children once. Duplicates cause a :any:`TreeError`:
>>> n.children = [a, b, d, a]
Traceback (most recent call last):
...
anytree.node.exceptions.TreeError: Cannot add node Node('/n/a') multiple times as child.
"""
return tuple(self.__children_or_empty)
@staticmethod
def __check_children(children):
seen = set()
for child in children:
childid = id(child)
if childid not in seen:
seen.add(childid)
else:
msg = "Cannot add node %r multiple times as child." % (child,)
raise TreeError(msg)
@children.setter
def children(self, children):
# convert iterable to tuple
children = tuple(children)
LightNodeMixin.__check_children(children)
# ATOMIC start
old_children = self.children
del self.children
try:
self._pre_attach_children(children)
for child in children:
child.parent = self
self._post_attach_children(children)
if ASSERTIONS: # pragma: no branch
assert len(self.children) == len(children)
except Exception:
self.children = old_children
raise
# ATOMIC end
@children.deleter
def children(self):
children = self.children
self._pre_detach_children(children)
for child in self.children:
child.parent = None
if ASSERTIONS: # pragma: no branch
assert len(self.children) == 0
self._post_detach_children(children)
def _pre_detach_children(self, children):
"""Method call before detaching `children`."""
def _post_detach_children(self, children):
"""Method call after detaching `children`."""
def _pre_attach_children(self, children):
"""Method call before attaching `children`."""
def _post_attach_children(self, children):
"""Method call after attaching `children`."""
@property
def path(self):
"""
Path from root node down to this `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.path
(Node('/Udo'),)
>>> marc.path
(Node('/Udo'), Node('/Udo/Marc'))
>>> lian.path
(Node('/Udo'), Node('/Udo/Marc'), Node('/Udo/Marc/Lian'))
"""
return self._path
def iter_path_reverse(self):
"""
Iterate up the tree from the current node to the root node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> for node in udo.iter_path_reverse():
... print(node)
Node('/Udo')
>>> for node in marc.iter_path_reverse():
... print(node)
Node('/Udo/Marc')
Node('/Udo')
>>> for node in lian.iter_path_reverse():
... print(node)
Node('/Udo/Marc/Lian')
Node('/Udo/Marc')
Node('/Udo')
"""
node = self
while node is not None:
yield node
node = node.parent
@property
def _path(self):
return tuple(reversed(list(self.iter_path_reverse())))
@property
def ancestors(self):
"""
All parent nodes and their parent nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.ancestors
()
>>> marc.ancestors
(Node('/Udo'),)
>>> lian.ancestors
(Node('/Udo'), Node('/Udo/Marc'))
"""
if self.parent is None:
return tuple()
return self.parent.path
@property
def descendants(self):
"""
All child nodes and all their child nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> soe = Node("Soe", parent=lian)
>>> udo.descendants
(Node('/Udo/Marc'), Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lian/Soe'), Node('/Udo/Marc/Loui'))
>>> marc.descendants
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lian/Soe'), Node('/Udo/Marc/Loui'))
>>> lian.descendants
(Node('/Udo/Marc/Lian/Soe'),)
"""
return tuple(PreOrderIter(self))[1:]
@property
def root(self):
"""
Tree Root Node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.root
Node('/Udo')
>>> marc.root
Node('/Udo')
>>> lian.root
Node('/Udo')
"""
node = self
while node.parent is not None:
node = node.parent
return node
@property
def siblings(self):
"""
Tuple of nodes with the same parent.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.siblings
()
>>> marc.siblings
()
>>> lian.siblings
(Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
>>> loui.siblings
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lazy'))
"""
parent = self.parent
if parent is None:
return tuple()
return tuple(node for node in parent.children if node is not self)
@property
def leaves(self):
"""
Tuple of all leaf nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.leaves
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
>>> marc.leaves
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
"""
return tuple(PreOrderIter(self, filter_=lambda node: node.is_leaf))
@property
def is_leaf(self):
"""
`Node` has no children (External Node).
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.is_leaf
False
>>> marc.is_leaf
False
>>> lian.is_leaf
True
"""
return len(self.__children_or_empty) == 0
@property
def is_root(self):
"""
`Node` is tree root.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.is_root
True
>>> marc.is_root
False
>>> lian.is_root
False
"""
return self.parent is None
@property
def height(self):
"""
Number of edges on the longest path to a leaf `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.height
2
>>> marc.height
1
>>> lian.height
0
"""
children = self.__children_or_empty
if children:
return max(child.height for child in children) + 1
return 0
@property
def depth(self):
"""
Number of edges to the root `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.depth
0
>>> marc.depth
1
>>> lian.depth
2
"""
# count without storing the entire path
# pylint: disable=W0631
for depth, _ in enumerate(self.iter_path_reverse()):
continue
return depth
@property
def size(self):
"""
Tree size --- the number of nodes in tree starting at this node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> soe = Node("Soe", parent=lian)
>>> udo.size
5
>>> marc.size
4
>>> lian.size
2
>>> loui.size
1
"""
# count without storing the entire path
# pylint: disable=W0631
for size, _ in enumerate(PreOrderIter(self), 1):
continue
return size
def _pre_detach(self, parent):
"""Method call before detaching from `parent`."""
def _post_detach(self, parent):
"""Method call after detaching from `parent`."""
def _pre_attach(self, parent):
"""Method call before attaching to `parent`."""
def _post_attach(self, parent):
"""Method call after attaching to `parent`."""
| () |
22,953 | anytree.node.lightnodemixin | __check_children | null | @staticmethod
def __check_children(children):
seen = set()
for child in children:
childid = id(child)
if childid not in seen:
seen.add(childid)
else:
msg = "Cannot add node %r multiple times as child." % (child,)
raise TreeError(msg)
| (children) |
22,965 | anytree.node.exceptions | LoopError | Tree contains infinite loop. | class LoopError(TreeError):
"""Tree contains infinite loop."""
| null |
22,966 | anytree.node.node | Node |
A simple tree node with a `name` and any `kwargs`.
Args:
name: A name or any other object this node can reference to as identifier.
Keyword Args:
parent: Reference to parent node.
children: Iterable with child nodes.
*: Any other given attribute is just stored as object attribute.
Other than :any:`AnyNode` this class has at least the `name` attribute,
to distinguish between different instances.
The `parent` attribute refers the parent node:
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0, foo=4, bar=109)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> s1a = Node("sub1A", parent=s1)
>>> s1b = Node("sub1B", parent=s1, bar=8)
>>> s1c = Node("sub1C", parent=s1)
>>> s1ca = Node("sub1Ca", parent=s1c)
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B', bar=109, foo=4)
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
βββ Node('/root/sub1/sub1A')
βββ Node('/root/sub1/sub1B', bar=8)
βββ Node('/root/sub1/sub1C')
βββ Node('/root/sub1/sub1C/sub1Ca')
The same tree can be constructed by using the `children` attribute:
>>> root = Node("root", children=[
... Node("sub0", children=[
... Node("sub0B", bar=109, foo=4),
... Node("sub0A", children=None),
... ]),
... Node("sub1", children=[
... Node("sub1A"),
... Node("sub1B", bar=8, children=[]),
... Node("sub1C", children=[
... Node("sub1Ca"),
... ]),
... ]),
... ])
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B', bar=109, foo=4)
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
βββ Node('/root/sub1/sub1A')
βββ Node('/root/sub1/sub1B', bar=8)
βββ Node('/root/sub1/sub1C')
βββ Node('/root/sub1/sub1C/sub1Ca')
| class Node(NodeMixin):
"""
A simple tree node with a `name` and any `kwargs`.
Args:
name: A name or any other object this node can reference to as identifier.
Keyword Args:
parent: Reference to parent node.
children: Iterable with child nodes.
*: Any other given attribute is just stored as object attribute.
Other than :any:`AnyNode` this class has at least the `name` attribute,
to distinguish between different instances.
The `parent` attribute refers the parent node:
>>> from anytree import Node, RenderTree
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root)
>>> s0b = Node("sub0B", parent=s0, foo=4, bar=109)
>>> s0a = Node("sub0A", parent=s0)
>>> s1 = Node("sub1", parent=root)
>>> s1a = Node("sub1A", parent=s1)
>>> s1b = Node("sub1B", parent=s1, bar=8)
>>> s1c = Node("sub1C", parent=s1)
>>> s1ca = Node("sub1Ca", parent=s1c)
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B', bar=109, foo=4)
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
βββ Node('/root/sub1/sub1A')
βββ Node('/root/sub1/sub1B', bar=8)
βββ Node('/root/sub1/sub1C')
βββ Node('/root/sub1/sub1C/sub1Ca')
The same tree can be constructed by using the `children` attribute:
>>> root = Node("root", children=[
... Node("sub0", children=[
... Node("sub0B", bar=109, foo=4),
... Node("sub0A", children=None),
... ]),
... Node("sub1", children=[
... Node("sub1A"),
... Node("sub1B", bar=8, children=[]),
... Node("sub1C", children=[
... Node("sub1Ca"),
... ]),
... ]),
... ])
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub0')
β βββ Node('/root/sub0/sub0B', bar=109, foo=4)
β βββ Node('/root/sub0/sub0A')
βββ Node('/root/sub1')
βββ Node('/root/sub1/sub1A')
βββ Node('/root/sub1/sub1B', bar=8)
βββ Node('/root/sub1/sub1C')
βββ Node('/root/sub1/sub1C/sub1Ca')
"""
def __init__(self, name, parent=None, children=None, **kwargs):
self.__dict__.update(kwargs)
self.name = name
self.parent = parent
if children:
self.children = children
def __repr__(self):
args = ["%r" % self.separator.join([""] + [str(node.name) for node in self.path])]
return _repr(self, args=args, nameblacklist=["name"])
| (name, parent=None, children=None, **kwargs) |
22,971 | anytree.node.node | __init__ | null | def __init__(self, name, parent=None, children=None, **kwargs):
self.__dict__.update(kwargs)
self.name = name
self.parent = parent
if children:
self.children = children
| (self, name, parent=None, children=None, **kwargs) |
22,972 | anytree.node.node | __repr__ | null | def __repr__(self):
args = ["%r" % self.separator.join([""] + [str(node.name) for node in self.path])]
return _repr(self, args=args, nameblacklist=["name"])
| (self) |
22,982 | anytree.node.nodemixin | NodeMixin |
The :any:`NodeMixin` class extends any Python class to a tree node.
The only tree relevant information is the `parent` attribute.
If `None` the :any:`NodeMixin` is root node.
If set to another node, the :any:`NodeMixin` becomes the child of it.
The `children` attribute can be used likewise.
If `None` the :any:`NodeMixin` has no children.
The `children` attribute can be set to any iterable of :any:`NodeMixin` instances.
These instances become children of the node.
>>> from anytree import NodeMixin, RenderTree
>>> class MyBaseClass(object): # Just an example of a base class
... foo = 4
>>> class MyClass(MyBaseClass, NodeMixin): # Add Node feature
... def __init__(self, name, length, width, parent=None, children=None):
... super(MyClass, self).__init__()
... self.name = name
... self.length = length
... self.width = width
... self.parent = parent
... if children:
... self.children = children
Construction via `parent`:
>>> my0 = MyClass('my0', 0, 0)
>>> my1 = MyClass('my1', 1, 0, parent=my0)
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Construction via `children`:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... MyClass('my2', 0, 2),
... ])
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Both approaches can be mixed:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... ])
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
| class NodeMixin:
"""
The :any:`NodeMixin` class extends any Python class to a tree node.
The only tree relevant information is the `parent` attribute.
If `None` the :any:`NodeMixin` is root node.
If set to another node, the :any:`NodeMixin` becomes the child of it.
The `children` attribute can be used likewise.
If `None` the :any:`NodeMixin` has no children.
The `children` attribute can be set to any iterable of :any:`NodeMixin` instances.
These instances become children of the node.
>>> from anytree import NodeMixin, RenderTree
>>> class MyBaseClass(object): # Just an example of a base class
... foo = 4
>>> class MyClass(MyBaseClass, NodeMixin): # Add Node feature
... def __init__(self, name, length, width, parent=None, children=None):
... super(MyClass, self).__init__()
... self.name = name
... self.length = length
... self.width = width
... self.parent = parent
... if children:
... self.children = children
Construction via `parent`:
>>> my0 = MyClass('my0', 0, 0)
>>> my1 = MyClass('my1', 1, 0, parent=my0)
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Construction via `children`:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... MyClass('my2', 0, 2),
... ])
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
Both approaches can be mixed:
>>> my0 = MyClass('my0', 0, 0, children=[
... MyClass('my1', 1, 0),
... ])
>>> my2 = MyClass('my2', 0, 2, parent=my0)
>>> for pre, _, node in RenderTree(my0):
... treestr = u"%s%s" % (pre, node.name)
... print(treestr.ljust(8), node.length, node.width)
my0 0 0
βββ my1 1 0
βββ my2 0 2
"""
separator = "/"
@property
def parent(self):
"""
Parent Node.
On set, the node is detached from any previous parent node and attached
to the new node.
>>> from anytree import Node, RenderTree
>>> udo = Node("Udo")
>>> marc = Node("Marc")
>>> lian = Node("Lian", parent=marc)
>>> print(RenderTree(udo))
Node('/Udo')
>>> print(RenderTree(marc))
Node('/Marc')
βββ Node('/Marc/Lian')
**Attach**
>>> marc.parent = udo
>>> print(RenderTree(udo))
Node('/Udo')
βββ Node('/Udo/Marc')
βββ Node('/Udo/Marc/Lian')
**Detach**
To make a node to a root node, just set this attribute to `None`.
>>> marc.is_root
False
>>> marc.parent = None
>>> marc.is_root
True
"""
if hasattr(self, "_NodeMixin__parent"):
return self.__parent
return None
@parent.setter
def parent(self, value):
if value is not None and not isinstance(value, (NodeMixin, LightNodeMixin)):
msg = "Parent node %r is not of type 'NodeMixin'." % (value,)
raise TreeError(msg)
if hasattr(self, "_NodeMixin__parent"):
parent = self.__parent
else:
parent = None
if parent is not value:
self.__check_loop(value)
self.__detach(parent)
self.__attach(value)
def __check_loop(self, node):
if node is not None:
if node is self:
msg = "Cannot set parent. %r cannot be parent of itself."
raise LoopError(msg % (self,))
if any(child is self for child in node.iter_path_reverse()):
msg = "Cannot set parent. %r is parent of %r."
raise LoopError(msg % (self, node))
def __detach(self, parent):
# pylint: disable=W0212,W0238
if parent is not None:
self._pre_detach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parent.__children = [child for child in parentchildren if child is not self]
self.__parent = None
# ATOMIC END
self._post_detach(parent)
def __attach(self, parent):
# pylint: disable=W0212
if parent is not None:
self._pre_attach(parent)
parentchildren = parent.__children_or_empty
if ASSERTIONS: # pragma: no branch
assert not any(child is self for child in parentchildren), "Tree is corrupt." # pragma: no cover
# ATOMIC START
parentchildren.append(self)
self.__parent = parent
# ATOMIC END
self._post_attach(parent)
@property
def __children_or_empty(self):
if not hasattr(self, "_NodeMixin__children"):
self.__children = []
return self.__children
@property
def children(self):
"""
All child nodes.
>>> from anytree import Node
>>> n = Node("n")
>>> a = Node("a", parent=n)
>>> b = Node("b", parent=n)
>>> c = Node("c", parent=n)
>>> n.children
(Node('/n/a'), Node('/n/b'), Node('/n/c'))
Modifying the children attribute modifies the tree.
**Detach**
The children attribute can be updated by setting to an iterable.
>>> n.children = [a, b]
>>> n.children
(Node('/n/a'), Node('/n/b'))
Node `c` is removed from the tree.
In case of an existing reference, the node `c` does not vanish and is the root of its own tree.
>>> c
Node('/c')
**Attach**
>>> d = Node("d")
>>> d
Node('/d')
>>> n.children = [a, b, d]
>>> n.children
(Node('/n/a'), Node('/n/b'), Node('/n/d'))
>>> d
Node('/n/d')
**Duplicate**
A node can just be the children once. Duplicates cause a :any:`TreeError`:
>>> n.children = [a, b, d, a]
Traceback (most recent call last):
...
anytree.node.exceptions.TreeError: Cannot add node Node('/n/a') multiple times as child.
"""
return tuple(self.__children_or_empty)
@staticmethod
def __check_children(children):
seen = set()
for child in children:
if not isinstance(child, (NodeMixin, LightNodeMixin)):
msg = "Cannot add non-node object %r. It is not a subclass of 'NodeMixin'." % (child,)
raise TreeError(msg)
childid = id(child)
if childid not in seen:
seen.add(childid)
else:
msg = "Cannot add node %r multiple times as child." % (child,)
raise TreeError(msg)
@children.setter
def children(self, children):
# convert iterable to tuple
children = tuple(children)
NodeMixin.__check_children(children)
# ATOMIC start
old_children = self.children
del self.children
try:
self._pre_attach_children(children)
for child in children:
child.parent = self
self._post_attach_children(children)
if ASSERTIONS: # pragma: no branch
assert len(self.children) == len(children)
except Exception:
self.children = old_children
raise
# ATOMIC end
@children.deleter
def children(self):
children = self.children
self._pre_detach_children(children)
for child in self.children:
child.parent = None
if ASSERTIONS: # pragma: no branch
assert len(self.children) == 0
self._post_detach_children(children)
def _pre_detach_children(self, children):
"""Method call before detaching `children`."""
def _post_detach_children(self, children):
"""Method call after detaching `children`."""
def _pre_attach_children(self, children):
"""Method call before attaching `children`."""
def _post_attach_children(self, children):
"""Method call after attaching `children`."""
@property
def path(self):
"""
Path from root node down to this `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.path
(Node('/Udo'),)
>>> marc.path
(Node('/Udo'), Node('/Udo/Marc'))
>>> lian.path
(Node('/Udo'), Node('/Udo/Marc'), Node('/Udo/Marc/Lian'))
"""
return self._path
def iter_path_reverse(self):
"""
Iterate up the tree from the current node to the root node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> for node in udo.iter_path_reverse():
... print(node)
Node('/Udo')
>>> for node in marc.iter_path_reverse():
... print(node)
Node('/Udo/Marc')
Node('/Udo')
>>> for node in lian.iter_path_reverse():
... print(node)
Node('/Udo/Marc/Lian')
Node('/Udo/Marc')
Node('/Udo')
"""
node = self
while node is not None:
yield node
node = node.parent
@property
def _path(self):
return tuple(reversed(list(self.iter_path_reverse())))
@property
def ancestors(self):
"""
All parent nodes and their parent nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.ancestors
()
>>> marc.ancestors
(Node('/Udo'),)
>>> lian.ancestors
(Node('/Udo'), Node('/Udo/Marc'))
"""
if self.parent is None:
return tuple()
return self.parent.path
@property
def anchestors(self):
"""
All parent nodes and their parent nodes - see :any:`ancestors`.
The attribute `anchestors` is just a typo of `ancestors`. Please use `ancestors`.
This attribute will be removed in the 3.0.0 release.
"""
warnings.warn(".anchestors was a typo and will be removed in version 3.0.0", DeprecationWarning)
return self.ancestors
@property
def descendants(self):
"""
All child nodes and all their child nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> soe = Node("Soe", parent=lian)
>>> udo.descendants
(Node('/Udo/Marc'), Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lian/Soe'), Node('/Udo/Marc/Loui'))
>>> marc.descendants
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lian/Soe'), Node('/Udo/Marc/Loui'))
>>> lian.descendants
(Node('/Udo/Marc/Lian/Soe'),)
"""
return tuple(PreOrderIter(self))[1:]
@property
def root(self):
"""
Tree Root Node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.root
Node('/Udo')
>>> marc.root
Node('/Udo')
>>> lian.root
Node('/Udo')
"""
node = self
while node.parent is not None:
node = node.parent
return node
@property
def siblings(self):
"""
Tuple of nodes with the same parent.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.siblings
()
>>> marc.siblings
()
>>> lian.siblings
(Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
>>> loui.siblings
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Lazy'))
"""
parent = self.parent
if parent is None:
return tuple()
return tuple(node for node in parent.children if node is not self)
@property
def leaves(self):
"""
Tuple of all leaf nodes.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> lazy = Node("Lazy", parent=marc)
>>> udo.leaves
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
>>> marc.leaves
(Node('/Udo/Marc/Lian'), Node('/Udo/Marc/Loui'), Node('/Udo/Marc/Lazy'))
"""
return tuple(PreOrderIter(self, filter_=lambda node: node.is_leaf))
@property
def is_leaf(self):
"""
`Node` has no children (External Node).
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.is_leaf
False
>>> marc.is_leaf
False
>>> lian.is_leaf
True
"""
return len(self.__children_or_empty) == 0
@property
def is_root(self):
"""
`Node` is tree root.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.is_root
True
>>> marc.is_root
False
>>> lian.is_root
False
"""
return self.parent is None
@property
def height(self):
"""
Number of edges on the longest path to a leaf `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.height
2
>>> marc.height
1
>>> lian.height
0
"""
children = self.__children_or_empty
if children:
return max(child.height for child in children) + 1
return 0
@property
def depth(self):
"""
Number of edges to the root `Node`.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> udo.depth
0
>>> marc.depth
1
>>> lian.depth
2
"""
# count without storing the entire path
# pylint: disable=W0631
for depth, _ in enumerate(self.iter_path_reverse()):
continue
return depth
@property
def size(self):
"""
Tree size --- the number of nodes in tree starting at this node.
>>> from anytree import Node
>>> udo = Node("Udo")
>>> marc = Node("Marc", parent=udo)
>>> lian = Node("Lian", parent=marc)
>>> loui = Node("Loui", parent=marc)
>>> soe = Node("Soe", parent=lian)
>>> udo.size
5
>>> marc.size
4
>>> lian.size
2
>>> loui.size
1
"""
# count without storing the entire path
# pylint: disable=W0631
for size, _ in enumerate(PreOrderIter(self), 1):
continue
return size
def _pre_detach(self, parent):
"""Method call before detaching from `parent`."""
def _post_detach(self, parent):
"""Method call after detaching from `parent`."""
def _pre_attach(self, parent):
"""Method call before attaching to `parent`."""
def _post_attach(self, parent):
"""Method call after attaching to `parent`."""
| () |
22,996 | anytree.iterators.postorderiter | PostOrderIter |
Iterate over tree applying post-order strategy starting at `node`.
>>> from anytree import Node, RenderTree, AsciiStyle, PostOrderIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [node.name for node in PostOrderIter(f)]
['a', 'c', 'e', 'd', 'b', 'h', 'i', 'g', 'f']
>>> [node.name for node in PostOrderIter(f, maxlevel=3)]
['a', 'd', 'b', 'i', 'g', 'f']
>>> [node.name for node in PostOrderIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
['a', 'c', 'd', 'b', 'h', 'i', 'f']
>>> [node.name for node in PostOrderIter(f, stop=lambda n: n.name == 'd')]
['a', 'b', 'h', 'i', 'g', 'f']
| class PostOrderIter(AbstractIter):
"""
Iterate over tree applying post-order strategy starting at `node`.
>>> from anytree import Node, RenderTree, AsciiStyle, PostOrderIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [node.name for node in PostOrderIter(f)]
['a', 'c', 'e', 'd', 'b', 'h', 'i', 'g', 'f']
>>> [node.name for node in PostOrderIter(f, maxlevel=3)]
['a', 'd', 'b', 'i', 'g', 'f']
>>> [node.name for node in PostOrderIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
['a', 'c', 'd', 'b', 'h', 'i', 'f']
>>> [node.name for node in PostOrderIter(f, stop=lambda n: n.name == 'd')]
['a', 'b', 'h', 'i', 'g', 'f']
"""
@staticmethod
def _iter(children, filter_, stop, maxlevel):
return PostOrderIter.__next(children, 1, filter_, stop, maxlevel)
@staticmethod
def __next(children, level, filter_, stop, maxlevel):
if not AbstractIter._abort_at_level(level, maxlevel):
for child in children:
grandchildren = AbstractIter._get_children(child.children, stop)
for grandchild in PostOrderIter.__next(grandchildren, level + 1, filter_, stop, maxlevel):
yield grandchild
if filter_(child):
yield child
| (node, filter_=None, stop=None, maxlevel=None) |
23,000 | anytree.iterators.postorderiter | __next | null | @staticmethod
def __next(children, level, filter_, stop, maxlevel):
if not AbstractIter._abort_at_level(level, maxlevel):
for child in children:
grandchildren = AbstractIter._get_children(child.children, stop)
for grandchild in PostOrderIter.__next(grandchildren, level + 1, filter_, stop, maxlevel):
yield grandchild
if filter_(child):
yield child
| (children, level, filter_, stop, maxlevel) |
23,006 | anytree.iterators.postorderiter | _iter | null | @staticmethod
def _iter(children, filter_, stop, maxlevel):
return PostOrderIter.__next(children, 1, filter_, stop, maxlevel)
| (children, filter_, stop, maxlevel) |
23,007 | anytree.iterators.preorderiter | PreOrderIter |
Iterate over tree applying pre-order strategy starting at `node`.
Start at root and go-down until reaching a leaf node.
Step upwards then, and search for the next leafs.
>>> from anytree import Node, RenderTree, AsciiStyle, PreOrderIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [node.name for node in PreOrderIter(f)]
['f', 'b', 'a', 'd', 'c', 'e', 'g', 'i', 'h']
>>> [node.name for node in PreOrderIter(f, maxlevel=3)]
['f', 'b', 'a', 'd', 'g', 'i']
>>> [node.name for node in PreOrderIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
['f', 'b', 'a', 'd', 'c', 'i', 'h']
>>> [node.name for node in PreOrderIter(f, stop=lambda n: n.name == 'd')]
['f', 'b', 'a', 'g', 'i', 'h']
| class PreOrderIter(AbstractIter):
"""
Iterate over tree applying pre-order strategy starting at `node`.
Start at root and go-down until reaching a leaf node.
Step upwards then, and search for the next leafs.
>>> from anytree import Node, RenderTree, AsciiStyle, PreOrderIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [node.name for node in PreOrderIter(f)]
['f', 'b', 'a', 'd', 'c', 'e', 'g', 'i', 'h']
>>> [node.name for node in PreOrderIter(f, maxlevel=3)]
['f', 'b', 'a', 'd', 'g', 'i']
>>> [node.name for node in PreOrderIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
['f', 'b', 'a', 'd', 'c', 'i', 'h']
>>> [node.name for node in PreOrderIter(f, stop=lambda n: n.name == 'd')]
['f', 'b', 'a', 'g', 'i', 'h']
"""
@staticmethod
def _iter(children, filter_, stop, maxlevel):
for child_ in children:
if stop(child_):
continue
if filter_(child_):
yield child_
if not AbstractIter._abort_at_level(2, maxlevel):
descendantmaxlevel = maxlevel - 1 if maxlevel else None
for descendant_ in PreOrderIter._iter(child_.children, filter_, stop, descendantmaxlevel):
yield descendant_
| (node, filter_=None, stop=None, maxlevel=None) |
23,016 | anytree.iterators.preorderiter | _iter | null | @staticmethod
def _iter(children, filter_, stop, maxlevel):
for child_ in children:
if stop(child_):
continue
if filter_(child_):
yield child_
if not AbstractIter._abort_at_level(2, maxlevel):
descendantmaxlevel = maxlevel - 1 if maxlevel else None
for descendant_ in PreOrderIter._iter(child_.children, filter_, stop, descendantmaxlevel):
yield descendant_
| (children, filter_, stop, maxlevel) |
23,017 | anytree.render | RenderTree |
Render tree starting at `node`.
Keyword Args:
style (AbstractStyle): Render Style.
childiter: Child iterator.
maxlevel: Limit rendering to this depth.
:any:`RenderTree` is an iterator, returning a tuple with 3 items:
`pre`
tree prefix.
`fill`
filling for multiline entries.
`node`
:any:`NodeMixin` object.
It is up to the user to assemble these parts to a whole.
>>> from anytree import Node, RenderTree
>>> root = Node("root", lines=["c0fe", "c0de"])
>>> s0 = Node("sub0", parent=root, lines=["ha", "ba"])
>>> s0b = Node("sub0B", parent=s0, lines=["1", "2", "3"])
>>> s0a = Node("sub0A", parent=s0, lines=["a", "b"])
>>> s1 = Node("sub1", parent=root, lines=["Z"])
Simple one line:
>>> for pre, _, node in RenderTree(root):
... print("%s%s" % (pre, node.name))
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
Multiline:
>>> for pre, fill, node in RenderTree(root):
... print("%s%s" % (pre, node.lines[0]))
... for line in node.lines[1:]:
... print("%s%s" % (fill, line))
c0fe
c0de
βββ ha
β ba
β βββ 1
β β 2
β β 3
β βββ a
β b
βββ Z
`maxlevel` limits the depth of the tree:
>>> print(RenderTree(root, maxlevel=2))
Node('/root', lines=['c0fe', 'c0de'])
βββ Node('/root/sub0', lines=['ha', 'ba'])
βββ Node('/root/sub1', lines=['Z'])
The `childiter` is responsible for iterating over child nodes at the
same level. An reversed order can be achived by using `reversed`.
>>> for row in RenderTree(root, childiter=reversed):
... print("%s%s" % (row.pre, row.node.name))
root
βββ sub1
βββ sub0
βββ sub0A
βββ sub0B
Or writing your own sort function:
>>> def mysort(items):
... return sorted(items, key=lambda item: item.name)
>>> for row in RenderTree(root, childiter=mysort):
... print("%s%s" % (row.pre, row.node.name))
root
βββ sub0
β βββ sub0A
β βββ sub0B
βββ sub1
:any:`by_attr` simplifies attribute rendering and supports multiline:
>>> print(RenderTree(root).by_attr())
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
>>> print(RenderTree(root).by_attr("lines"))
c0fe
c0de
βββ ha
β ba
β βββ 1
β β 2
β β 3
β βββ a
β b
βββ Z
And can be a function:
>>> print(RenderTree(root).by_attr(lambda n: " ".join(n.lines)))
c0fe c0de
βββ ha ba
β βββ 1 2 3
β βββ a b
βββ Z
| class RenderTree:
"""
Render tree starting at `node`.
Keyword Args:
style (AbstractStyle): Render Style.
childiter: Child iterator.
maxlevel: Limit rendering to this depth.
:any:`RenderTree` is an iterator, returning a tuple with 3 items:
`pre`
tree prefix.
`fill`
filling for multiline entries.
`node`
:any:`NodeMixin` object.
It is up to the user to assemble these parts to a whole.
>>> from anytree import Node, RenderTree
>>> root = Node("root", lines=["c0fe", "c0de"])
>>> s0 = Node("sub0", parent=root, lines=["ha", "ba"])
>>> s0b = Node("sub0B", parent=s0, lines=["1", "2", "3"])
>>> s0a = Node("sub0A", parent=s0, lines=["a", "b"])
>>> s1 = Node("sub1", parent=root, lines=["Z"])
Simple one line:
>>> for pre, _, node in RenderTree(root):
... print("%s%s" % (pre, node.name))
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
Multiline:
>>> for pre, fill, node in RenderTree(root):
... print("%s%s" % (pre, node.lines[0]))
... for line in node.lines[1:]:
... print("%s%s" % (fill, line))
c0fe
c0de
βββ ha
β ba
β βββ 1
β β 2
β β 3
β βββ a
β b
βββ Z
`maxlevel` limits the depth of the tree:
>>> print(RenderTree(root, maxlevel=2))
Node('/root', lines=['c0fe', 'c0de'])
βββ Node('/root/sub0', lines=['ha', 'ba'])
βββ Node('/root/sub1', lines=['Z'])
The `childiter` is responsible for iterating over child nodes at the
same level. An reversed order can be achived by using `reversed`.
>>> for row in RenderTree(root, childiter=reversed):
... print("%s%s" % (row.pre, row.node.name))
root
βββ sub1
βββ sub0
βββ sub0A
βββ sub0B
Or writing your own sort function:
>>> def mysort(items):
... return sorted(items, key=lambda item: item.name)
>>> for row in RenderTree(root, childiter=mysort):
... print("%s%s" % (row.pre, row.node.name))
root
βββ sub0
β βββ sub0A
β βββ sub0B
βββ sub1
:any:`by_attr` simplifies attribute rendering and supports multiline:
>>> print(RenderTree(root).by_attr())
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
>>> print(RenderTree(root).by_attr("lines"))
c0fe
c0de
βββ ha
β ba
β βββ 1
β β 2
β β 3
β βββ a
β b
βββ Z
And can be a function:
>>> print(RenderTree(root).by_attr(lambda n: " ".join(n.lines)))
c0fe c0de
βββ ha ba
β βββ 1 2 3
β βββ a b
βββ Z
"""
def __init__(self, node, style=ContStyle(), childiter=list, maxlevel=None):
if not isinstance(style, AbstractStyle):
style = style()
self.node = node
self.style = style
self.childiter = childiter
self.maxlevel = maxlevel
def __iter__(self):
return self.__next(self.node, tuple())
def __next(self, node, continues, level=0):
yield RenderTree.__item(node, continues, self.style)
level += 1
if self.maxlevel is None or level < self.maxlevel:
children = node.children
if children:
children = self.childiter(children)
for child, is_last in _is_last(children):
for grandchild in self.__next(child, continues + (not is_last,), level=level):
yield grandchild
@staticmethod
def __item(node, continues, style):
if not continues:
return Row("", "", node)
items = [style.vertical if cont else style.empty for cont in continues]
indent = "".join(items[:-1])
branch = style.cont if continues[-1] else style.end
pre = indent + branch
fill = "".join(items)
return Row(pre, fill, node)
def __str__(self):
def get():
for row in self:
lines = repr(row.node).splitlines() or [""]
yield "%s%s" % (row.pre, lines[0])
for line in lines[1:]:
yield "%s%s" % (row.fill, line)
return "\n".join(get())
def __repr__(self):
classname = self.__class__.__name__
args = [repr(self.node), "style=%s" % repr(self.style), "childiter=%s" % repr(self.childiter)]
return "%s(%s)" % (classname, ", ".join(args))
def by_attr(self, attrname="name"):
"""
Return rendered tree with node attribute `attrname`.
>>> from anytree import AnyNode, RenderTree
>>> root = AnyNode(id="root")
>>> s0 = AnyNode(id="sub0", parent=root)
>>> s0b = AnyNode(id="sub0B", parent=s0, foo=4, bar=109)
>>> s0a = AnyNode(id="sub0A", parent=s0)
>>> s1 = AnyNode(id="sub1", parent=root)
>>> s1a = AnyNode(id="sub1A", parent=s1)
>>> s1b = AnyNode(id="sub1B", parent=s1, bar=8)
>>> s1c = AnyNode(id="sub1C", parent=s1)
>>> s1ca = AnyNode(id="sub1Ca", parent=s1c)
>>> print(RenderTree(root).by_attr('id'))
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
βββ sub1A
βββ sub1B
βββ sub1C
βββ sub1Ca
"""
def get():
if callable(attrname):
for row in self:
attr = attrname(row.node)
yield from _format_row_any(row, attr)
else:
for row in self:
attr = getattr(row.node, attrname, "")
yield from _format_row_any(row, attr)
return "\n".join(get())
| (node, style=ContStyle(), childiter=<class 'list'>, maxlevel=None) |
23,018 | anytree.render | __item | null | @staticmethod
def __item(node, continues, style):
if not continues:
return Row("", "", node)
items = [style.vertical if cont else style.empty for cont in continues]
indent = "".join(items[:-1])
branch = style.cont if continues[-1] else style.end
pre = indent + branch
fill = "".join(items)
return Row(pre, fill, node)
| (node, continues, style) |
23,019 | anytree.render | __next | null | def __next(self, node, continues, level=0):
yield RenderTree.__item(node, continues, self.style)
level += 1
if self.maxlevel is None or level < self.maxlevel:
children = node.children
if children:
children = self.childiter(children)
for child, is_last in _is_last(children):
for grandchild in self.__next(child, continues + (not is_last,), level=level):
yield grandchild
| (self, node, continues, level=0) |
23,020 | anytree.render | __init__ | null | def __init__(self, node, style=ContStyle(), childiter=list, maxlevel=None):
if not isinstance(style, AbstractStyle):
style = style()
self.node = node
self.style = style
self.childiter = childiter
self.maxlevel = maxlevel
| (self, node, style=ContStyle(), childiter=<class 'list'>, maxlevel=None) |
23,021 | anytree.render | __iter__ | null | def __iter__(self):
return self.__next(self.node, tuple())
| (self) |
23,022 | anytree.render | __repr__ | null | def __repr__(self):
classname = self.__class__.__name__
args = [repr(self.node), "style=%s" % repr(self.style), "childiter=%s" % repr(self.childiter)]
return "%s(%s)" % (classname, ", ".join(args))
| (self) |
23,023 | anytree.render | __str__ | null | def __str__(self):
def get():
for row in self:
lines = repr(row.node).splitlines() or [""]
yield "%s%s" % (row.pre, lines[0])
for line in lines[1:]:
yield "%s%s" % (row.fill, line)
return "\n".join(get())
| (self) |
23,024 | anytree.render | by_attr |
Return rendered tree with node attribute `attrname`.
>>> from anytree import AnyNode, RenderTree
>>> root = AnyNode(id="root")
>>> s0 = AnyNode(id="sub0", parent=root)
>>> s0b = AnyNode(id="sub0B", parent=s0, foo=4, bar=109)
>>> s0a = AnyNode(id="sub0A", parent=s0)
>>> s1 = AnyNode(id="sub1", parent=root)
>>> s1a = AnyNode(id="sub1A", parent=s1)
>>> s1b = AnyNode(id="sub1B", parent=s1, bar=8)
>>> s1c = AnyNode(id="sub1C", parent=s1)
>>> s1ca = AnyNode(id="sub1Ca", parent=s1c)
>>> print(RenderTree(root).by_attr('id'))
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
βββ sub1A
βββ sub1B
βββ sub1C
βββ sub1Ca
| def by_attr(self, attrname="name"):
"""
Return rendered tree with node attribute `attrname`.
>>> from anytree import AnyNode, RenderTree
>>> root = AnyNode(id="root")
>>> s0 = AnyNode(id="sub0", parent=root)
>>> s0b = AnyNode(id="sub0B", parent=s0, foo=4, bar=109)
>>> s0a = AnyNode(id="sub0A", parent=s0)
>>> s1 = AnyNode(id="sub1", parent=root)
>>> s1a = AnyNode(id="sub1A", parent=s1)
>>> s1b = AnyNode(id="sub1B", parent=s1, bar=8)
>>> s1c = AnyNode(id="sub1C", parent=s1)
>>> s1ca = AnyNode(id="sub1Ca", parent=s1c)
>>> print(RenderTree(root).by_attr('id'))
root
βββ sub0
β βββ sub0B
β βββ sub0A
βββ sub1
βββ sub1A
βββ sub1B
βββ sub1C
βββ sub1Ca
"""
def get():
if callable(attrname):
for row in self:
attr = attrname(row.node)
yield from _format_row_any(row, attr)
else:
for row in self:
attr = getattr(row.node, attrname, "")
yield from _format_row_any(row, attr)
return "\n".join(get())
| (self, attrname='name') |
23,025 | anytree.resolver | Resolver |
Resolve :any:`NodeMixin` paths using attribute `pathattr`.
Keyword Args:
name (str): Name of the node attribute to be used for resolving
ignorecase (bool): Enable case insensisitve handling.
relax (bool): Do not raise an exception.
| class Resolver:
"""
Resolve :any:`NodeMixin` paths using attribute `pathattr`.
Keyword Args:
name (str): Name of the node attribute to be used for resolving
ignorecase (bool): Enable case insensisitve handling.
relax (bool): Do not raise an exception.
"""
_match_cache = {}
def __init__(self, pathattr="name", ignorecase=False, relax=False):
super(Resolver, self).__init__()
self.pathattr = pathattr
self.ignorecase = ignorecase
self.relax = relax
def get(self, node, path):
"""
Return instance at `path`.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0sub0", parent=sub0)
>>> sub0sub1 = Node("sub0sub1", parent=sub0)
>>> sub1 = Node("sub1", parent=top)
A resolver using the `name` attribute:
>>> resolver = Resolver('name')
>>> relaxedresolver = Resolver('name', relax=True) # never generate exceptions
Relative paths:
>>> resolver.get(top, "sub0/sub0sub0")
Node('/top/sub0/sub0sub0')
>>> resolver.get(sub1, "..")
Node('/top')
>>> resolver.get(sub1, "../sub0/sub0sub1")
Node('/top/sub0/sub0sub1')
>>> resolver.get(sub1, ".")
Node('/top/sub1')
>>> resolver.get(sub1, "")
Node('/top/sub1')
>>> resolver.get(top, "sub2")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top') has no child sub2. Children are: 'sub0', 'sub1'.
>>> print(relaxedresolver.get(top, "sub2"))
None
Absolute paths:
>>> resolver.get(sub0sub0, "/top")
Node('/top')
>>> resolver.get(sub0sub0, "/top/sub0")
Node('/top/sub0')
>>> resolver.get(sub0sub0, "/")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: root node missing. root is '/top'.
>>> print(relaxedresolver.get(sub0sub0, "/"))
None
>>> resolver.get(sub0sub0, "/bar")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/bar'. root is '/top'.
>>> print(relaxedresolver.get(sub0sub0, "/bar"))
None
Going above the root node raises a :any:`RootResolverError`:
>>> resolver.get(top, "..")
Traceback (most recent call last):
...
anytree.resolver.RootResolverError: Cannot go above root node Node('/top')
.. note:: Please not that :any:`get()` returned `None` in exactly that case above,
which was a bug until version 1.8.1.
Case insensitive matching:
>>> resolver.get(top, '/TOP')
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/TOP'. root is '/top'.
>>> ignorecaseresolver = Resolver('name', ignorecase=True)
>>> ignorecaseresolver.get(top, '/TOp')
Node('/top')
"""
node, parts = self.__start(node, path, self.__cmp)
if node is None and self.relax:
return None
for part in parts:
if part == "..":
parent = node.parent
if parent is None:
if self.relax:
return None
raise RootResolverError(node)
node = parent
elif part in ("", "."):
pass
else:
node = self.__get(node, part)
return node
def __get(self, node, name):
namestr = str(name)
for child in node.children:
if self.__cmp(_getattr(child, self.pathattr), namestr):
return child
if self.relax:
return None
raise ChildResolverError(node, name, self.pathattr)
def glob(self, node, path):
"""
Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, except '/'.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0", parent=sub0)
>>> sub0sub1 = Node("sub1", parent=sub0)
>>> sub1 = Node("sub1", parent=top)
>>> sub1sub0 = Node("sub0", parent=sub1)
A resolver using the `name` attribute:
>>> resolver = Resolver('name')
>>> relaxedresolver = Resolver('name', relax=True) # never generate exceptions
Relative paths:
>>> resolver.glob(top, "sub0/sub?")
[Node('/top/sub0/sub0'), Node('/top/sub0/sub1')]
>>> resolver.glob(sub1, ".././*")
[Node('/top/sub0'), Node('/top/sub1')]
>>> resolver.glob(top, "*/*")
[Node('/top/sub0/sub0'), Node('/top/sub0/sub1'), Node('/top/sub1/sub0')]
>>> resolver.glob(top, "*/sub0")
[Node('/top/sub0/sub0'), Node('/top/sub1/sub0')]
>>> resolver.glob(top, "sub1/sub1")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top/sub1') has no child sub1. Children are: 'sub0'.
>>> relaxedresolver.glob(top, "sub1/sub1")
[]
Non-matching wildcards are no error:
>>> resolver.glob(top, "bar*")
[]
>>> resolver.glob(top, "sub2")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top') has no child sub2. Children are: 'sub0', 'sub1'.
>>> relaxedresolver.glob(top, "sub2")
[]
Absolute paths:
>>> resolver.glob(sub0sub0, "/top/*")
[Node('/top/sub0'), Node('/top/sub1')]
>>> resolver.glob(sub0sub0, "/")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: root node missing. root is '/top'.
>>> relaxedresolver.glob(sub0sub0, "/")
[]
>>> resolver.glob(sub0sub0, "/bar")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/bar'. root is '/top'.
Going above the root node raises a :any:`RootResolverError`:
>>> resolver.glob(top, "..")
Traceback (most recent call last):
...
anytree.resolver.RootResolverError: Cannot go above root node Node('/top')
>>> relaxedresolver.glob(top, "..")
[]
"""
node, parts = self.__start(node, path, self.__match)
if node is None and self.relax:
return []
return self.__glob(node, parts)
def __start(self, node, path, cmp_):
sep = node.separator
parts = path.split(sep)
# resolve root
if path.startswith(sep):
node = node.root
rootpart = _getattr(node, self.pathattr)
parts.pop(0)
if not parts[0]:
if self.relax:
return None, None
msg = "root node missing. root is '%s%s'."
raise ResolverError(node, "", msg % (sep, str(rootpart)))
if not cmp_(rootpart, parts[0]):
if self.relax:
return None, None
msg = "unknown root node '%s%s'. root is '%s%s'."
raise ResolverError(node, "", msg % (sep, parts[0], sep, str(rootpart)))
parts.pop(0)
return node, parts
def __glob(self, node, parts):
if ASSERTIONS: # pragma: no branch
assert node is not None
if not parts:
return [node]
name = parts[0]
remainder = parts[1:]
# handle relative
if name == "..":
parent = node.parent
if parent is None:
if self.relax:
return []
raise RootResolverError(node)
return self.__glob(parent, remainder)
if name in ("", "."):
return self.__glob(node, remainder)
# handle recursive
if name == "**":
matches = []
for subnode in PreOrderIter(node):
try:
for match in self.__glob(subnode, remainder):
if match not in matches:
matches.append(match)
except ChildResolverError:
pass
return matches
matches = self.__find(node, name, remainder)
if not matches and not Resolver.is_wildcard(name) and not self.relax:
raise ChildResolverError(node, name, self.pathattr)
return matches
def __find(self, node, pat, remainder):
matches = []
for child in node.children:
name = _getattr(child, self.pathattr)
try:
if self.__match(name, pat):
if remainder:
matches += self.__glob(child, remainder)
else:
matches.append(child)
except ResolverError as exc:
if not Resolver.is_wildcard(pat):
raise exc
return matches
@staticmethod
def is_wildcard(path):
"""Return `True` is a wildcard."""
return "?" in path or "*" in path
def __match(self, name, pat):
k = (pat, self.ignorecase)
try:
re_pat = Resolver._match_cache[k]
except KeyError:
res = Resolver.__translate(pat)
if len(Resolver._match_cache) >= _MAXCACHE:
Resolver._match_cache.clear()
flags = 0
if self.ignorecase:
flags |= re.IGNORECASE
Resolver._match_cache[k] = re_pat = re.compile(res, flags=flags)
return re_pat.match(name) is not None
def __cmp(self, name, pat):
if self.ignorecase:
return name.upper() == pat.upper()
return name == pat
@staticmethod
def __translate(pat):
re_pat = ""
for char in pat:
if char == "*":
re_pat += ".*"
elif char == "?":
re_pat += "."
else:
re_pat += re.escape(char)
return r"(?ms)" + re_pat + r"\Z"
| (pathattr='name', ignorecase=False, relax=False) |
23,026 | anytree.resolver | __cmp | null | def __cmp(self, name, pat):
if self.ignorecase:
return name.upper() == pat.upper()
return name == pat
| (self, name, pat) |
23,027 | anytree.resolver | __find | null | def __find(self, node, pat, remainder):
matches = []
for child in node.children:
name = _getattr(child, self.pathattr)
try:
if self.__match(name, pat):
if remainder:
matches += self.__glob(child, remainder)
else:
matches.append(child)
except ResolverError as exc:
if not Resolver.is_wildcard(pat):
raise exc
return matches
| (self, node, pat, remainder) |
23,028 | anytree.resolver | __get | null | def __get(self, node, name):
namestr = str(name)
for child in node.children:
if self.__cmp(_getattr(child, self.pathattr), namestr):
return child
if self.relax:
return None
raise ChildResolverError(node, name, self.pathattr)
| (self, node, name) |
23,029 | anytree.resolver | __glob | null | def __glob(self, node, parts):
if ASSERTIONS: # pragma: no branch
assert node is not None
if not parts:
return [node]
name = parts[0]
remainder = parts[1:]
# handle relative
if name == "..":
parent = node.parent
if parent is None:
if self.relax:
return []
raise RootResolverError(node)
return self.__glob(parent, remainder)
if name in ("", "."):
return self.__glob(node, remainder)
# handle recursive
if name == "**":
matches = []
for subnode in PreOrderIter(node):
try:
for match in self.__glob(subnode, remainder):
if match not in matches:
matches.append(match)
except ChildResolverError:
pass
return matches
matches = self.__find(node, name, remainder)
if not matches and not Resolver.is_wildcard(name) and not self.relax:
raise ChildResolverError(node, name, self.pathattr)
return matches
| (self, node, parts) |
23,030 | anytree.resolver | __match | null | def __match(self, name, pat):
k = (pat, self.ignorecase)
try:
re_pat = Resolver._match_cache[k]
except KeyError:
res = Resolver.__translate(pat)
if len(Resolver._match_cache) >= _MAXCACHE:
Resolver._match_cache.clear()
flags = 0
if self.ignorecase:
flags |= re.IGNORECASE
Resolver._match_cache[k] = re_pat = re.compile(res, flags=flags)
return re_pat.match(name) is not None
| (self, name, pat) |
23,031 | anytree.resolver | __start | null | def __start(self, node, path, cmp_):
sep = node.separator
parts = path.split(sep)
# resolve root
if path.startswith(sep):
node = node.root
rootpart = _getattr(node, self.pathattr)
parts.pop(0)
if not parts[0]:
if self.relax:
return None, None
msg = "root node missing. root is '%s%s'."
raise ResolverError(node, "", msg % (sep, str(rootpart)))
if not cmp_(rootpart, parts[0]):
if self.relax:
return None, None
msg = "unknown root node '%s%s'. root is '%s%s'."
raise ResolverError(node, "", msg % (sep, parts[0], sep, str(rootpart)))
parts.pop(0)
return node, parts
| (self, node, path, cmp_) |
23,032 | anytree.resolver | __translate | null | @staticmethod
def __translate(pat):
re_pat = ""
for char in pat:
if char == "*":
re_pat += ".*"
elif char == "?":
re_pat += "."
else:
re_pat += re.escape(char)
return r"(?ms)" + re_pat + r"\Z"
| (pat) |
23,033 | anytree.resolver | __init__ | null | def __init__(self, pathattr="name", ignorecase=False, relax=False):
super(Resolver, self).__init__()
self.pathattr = pathattr
self.ignorecase = ignorecase
self.relax = relax
| (self, pathattr='name', ignorecase=False, relax=False) |
23,034 | anytree.resolver | get |
Return instance at `path`.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0sub0", parent=sub0)
>>> sub0sub1 = Node("sub0sub1", parent=sub0)
>>> sub1 = Node("sub1", parent=top)
A resolver using the `name` attribute:
>>> resolver = Resolver('name')
>>> relaxedresolver = Resolver('name', relax=True) # never generate exceptions
Relative paths:
>>> resolver.get(top, "sub0/sub0sub0")
Node('/top/sub0/sub0sub0')
>>> resolver.get(sub1, "..")
Node('/top')
>>> resolver.get(sub1, "../sub0/sub0sub1")
Node('/top/sub0/sub0sub1')
>>> resolver.get(sub1, ".")
Node('/top/sub1')
>>> resolver.get(sub1, "")
Node('/top/sub1')
>>> resolver.get(top, "sub2")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top') has no child sub2. Children are: 'sub0', 'sub1'.
>>> print(relaxedresolver.get(top, "sub2"))
None
Absolute paths:
>>> resolver.get(sub0sub0, "/top")
Node('/top')
>>> resolver.get(sub0sub0, "/top/sub0")
Node('/top/sub0')
>>> resolver.get(sub0sub0, "/")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: root node missing. root is '/top'.
>>> print(relaxedresolver.get(sub0sub0, "/"))
None
>>> resolver.get(sub0sub0, "/bar")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/bar'. root is '/top'.
>>> print(relaxedresolver.get(sub0sub0, "/bar"))
None
Going above the root node raises a :any:`RootResolverError`:
>>> resolver.get(top, "..")
Traceback (most recent call last):
...
anytree.resolver.RootResolverError: Cannot go above root node Node('/top')
.. note:: Please not that :any:`get()` returned `None` in exactly that case above,
which was a bug until version 1.8.1.
Case insensitive matching:
>>> resolver.get(top, '/TOP')
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/TOP'. root is '/top'.
>>> ignorecaseresolver = Resolver('name', ignorecase=True)
>>> ignorecaseresolver.get(top, '/TOp')
Node('/top')
| def get(self, node, path):
"""
Return instance at `path`.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0sub0", parent=sub0)
>>> sub0sub1 = Node("sub0sub1", parent=sub0)
>>> sub1 = Node("sub1", parent=top)
A resolver using the `name` attribute:
>>> resolver = Resolver('name')
>>> relaxedresolver = Resolver('name', relax=True) # never generate exceptions
Relative paths:
>>> resolver.get(top, "sub0/sub0sub0")
Node('/top/sub0/sub0sub0')
>>> resolver.get(sub1, "..")
Node('/top')
>>> resolver.get(sub1, "../sub0/sub0sub1")
Node('/top/sub0/sub0sub1')
>>> resolver.get(sub1, ".")
Node('/top/sub1')
>>> resolver.get(sub1, "")
Node('/top/sub1')
>>> resolver.get(top, "sub2")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top') has no child sub2. Children are: 'sub0', 'sub1'.
>>> print(relaxedresolver.get(top, "sub2"))
None
Absolute paths:
>>> resolver.get(sub0sub0, "/top")
Node('/top')
>>> resolver.get(sub0sub0, "/top/sub0")
Node('/top/sub0')
>>> resolver.get(sub0sub0, "/")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: root node missing. root is '/top'.
>>> print(relaxedresolver.get(sub0sub0, "/"))
None
>>> resolver.get(sub0sub0, "/bar")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/bar'. root is '/top'.
>>> print(relaxedresolver.get(sub0sub0, "/bar"))
None
Going above the root node raises a :any:`RootResolverError`:
>>> resolver.get(top, "..")
Traceback (most recent call last):
...
anytree.resolver.RootResolverError: Cannot go above root node Node('/top')
.. note:: Please not that :any:`get()` returned `None` in exactly that case above,
which was a bug until version 1.8.1.
Case insensitive matching:
>>> resolver.get(top, '/TOP')
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/TOP'. root is '/top'.
>>> ignorecaseresolver = Resolver('name', ignorecase=True)
>>> ignorecaseresolver.get(top, '/TOp')
Node('/top')
"""
node, parts = self.__start(node, path, self.__cmp)
if node is None and self.relax:
return None
for part in parts:
if part == "..":
parent = node.parent
if parent is None:
if self.relax:
return None
raise RootResolverError(node)
node = parent
elif part in ("", "."):
pass
else:
node = self.__get(node, part)
return node
| (self, node, path) |
23,035 | anytree.resolver | glob |
Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, except '/'.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0", parent=sub0)
>>> sub0sub1 = Node("sub1", parent=sub0)
>>> sub1 = Node("sub1", parent=top)
>>> sub1sub0 = Node("sub0", parent=sub1)
A resolver using the `name` attribute:
>>> resolver = Resolver('name')
>>> relaxedresolver = Resolver('name', relax=True) # never generate exceptions
Relative paths:
>>> resolver.glob(top, "sub0/sub?")
[Node('/top/sub0/sub0'), Node('/top/sub0/sub1')]
>>> resolver.glob(sub1, ".././*")
[Node('/top/sub0'), Node('/top/sub1')]
>>> resolver.glob(top, "*/*")
[Node('/top/sub0/sub0'), Node('/top/sub0/sub1'), Node('/top/sub1/sub0')]
>>> resolver.glob(top, "*/sub0")
[Node('/top/sub0/sub0'), Node('/top/sub1/sub0')]
>>> resolver.glob(top, "sub1/sub1")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top/sub1') has no child sub1. Children are: 'sub0'.
>>> relaxedresolver.glob(top, "sub1/sub1")
[]
Non-matching wildcards are no error:
>>> resolver.glob(top, "bar*")
[]
>>> resolver.glob(top, "sub2")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top') has no child sub2. Children are: 'sub0', 'sub1'.
>>> relaxedresolver.glob(top, "sub2")
[]
Absolute paths:
>>> resolver.glob(sub0sub0, "/top/*")
[Node('/top/sub0'), Node('/top/sub1')]
>>> resolver.glob(sub0sub0, "/")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: root node missing. root is '/top'.
>>> relaxedresolver.glob(sub0sub0, "/")
[]
>>> resolver.glob(sub0sub0, "/bar")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/bar'. root is '/top'.
Going above the root node raises a :any:`RootResolverError`:
>>> resolver.glob(top, "..")
Traceback (most recent call last):
...
anytree.resolver.RootResolverError: Cannot go above root node Node('/top')
>>> relaxedresolver.glob(top, "..")
[]
| def glob(self, node, path):
"""
Return instances at `path` supporting wildcards.
Behaves identical to :any:`get`, but accepts wildcards and returns
a list of found nodes.
* `*` matches any characters, except '/'.
* `?` matches a single character, except '/'.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0", parent=sub0)
>>> sub0sub1 = Node("sub1", parent=sub0)
>>> sub1 = Node("sub1", parent=top)
>>> sub1sub0 = Node("sub0", parent=sub1)
A resolver using the `name` attribute:
>>> resolver = Resolver('name')
>>> relaxedresolver = Resolver('name', relax=True) # never generate exceptions
Relative paths:
>>> resolver.glob(top, "sub0/sub?")
[Node('/top/sub0/sub0'), Node('/top/sub0/sub1')]
>>> resolver.glob(sub1, ".././*")
[Node('/top/sub0'), Node('/top/sub1')]
>>> resolver.glob(top, "*/*")
[Node('/top/sub0/sub0'), Node('/top/sub0/sub1'), Node('/top/sub1/sub0')]
>>> resolver.glob(top, "*/sub0")
[Node('/top/sub0/sub0'), Node('/top/sub1/sub0')]
>>> resolver.glob(top, "sub1/sub1")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top/sub1') has no child sub1. Children are: 'sub0'.
>>> relaxedresolver.glob(top, "sub1/sub1")
[]
Non-matching wildcards are no error:
>>> resolver.glob(top, "bar*")
[]
>>> resolver.glob(top, "sub2")
Traceback (most recent call last):
...
anytree.resolver.ChildResolverError: Node('/top') has no child sub2. Children are: 'sub0', 'sub1'.
>>> relaxedresolver.glob(top, "sub2")
[]
Absolute paths:
>>> resolver.glob(sub0sub0, "/top/*")
[Node('/top/sub0'), Node('/top/sub1')]
>>> resolver.glob(sub0sub0, "/")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: root node missing. root is '/top'.
>>> relaxedresolver.glob(sub0sub0, "/")
[]
>>> resolver.glob(sub0sub0, "/bar")
Traceback (most recent call last):
...
anytree.resolver.ResolverError: unknown root node '/bar'. root is '/top'.
Going above the root node raises a :any:`RootResolverError`:
>>> resolver.glob(top, "..")
Traceback (most recent call last):
...
anytree.resolver.RootResolverError: Cannot go above root node Node('/top')
>>> relaxedresolver.glob(top, "..")
[]
"""
node, parts = self.__start(node, path, self.__match)
if node is None and self.relax:
return []
return self.__glob(node, parts)
| (self, node, path) |
23,036 | anytree.resolver | is_wildcard | Return `True` is a wildcard. | @staticmethod
def is_wildcard(path):
"""Return `True` is a wildcard."""
return "?" in path or "*" in path
| (path) |
23,037 | anytree.resolver | ResolverError | null | class ResolverError(RuntimeError):
def __init__(self, node, child, msg):
"""Resolve Error at `node` handling `child`."""
super(ResolverError, self).__init__(msg)
self.node = node
self.child = child
| (node, child, msg) |
23,038 | anytree.resolver | __init__ | Resolve Error at `node` handling `child`. | def __init__(self, node, child, msg):
"""Resolve Error at `node` handling `child`."""
super(ResolverError, self).__init__(msg)
self.node = node
self.child = child
| (self, node, child, msg) |
23,039 | anytree.resolver | RootResolverError | null | class RootResolverError(ResolverError):
def __init__(self, root):
"""Root Resolve Error, cannot go above root node."""
msg = "Cannot go above root node %r" % (root,)
super(RootResolverError, self).__init__(root, None, msg)
| (root) |
23,040 | anytree.resolver | __init__ | Root Resolve Error, cannot go above root node. | def __init__(self, root):
"""Root Resolve Error, cannot go above root node."""
msg = "Cannot go above root node %r" % (root,)
super(RootResolverError, self).__init__(root, None, msg)
| (self, root) |
23,041 | anytree.node.symlinknode | SymlinkNode |
Tree node which references to another tree node.
Args:
target: Symbolic Link Target. Another tree node, which is refered to.
Keyword Args:
parent: Reference to parent node.
children: Iterable with child nodes.
*: Any other given attribute is just stored as attribute **in** `target`.
The :any:`SymlinkNode` has its own parent and its own child nodes.
All other attribute accesses are just forwarded to the target node.
>>> from anytree import SymlinkNode, Node, RenderTree
>>> root = Node("root")
>>> s1 = Node("sub1", parent=root, bar=17)
>>> l = SymlinkNode(s1, parent=root, baz=18)
>>> l0 = Node("l0", parent=l)
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub1', bar=17, baz=18)
βββ SymlinkNode(Node('/root/sub1', bar=17, baz=18))
βββ Node('/root/sub1/l0')
Any modifications on the target node are also available on the linked node and vice-versa:
>>> s1.foo = 4
>>> s1.foo
4
>>> l.foo
4
>>> l.foo = 9
>>> s1.foo
9
>>> l.foo
9
| class SymlinkNode(SymlinkNodeMixin):
"""
Tree node which references to another tree node.
Args:
target: Symbolic Link Target. Another tree node, which is refered to.
Keyword Args:
parent: Reference to parent node.
children: Iterable with child nodes.
*: Any other given attribute is just stored as attribute **in** `target`.
The :any:`SymlinkNode` has its own parent and its own child nodes.
All other attribute accesses are just forwarded to the target node.
>>> from anytree import SymlinkNode, Node, RenderTree
>>> root = Node("root")
>>> s1 = Node("sub1", parent=root, bar=17)
>>> l = SymlinkNode(s1, parent=root, baz=18)
>>> l0 = Node("l0", parent=l)
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub1', bar=17, baz=18)
βββ SymlinkNode(Node('/root/sub1', bar=17, baz=18))
βββ Node('/root/sub1/l0')
Any modifications on the target node are also available on the linked node and vice-versa:
>>> s1.foo = 4
>>> s1.foo
4
>>> l.foo
4
>>> l.foo = 9
>>> s1.foo
9
>>> l.foo
9
"""
def __init__(self, target, parent=None, children=None, **kwargs):
self.target = target
self.target.__dict__.update(kwargs)
self.parent = parent
if children:
self.children = children
def __repr__(self):
return _repr(self, [repr(self.target)], nameblacklist=("target",))
| (target, parent=None, children=None, **kwargs) |
23,046 | anytree.node.symlinknodemixin | __getattr__ | null | def __getattr__(self, name):
if name in ("_NodeMixin__parent", "_NodeMixin__children"):
return super(SymlinkNodeMixin, self).__getattr__(name)
if name == "__setstate__":
raise AttributeError(name)
return getattr(self.target, name)
| (self, name) |
23,047 | anytree.node.symlinknode | __init__ | null | def __init__(self, target, parent=None, children=None, **kwargs):
self.target = target
self.target.__dict__.update(kwargs)
self.parent = parent
if children:
self.children = children
| (self, target, parent=None, children=None, **kwargs) |
23,048 | anytree.node.symlinknode | __repr__ | null | def __repr__(self):
return _repr(self, [repr(self.target)], nameblacklist=("target",))
| (self) |
23,049 | anytree.node.symlinknodemixin | __setattr__ | null | def __setattr__(self, name, value):
if name in ("_NodeMixin__parent", "_NodeMixin__children", "parent", "children", "target"):
super(SymlinkNodeMixin, self).__setattr__(name, value)
else:
setattr(self.target, name, value)
| (self, name, value) |
23,059 | anytree.node.symlinknodemixin | SymlinkNodeMixin |
The :any:`SymlinkNodeMixin` class extends any Python class to a symbolic link to a tree node.
The class **MUST** have a `target` attribute refering to another tree node.
The :any:`SymlinkNodeMixin` class has its own parent and its own child nodes.
All other attribute accesses are just forwarded to the target node.
A minimal implementation looks like (see :any:`SymlinkNode` for a full implemenation):
>>> from anytree import SymlinkNodeMixin, Node, RenderTree
>>> class SymlinkNode(SymlinkNodeMixin):
... def __init__(self, target, parent=None, children=None):
... self.target = target
... self.parent = parent
... if children:
... self.children = children
... def __repr__(self):
... return "SymlinkNode(%r)" % (self.target)
>>> root = Node("root")
>>> s1 = Node("sub1", parent=root)
>>> l = SymlinkNode(s1, parent=root)
>>> l0 = Node("l0", parent=l)
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub1')
βββ SymlinkNode(Node('/root/sub1'))
βββ Node('/root/sub1/l0')
Any modifications on the target node are also available on the linked node and vice-versa:
>>> s1.foo = 4
>>> s1.foo
4
>>> l.foo
4
>>> l.foo = 9
>>> s1.foo
9
>>> l.foo
9
| class SymlinkNodeMixin(NodeMixin):
"""
The :any:`SymlinkNodeMixin` class extends any Python class to a symbolic link to a tree node.
The class **MUST** have a `target` attribute refering to another tree node.
The :any:`SymlinkNodeMixin` class has its own parent and its own child nodes.
All other attribute accesses are just forwarded to the target node.
A minimal implementation looks like (see :any:`SymlinkNode` for a full implemenation):
>>> from anytree import SymlinkNodeMixin, Node, RenderTree
>>> class SymlinkNode(SymlinkNodeMixin):
... def __init__(self, target, parent=None, children=None):
... self.target = target
... self.parent = parent
... if children:
... self.children = children
... def __repr__(self):
... return "SymlinkNode(%r)" % (self.target)
>>> root = Node("root")
>>> s1 = Node("sub1", parent=root)
>>> l = SymlinkNode(s1, parent=root)
>>> l0 = Node("l0", parent=l)
>>> print(RenderTree(root))
Node('/root')
βββ Node('/root/sub1')
βββ SymlinkNode(Node('/root/sub1'))
βββ Node('/root/sub1/l0')
Any modifications on the target node are also available on the linked node and vice-versa:
>>> s1.foo = 4
>>> s1.foo
4
>>> l.foo
4
>>> l.foo = 9
>>> s1.foo
9
>>> l.foo
9
"""
def __getattr__(self, name):
if name in ("_NodeMixin__parent", "_NodeMixin__children"):
return super(SymlinkNodeMixin, self).__getattr__(name)
if name == "__setstate__":
raise AttributeError(name)
return getattr(self.target, name)
def __setattr__(self, name, value):
if name in ("_NodeMixin__parent", "_NodeMixin__children", "parent", "children", "target"):
super(SymlinkNodeMixin, self).__setattr__(name, value)
else:
setattr(self.target, name, value)
| () |
23,075 | anytree.node.exceptions | TreeError | Tree Error. | class TreeError(RuntimeError):
"""Tree Error."""
| null |
23,076 | anytree.walker | WalkError | Walk Error. | class WalkError(RuntimeError):
"""Walk Error."""
| null |
23,077 | anytree.walker | Walker | Walk from one node to another. | class Walker:
"""Walk from one node to another."""
@staticmethod
def walk(start, end):
"""
Walk from `start` node to `end` node.
Returns:
(upwards, common, downwards): `upwards` is a list of nodes to go upward to.
`common` top node. `downwards` is a list of nodes to go downward to.
Raises:
WalkError: on no common root node.
Example:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()))
Node('/f')
|-- Node('/f/b')
| |-- Node('/f/b/a')
| +-- Node('/f/b/d')
| |-- Node('/f/b/d/c')
| +-- Node('/f/b/d/e')
+-- Node('/f/g')
+-- Node('/f/g/i')
+-- Node('/f/g/i/h')
Create a walker:
>>> w = Walker()
This class is made for walking:
>>> w.walk(f, f)
((), Node('/f'), ())
>>> w.walk(f, b)
((), Node('/f'), (Node('/f/b'),))
>>> w.walk(b, f)
((Node('/f/b'),), Node('/f'), ())
>>> w.walk(h, e)
((Node('/f/g/i/h'), Node('/f/g/i'), Node('/f/g')), Node('/f'), (Node('/f/b'), Node('/f/b/d'), Node('/f/b/d/e')))
>>> w.walk(d, e)
((), Node('/f/b/d'), (Node('/f/b/d/e'),))
For a proper walking the nodes need to be part of the same tree:
>>> w.walk(Node("a"), Node("b"))
Traceback (most recent call last):
...
anytree.walker.WalkError: Node('/a') and Node('/b') are not part of the same tree.
"""
startpath = start.path
endpath = end.path
if start.root is not end.root:
msg = "%r and %r are not part of the same tree." % (start, end)
raise WalkError(msg)
# common
common = Walker.__calc_common(startpath, endpath)
if ASSERTIONS: # pragma: no branch
assert common[0] is start.root
len_common = len(common)
# upwards
if start is common[-1]:
upwards = tuple()
else:
upwards = tuple(reversed(startpath[len_common:]))
# down
if end is common[-1]:
down = tuple()
else:
down = endpath[len_common:]
return upwards, common[-1], down
@staticmethod
def __calc_common(start, end):
return tuple(si for si, ei in zip(start, end) if si is ei)
| () |
23,078 | anytree.walker | __calc_common | null | @staticmethod
def __calc_common(start, end):
return tuple(si for si, ei in zip(start, end) if si is ei)
| (start, end) |
23,079 | anytree.walker | walk |
Walk from `start` node to `end` node.
Returns:
(upwards, common, downwards): `upwards` is a list of nodes to go upward to.
`common` top node. `downwards` is a list of nodes to go downward to.
Raises:
WalkError: on no common root node.
Example:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()))
Node('/f')
|-- Node('/f/b')
| |-- Node('/f/b/a')
| +-- Node('/f/b/d')
| |-- Node('/f/b/d/c')
| +-- Node('/f/b/d/e')
+-- Node('/f/g')
+-- Node('/f/g/i')
+-- Node('/f/g/i/h')
Create a walker:
>>> w = Walker()
This class is made for walking:
>>> w.walk(f, f)
((), Node('/f'), ())
>>> w.walk(f, b)
((), Node('/f'), (Node('/f/b'),))
>>> w.walk(b, f)
((Node('/f/b'),), Node('/f'), ())
>>> w.walk(h, e)
((Node('/f/g/i/h'), Node('/f/g/i'), Node('/f/g')), Node('/f'), (Node('/f/b'), Node('/f/b/d'), Node('/f/b/d/e')))
>>> w.walk(d, e)
((), Node('/f/b/d'), (Node('/f/b/d/e'),))
For a proper walking the nodes need to be part of the same tree:
>>> w.walk(Node("a"), Node("b"))
Traceback (most recent call last):
...
anytree.walker.WalkError: Node('/a') and Node('/b') are not part of the same tree.
| @staticmethod
def walk(start, end):
"""
Walk from `start` node to `end` node.
Returns:
(upwards, common, downwards): `upwards` is a list of nodes to go upward to.
`common` top node. `downwards` is a list of nodes to go downward to.
Raises:
WalkError: on no common root node.
Example:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()))
Node('/f')
|-- Node('/f/b')
| |-- Node('/f/b/a')
| +-- Node('/f/b/d')
| |-- Node('/f/b/d/c')
| +-- Node('/f/b/d/e')
+-- Node('/f/g')
+-- Node('/f/g/i')
+-- Node('/f/g/i/h')
Create a walker:
>>> w = Walker()
This class is made for walking:
>>> w.walk(f, f)
((), Node('/f'), ())
>>> w.walk(f, b)
((), Node('/f'), (Node('/f/b'),))
>>> w.walk(b, f)
((Node('/f/b'),), Node('/f'), ())
>>> w.walk(h, e)
((Node('/f/g/i/h'), Node('/f/g/i'), Node('/f/g')), Node('/f'), (Node('/f/b'), Node('/f/b/d'), Node('/f/b/d/e')))
>>> w.walk(d, e)
((), Node('/f/b/d'), (Node('/f/b/d/e'),))
For a proper walking the nodes need to be part of the same tree:
>>> w.walk(Node("a"), Node("b"))
Traceback (most recent call last):
...
anytree.walker.WalkError: Node('/a') and Node('/b') are not part of the same tree.
"""
startpath = start.path
endpath = end.path
if start.root is not end.root:
msg = "%r and %r are not part of the same tree." % (start, end)
raise WalkError(msg)
# common
common = Walker.__calc_common(startpath, endpath)
if ASSERTIONS: # pragma: no branch
assert common[0] is start.root
len_common = len(common)
# upwards
if start is common[-1]:
upwards = tuple()
else:
upwards = tuple(reversed(startpath[len_common:]))
# down
if end is common[-1]:
down = tuple()
else:
down = endpath[len_common:]
return upwards, common[-1], down
| (start, end) |
23,080 | anytree.iterators.zigzaggroupiter | ZigZagGroupIter |
Iterate over tree applying Zig-Zag strategy with grouping starting at `node`.
Return a tuple of nodes for each level. The first tuple contains the
nodes at level 0 (always `node`). The second tuple contains the nodes at level 1
(children of `node`) in reversed order.
The next level contains the children of the children in forward order, and so on.
>>> from anytree import Node, RenderTree, AsciiStyle, ZigZagGroupIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [[node.name for node in children] for children in ZigZagGroupIter(f)]
[['f'], ['g', 'b'], ['a', 'd', 'i'], ['h', 'e', 'c']]
>>> [[node.name for node in children] for children in ZigZagGroupIter(f, maxlevel=3)]
[['f'], ['g', 'b'], ['a', 'd', 'i']]
>>> [[node.name for node in children]
... for children in ZigZagGroupIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
[['f'], ['b'], ['a', 'd', 'i'], ['h', 'c']]
>>> [[node.name for node in children]
... for children in ZigZagGroupIter(f, stop=lambda n: n.name == 'd')]
[['f'], ['g', 'b'], ['a', 'i'], ['h']]
| class ZigZagGroupIter(AbstractIter):
"""
Iterate over tree applying Zig-Zag strategy with grouping starting at `node`.
Return a tuple of nodes for each level. The first tuple contains the
nodes at level 0 (always `node`). The second tuple contains the nodes at level 1
(children of `node`) in reversed order.
The next level contains the children of the children in forward order, and so on.
>>> from anytree import Node, RenderTree, AsciiStyle, ZigZagGroupIter
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> [[node.name for node in children] for children in ZigZagGroupIter(f)]
[['f'], ['g', 'b'], ['a', 'd', 'i'], ['h', 'e', 'c']]
>>> [[node.name for node in children] for children in ZigZagGroupIter(f, maxlevel=3)]
[['f'], ['g', 'b'], ['a', 'd', 'i']]
>>> [[node.name for node in children]
... for children in ZigZagGroupIter(f, filter_=lambda n: n.name not in ('e', 'g'))]
[['f'], ['b'], ['a', 'd', 'i'], ['h', 'c']]
>>> [[node.name for node in children]
... for children in ZigZagGroupIter(f, stop=lambda n: n.name == 'd')]
[['f'], ['g', 'b'], ['a', 'i'], ['h']]
"""
@staticmethod
def _iter(children, filter_, stop, maxlevel):
if children:
if ASSERTIONS: # pragma: no branch
assert len(children) == 1
_iter = LevelOrderGroupIter(children[0], filter_, stop, maxlevel)
while True:
try:
yield next(_iter)
yield tuple(reversed(next(_iter)))
except StopIteration:
break
| (node, filter_=None, stop=None, maxlevel=None) |
23,089 | anytree.iterators.zigzaggroupiter | _iter | null | @staticmethod
def _iter(children, filter_, stop, maxlevel):
if children:
if ASSERTIONS: # pragma: no branch
assert len(children) == 1
_iter = LevelOrderGroupIter(children[0], filter_, stop, maxlevel)
while True:
try:
yield next(_iter)
yield tuple(reversed(next(_iter)))
except StopIteration:
break
| (children, filter_, stop, maxlevel) |
23,092 | anytree.search | find |
Search for *single* node matching `filter_` but stop at `maxlevel` or `stop`.
Return matching node.
Args:
node: top node, start searching.
Keyword Args:
filter_: function called with every `node` as argument, `node` is returned if `True`.
stop: stop iteration at `node` if `stop` function returns `True` for `node`.
maxlevel (int): maximum descending in the node hierarchy.
Example tree:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> find(f, lambda node: node.name == "d")
Node('/f/b/d')
>>> find(f, lambda node: node.name == "z")
>>> find(f, lambda node: b in node.path) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
anytree.search.CountError: Expecting 1 elements at maximum, but found 5. (Node('/f/b')... Node('/f/b/d/e'))
| def find(node, filter_=None, stop=None, maxlevel=None):
"""
Search for *single* node matching `filter_` but stop at `maxlevel` or `stop`.
Return matching node.
Args:
node: top node, start searching.
Keyword Args:
filter_: function called with every `node` as argument, `node` is returned if `True`.
stop: stop iteration at `node` if `stop` function returns `True` for `node`.
maxlevel (int): maximum descending in the node hierarchy.
Example tree:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> find(f, lambda node: node.name == "d")
Node('/f/b/d')
>>> find(f, lambda node: node.name == "z")
>>> find(f, lambda node: b in node.path) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
anytree.search.CountError: Expecting 1 elements at maximum, but found 5. (Node('/f/b')... Node('/f/b/d/e'))
"""
return _find(node, filter_=filter_, stop=stop, maxlevel=maxlevel)
| (node, filter_=None, stop=None, maxlevel=None) |
23,093 | anytree.search | find_by_attr |
Search for *single* node with attribute `name` having `value` but stop at `maxlevel`.
Return matching node.
Args:
node: top node, start searching.
value: value which need to match
Keyword Args:
name (str): attribute name need to match
maxlevel (int): maximum descending in the node hierarchy.
Example tree:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d, foo=4)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> find_by_attr(f, "d")
Node('/f/b/d')
>>> find_by_attr(f, name="foo", value=4)
Node('/f/b/d/c', foo=4)
>>> find_by_attr(f, name="foo", value=8)
| def find_by_attr(node, value, name="name", maxlevel=None):
"""
Search for *single* node with attribute `name` having `value` but stop at `maxlevel`.
Return matching node.
Args:
node: top node, start searching.
value: value which need to match
Keyword Args:
name (str): attribute name need to match
maxlevel (int): maximum descending in the node hierarchy.
Example tree:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d, foo=4)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> find_by_attr(f, "d")
Node('/f/b/d')
>>> find_by_attr(f, name="foo", value=4)
Node('/f/b/d/c', foo=4)
>>> find_by_attr(f, name="foo", value=8)
"""
return _find(node, filter_=lambda n: _filter_by_name(n, name, value), maxlevel=maxlevel)
| (node, value, name='name', maxlevel=None) |
23,094 | anytree.search | findall |
Search nodes matching `filter_` but stop at `maxlevel` or `stop`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
Keyword Args:
filter_: function called with every `node` as argument, `node` is returned if `True`.
stop: stop iteration at `node` if `stop` function returns `True` for `node`.
maxlevel (int): maximum descending in the node hierarchy.
mincount (int): minimum number of nodes.
maxcount (int): maximum number of nodes.
Example tree:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> findall(f, filter_=lambda node: node.name in ("a", "b"))
(Node('/f/b'), Node('/f/b/a'))
>>> findall(f, filter_=lambda node: d in node.path)
(Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))
The number of matches can be limited:
>>> findall(f, filter_=lambda node: d in node.path, mincount=4) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
anytree.search.CountError: Expecting at least 4 elements, but found 3. ... Node('/f/b/d/e'))
>>> findall(f, filter_=lambda node: d in node.path, maxcount=2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
anytree.search.CountError: Expecting 2 elements at maximum, but found 3. ... Node('/f/b/d/e'))
| def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None):
"""
Search nodes matching `filter_` but stop at `maxlevel` or `stop`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
Keyword Args:
filter_: function called with every `node` as argument, `node` is returned if `True`.
stop: stop iteration at `node` if `stop` function returns `True` for `node`.
maxlevel (int): maximum descending in the node hierarchy.
mincount (int): minimum number of nodes.
maxcount (int): maximum number of nodes.
Example tree:
>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
>>> findall(f, filter_=lambda node: node.name in ("a", "b"))
(Node('/f/b'), Node('/f/b/a'))
>>> findall(f, filter_=lambda node: d in node.path)
(Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))
The number of matches can be limited:
>>> findall(f, filter_=lambda node: d in node.path, mincount=4) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
anytree.search.CountError: Expecting at least 4 elements, but found 3. ... Node('/f/b/d/e'))
>>> findall(f, filter_=lambda node: d in node.path, maxcount=2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
anytree.search.CountError: Expecting 2 elements at maximum, but found 3. ... Node('/f/b/d/e'))
"""
return _findall(node, filter_=filter_, stop=stop, maxlevel=maxlevel, mincount=mincount, maxcount=maxcount)
| (node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.