delb¶
delb
is a library that provides an ergonomic model for XML encoded text
documents (e.g. TEI-XML) for the Python programming language.
It fills a gap for the humanities-related field of software development towards
the excellent (scientific) communities in the Python ecosystem.
For a more elaborated discussion see the Design chapter of the documentation.
Features¶
Loads documents from various source types. This is customizable and extensible.
XML DOM types are represented by distinct classes.
A completely type-annotated API.
Consistent design regarding names and callables’ signatures.
Shadows comments and processing instructions by default.
Querying with XPath and CSS expressions.
Development status¶
You’re invited to submit tests that reflect desired use cases or are merely of theoretical nature. Of course, any kind of proposals for or implementations of improvements are welcome as well.
Related Projects & Testimonials¶
snakesist is an eXist-db client that uses delb
to expose database
resources.
Kurt Raschke noted in 2010:
In a DOM-based implementation, it would be relatively easy […]
But lxml doesn't use text nodes; instead it uses [text] and [tail]
properties to hold text content.
About the design¶
tl;dr¶
lxml resp. libxml2 are powerful tools, but have an unergonomic data model to work with encoded text. Let’s build a DOM API inspired wrapper around it.
Aspects & Caveats¶
The library is partly opinionated to encourage good practices and to be more pythonic. Therefore its behaviour deviates from lxml and ignores stuff:
Serializations of documents are UTF-8 encoded by default and always start with an XML declaration.
Comment and processing instruction nodes are shadowed by default, see
delb.altered_default_filters()
on how to make them accessible.CDATA nodes are not accessible at all, but are retained and appear in serializations; unless you [DANGER ZONE] manipulate the tree. Depending on your actions you might encounter no alterations or a complete loss of these nodes within the root node. [/DANGER ZONE]
If you need to apply bad practices anyway, you can fall back to tinker with the
lxml objects that are bound to TagNode._etree_obj
.
Reasoning¶
XML can be used to encode text documents, examples for such uses would be the Open Document Format and XML-TEI. It’s more prevalent use however is to encode data that is to be consumed by algorithms as configuration, measurements, application events, various metadata and so on.
Python is a high-level, general programming language with a vast ecosystem, notably including diverse scientific communities and tools. As such it is well suited to solve and cause problems in the humanities related field of Research Software Engineering by programmers with diverse educational background and expertise.
The commonly used Python library to parse and interact with a representation
of an XML document is lxml. Other libraries like the
xml.etree.ElementTree
module from the Python standard library shall not
be discussed due to their insignificance and shortcomings. It is notable that at
least these two share significant design aspects of Java APIs which is perceived
as weird and clumsy in Python code.
lxml is a wrapper around libxml2 which was developed by the GNOME developers
for other data than text documents. Data that is strictly structured and
expectable. Text documents are different in these regards as natural languages
and variety of media allow and lead to unprecedented manifestations for which an
encoding mixes different abstracted encapsulations of text fragments. And they
are formulated and structured for human consumers, and often printing devices.
So, what’s wrong with lxml? Not much, it’s a rock-solid, fast API for XML documents with known issues and known workarounds that represents the full glory of what a full-fledged family of specification implies - of which a lot is not of concern for the problems at hand and occasionally make solutions complicated. The one aspect that’s very wrong in the context of text processing is unfortunately its central model of elements and data/text that is attached to it in two different relations. In particular the notion of an element tail makes the whole enchilada tricky to traverse / navigate. The existence of this attribute is due to the insignificance of these fragments of an XML stream in the aforementioned, common uses of XML.
Now it is time for an example, given this document snippet:
<p rendition="#justify">
<lb/>Nomadisme épique exploratori-
<lb/><space dim="horizontal" quantity="2" units="chars"/>sme urbain <hi rendition="#b">Art des voya-
<lb/><space dim="horizontal" quantity="2" units="chars"/>ges</hi> et des promenades
</p>
Here’s a graphical representation of the markup with etree’s elements and their text and tail attributes:

When thinking about a paragraph of text, a way to conceptualize it is as a
sequence of sentences, formed by a series of words, a sequence of graphemes,
and punctuation. That’s a quite simple cascade of categories which can be very
well anticipated when processing text. With that mental model, line beginnings
would rather be considered to be on the same level as signs, but “Nomadisme …”
turns out not to be a sibling object of the object that represents the line
beginning and is not in direct relation with the paragraph. In lxml’s model it
is rather an attribute tail
assigned to that line beginning. The text
contents of the object that represents the hi
element and its children give
a good impression how hairy simple tasks can become.
An algorithm that shall remove line beginnings, space representations and
concatenate broken words would need a function that removes the element objects
in question while preserving the text fragments in its meaningful sequence
attached to the text
and tail
properties. In case these have no content,
their value of None
leads to different operations to concatenate strings.
Here’s a working implementation from the inxs library 1 for that data
model:
def remove_elements(
*elements: etree.ElementBase,
keep_children=False,
preserve_text=False,
preserve_tail=False
) -> None:
""" Removes the given elements from its tree. Unless ``keep_children`` is
passed as ``True``, its children vanish with it into void. If
``preserve_text`` is ``True``, the text and tail of a deleted element
will be preserved either in its left sibling's tail or its parent's
text. """
for element in elements:
if preserve_text and element.text:
previous = element.getprevious()
if previous is None:
parent = element.getparent()
if parent.text is None:
parent.text = ''
parent.text += element.text
else:
if previous.tail is None:
previous.tail = element.text
else:
previous.tail += element.text
if preserve_tail and element.tail:
if keep_children and len(element):
if element[-1].tail:
element[-1].tail += element.tail
else:
element[-1].tail = element.tail
else:
previous = element.getprevious()
if previous is None:
parent = element.getparent()
if parent.text is None:
parent.text = ''
parent.text += element.tail
else:
if len(element):
if element[-1].tail is None:
element[-1].tail = element.tail
else:
element[-1].tail += element.tail
else:
if previous.tail is None:
previous.tail = ''
previous.tail += element.tail
if keep_children:
for child in element:
element.addprevious(child)
element.getparent().remove(element)
That by itself is enough to simply remove the space
elements, but also
considering word-breaking dashes to wrap everything up is a similar piece of
routine of its own. And these quirks come back to you steadily while actual
markup is regularly more complex.
Now obviously, the data model that lxml / libxml2 provides is not up to standard Python ergonomics to solve text encoding problems.
There must be a better way.
There is a notable other markup parser that wraps around lxml, BeautifulSoup4.
It carries some interesting ideas, but is overall too opinionated and partly
ambiguous to implement a stringent data model. A notable specification of a
solid model for text documents is the DOM API that is even implemented in the
standard library’s xml.dom.minidom
module. But it lacks an XPath
interface and rumours say it’s slow. To illustrate the more accessible model
with a better locatability, here’s another graphical representation of the
markup example from above with text content in an emancipated, dedicated node
type:

Note that text containing attributes appear in document order which promises an eased lookaround. So, the obvious (?) idea is to wrap lxml in a layer that takes the DOM API as paradigmatic inspiration, looks and behaves pythonic while keeping the wrapped powers accessible.
Now with that API available, this is what an equivalent of the horribly complicated function seen above would look like:
@altered_default_filters()
def remove_nodes(*nodes: NodeBase, keep_children=False):
""" Removes the given nodes from its tree. Unless ``keep_children`` is
passed as ``True``, its children vanish with it into void. """
for node in nodes:
node.detach(retain_child_nodes=keep_children)
Frequently Asked Questions¶
Isn’t XML an obsolete format for text encoding, invented by boomers and cynically held up by their Generation X apologists? Why don’t you put your efforts in developing new approaches such as storing text in a graph database?
We think that XML-based encodings are actually very well suited for long-term usable text representations with a broad potential for granularity of capturing and semantic annotations. Not only is the data format simple enough to hold a full artifact in a self-contained file, but we also consider the duality of a format that can be handled both as stream and as tree as a helpful feature to address the physical and logical dimensions of a text and its manifestation. That is advantageous over depending on a heavy-weight database system. We acknowledge unquestionably that the specifications in the XML universe are often over-engineered, partly stuck in the times of their genesis and thus (euphemistically put) no fun. As a direct result of that the availability of implementations for contemporary development contexts and their ergonomics are poor, if available at all for a platform. That is what delb is addressing.
What are your long-term goals with this project?
Currently we want to flesh out a concluded user interface that lets developers concentrate on their tasks and not on the shortcomings and idiosyncrasies of available tools in the Pythoniverse. After modeling that API as a wrapper around lxml the aim is now to replace it piece by piece with a Pure Python™ implementation that will later be transpiled to C extension code with mypyc.
Eventually we’d like to re-conquer the world wide web and make unagitated, long texts and Stooges clips its predominant content again. On that occasion, fuck you Mark, fuck off Jeff, go fuck yourself Peter and all the other fucknut character masks. What a disgusting misery it is that the capital created from Tim’s ideas.
- 1
The
inxs
library failed. Yet it made clear which layer in Python XML Text handling needs to be fixed.
Installation¶
From the Python Package Index¶
To install delb manually, not as dependency, use pip:
$ pip install delb
At the moment there’s only one optional dependency to enable document loading via http and https, to include it use:
$ pip install delb[https-loader]
From source¶
Prerequisites:
A virtual environment of your project is activated.
That virtual environment houses an interpreter for Python 3.7 or later.
Obtain the code with roughly one of:
git clone git@github.com:delb-xml/delb-py.git
curl -LosS https://github.com/delb-xml/delb-py/archive/main.tar.gz | tar xzf -
To install it regularly:
…/delb-py $ pip install .
Again, to include the loading over http(s):
…/delb-py $ pip install .[https-loader]
For developing purposes of delb
itself, the library should be installed in
editable mode:
…/delb-py $ pip install --editable .
Hint
Using git submodules is a great way to vendorize a lib for your project and to have a fork for your adjustments. Please offer the latter to upstream if done well.
Developer toolbox¶
The repository includes configurations so that beside a suited Python interpreter three tools need to be available globally. pipx is the recommended facilitation to install the Python implemented tools black and hatch.
just¶
just is a task runner that executes a variety of common recipes. This gives a list of all available ones:
…/delb-py $ just --list
Before committing changes, run the complete suite of quality checks by invoking the default recipe:
…/delb-py $ just
black¶
It’s recommended to configure the used editors and IDEs to enforce black’s code style, but it can also be applied with:
…/delb-py $ just black
hatch¶
Several of the just recipes rely on hatch.
API Documentation¶
Note
There are actually two packages that are installed with delb:
delb
and _delb
. As the underscore indicates, the latter is exposing
private parts of the API while the first is re-exposing what is deemed to
be public from that one and additional contents.
As a rule of thumb, use the public API in applications and the private API
in delb extensions. By doing so, you can avoid circular dependencies if
your extension (or other code that it depends on) uses contents from the
_delb
package.
Documents¶
- class delb.Document(source, collapse_whitespace=None, parser=None, parser_options=None, klass=None, **config)[source]¶
This class is the entrypoint to obtain a representation of an XML encoded text document. For instantiation any object can be passed. A suitable loader must be available for the given source. See Document loaders for the default loaders that come with this package. Plugins are capable to alter the available loaders, see Extending delb.
Nodes can be tested for membership in a document:
>>> document = Document("<root>text</root>") >>> text_node = document.root[0] >>> text_node in document True >>> text_node.clone() in document False
The string coercion of a document yields an XML encoded stream, but unlike
Document.save()
andDocument.write()
, without an XML declaration:>>> document = Document("<root/>") >>> str(document) '<root/>'
- Parameters
source – Anything that the configured loaders can make sense of to return a parsed document tree.
collapse_whitespace – Deprecated. Use the argument with the same name on the
parser_options
object.parser – Deprecated.
parser_options – A
delb.ParserOptions
class to configure the used parser.klass – Explicitly define the initilized class. This can be useful for applications that have default document subclasses in use.
config – Additional keyword arguments for the configuration of extension classes.
Properties
Beside the used
parser
andcollapsed_whitespace
option, this property contains the namespaced data that extension classes and loaders may have stored.A list-like accessor to the nodes that precede the document's root node.
The namespace mapping of the document's
root
node.The root node of a document tree.
The source URL where a loader obtained the document's contents or
None
.A list-like accessor to the nodes that follow the document's root node.
Uncategorized methods
cleanup_namespaces
([namespaces, retain_prefixes])Consolidates the namespace declarations in the document by removing unused and redundant ones.
clone
()- return
Another instance with the duplicated contents.
Collapses whitespace as described here: https://wiki.tei-c.org/index.php/XML_Whitespace#Recommendations
css_select
(expression[, namespaces])This method proxies to the
TagNode.css_select()
method of the document'sroot
node.This method proxies to the
TagNode.merge_text_nodes()
method of the document'sroot
node.new_tag_node
(local_name[, attributes, namespace])This method proxies to the
TagNode.new_tag_node()
method of the document's root node.save
(path[, pretty])- param path
The path where the document shall be saved.
write
(buffer[, pretty])- param buffer
A file-like object that the document is written to.
xpath
(expression[, namespaces])This method proxies to the
TagNode.xpath()
method of the document'sroot
node.xslt
(transformation)- param transformation
A
lxml.etree.XSLT
instance that shall be
- cleanup_namespaces(namespaces: Optional[Mapping[Optional[str], str]] = None, retain_prefixes: Optional[Iterable[str]] = None)[source]¶
Consolidates the namespace declarations in the document by removing unused and redundant ones.
- There are currently some caveats due to lxml/libxml2’s implementations:
prefixes cannot be set for the default namespace
a namespace cannot be declared as default after a node’s creation (where a namespace was specified that had been registered for a prefix with
register_namespace()
)there’s no way to unregister a prefix for a namespace
if there are other namespaces used as default namespaces (where a namespace was specified that had not been registered for a prefix) in the descendants of the root, their declarations are lost when this method is used
- To ensure clean serializations, one should:
register prefixes for all namespaces except the default one at the start of an application
use only one default namespace within a document
- Parameters
namespaces – An optional mapping of prefixes (keys) to namespaces (values) that will be declared at the root element.
retain_prefixes – An optional iterable that contains prefixes whose declarations shall be kept despite not being used.
- collapse_whitespace()[source]¶
Collapses whitespace as described here: https://wiki.tei-c.org/index.php/XML_Whitespace#Recommendations
Implicitly merges all neighbouring text nodes.
- config: SimpleNamespace¶
Beside the used
parser
andcollapsed_whitespace
option, this property contains the namespaced data that extension classes and loaders may have stored.
- css_select(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults[source]¶
This method proxies to the
TagNode.css_select()
method of the document’sroot
node.
- head_nodes¶
A list-like accessor to the nodes that precede the document’s root node. Note that nodes can’t be removed or replaced.
- merge_text_nodes()[source]¶
This method proxies to the
TagNode.merge_text_nodes()
method of the document’sroot
node.
- new_tag_node(local_name: str, attributes: Optional[Dict[str, str]] = None, namespace: Optional[str] = None) → TagNode[source]¶
This method proxies to the
TagNode.new_tag_node()
method of the document’s root node.
- save(path: Path, pretty: bool = False, **cleanup_namespaces_args)[source]¶
- Parameters
path – The path where the document shall be saved.
pretty – Adds indentation for human consumers when
True
.cleanup_namespaces_args – Arguments that are a passed to
Document.cleanup_namespaces()
before saving.
- tail_nodes¶
A list-like accessor to the nodes that follow the document’s root node. Note that nodes can’t be removed or replaced.
- write(buffer: IO, pretty: bool = False, **cleanup_namespaces_args)[source]¶
- Parameters
buffer – A file-like object that the document is written to.
pretty – Adds indentation for human consumers when
True
.cleanup_namespaces_args – Arguments that are a passed to
Document.cleanup_namespaces()
before writing.
- xpath(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults[source]¶
This method proxies to the
TagNode.xpath()
method of the document’sroot
node.
Document loaders¶
If you want or need to manipulate the availability of or order in which loaders
are attempted, you can change the
delb.plugins.plugin_manager.plugins.loaders
object which is a
list
. Its state is reflected in your whole application. Please refer to
this issue when you require finer controls over these aspects.
Core¶
The core_loaders
module provides a set loaders to retrieve documents from various
data sources.
- _delb.plugins.core_loaders.buffer_loader(data: Any, config: SimpleNamespace) → _delb.typing.LoaderResult[source]¶
This loader loads a document from a file-like object.
- _delb.plugins.core_loaders.etree_loader(data: Any, config: SimpleNamespace) → _delb.typing.LoaderResult[source]¶
This loader processes
lxml.etree._Element
andlxml.etree._ElementTree
instances.
- _delb.plugins.core_loaders.ftp_loader(data: Any, config: SimpleNamespace) → _delb.typing.LoaderResult[source]¶
Loads a document from a URL with either the
ftp
schema. The URL will be bound tosource_url
on the document’sDocument.config
attribute.
- _delb.plugins.core_loaders.path_loader(data: Any, config: SimpleNamespace) → _delb.typing.LoaderResult[source]¶
This loader loads from a file that is pointed at with a
pathlib.Path
instance. That instance will be bound tosource_path
on the document’sDocument.config
attribute.
- _delb.plugins.core_loaders.tag_node_loader(data: Any, config: SimpleNamespace) → _delb.typing.LoaderResult[source]¶
This loader loads, or rather clones, a
delb.TagNode
instance and its descendant nodes.
- _delb.plugins.core_loaders.text_loader(data: Any, config: SimpleNamespace) → _delb.typing.LoaderResult[source]¶
Parses a string containing a full document.
Extra¶
If delb
is installed with https-loader
as extra, the required
dependencies for this loader are installed as well. See Installation.
- _delb.plugins.https_loader.https_loader(data: ~typing.Any, config: ~types.SimpleNamespace, client: ~httpx.Client = <httpx.Client object>) → _delb.typing.LoaderResult[source]¶
This loader loads a document from a URL with the
http
andhttps
scheme. Redirects are followed. The default httpx-client follows redirects and can partially be configured with environment variables. The URL will be bound to the namesource_url
on the document’sDocument.config
attribute.Loaders with specifically configured httpx-clients can build on this loader like so:
import httpx from _delb.plugins import plugin_manager from _delb.plugins.https_loader import https_loader client = httpx.Client(follow_redirects=False, trust_env=False) @plugin_manager.register_loader(before=https_loader) def custom_https_loader(data, config): return https_loader(data, config, client=client)
Parser options¶
- class delb.ParserOptions(cleanup_namespaces: bool = False, collapse_whitespace: bool = False, remove_comments: bool = False, remove_processing_instructions: bool = False, resolve_entities: bool = True, unplugged: bool = False)[source]¶
The configuration options that define an XML parser’s behaviour.
- Parameters
cleanup_namespaces – Consolidate XML namespace declarations.
collapse_whitespace –
Collapse the content's whitespace
.remove_comments – Ignore comments.
remove_processing_instructions – Don’t include processing instructions in the parsed tree.
resolve_entities – Resolve entities.
unplugged – Don’t load referenced resources over network.
Nodes¶
Comment¶
- class delb.CommentNode(etree_element: _Element)[source]¶
The instances of this class represent comment nodes of a tree.
To instantiate new nodes use
new_comment_node()
.Properties
The comment's text.
The depth (or level) of the node in its tree.
The
Document
instances that the node is associated with orNone
.The concatenated contents of all text node descendants in document order.
The node's index within the parent's collection of child nodes or
None
when the node has no parent.The prefix to namespace mapping of the node.
The node's parent or
None
.Fetching a single relative node
fetch_following
(*filter)- param filter
Any number of filter s.
fetch_following_sibling
(*filter)- param filter
Any number of filter s.
fetch_preceding
(*filter)- param filter
Any number of filter s.
fetch_preceding_sibling
(*filter)- param filter
Any number of filter s.
Iterating over relative nodes
iterate_ancestors
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_children
(*filter[, recurse])A generator iterator that yields nothing.
iterate_descendants
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
Querying nodes
xpath
(expression[, namespaces])See Queries with XPath & CSS for details on the extent of the XPath implementation.
Adding nodes
add_following_siblings
(*node[, clone])Adds one or more nodes to the right of the node this method is called on.
add_preceding_siblings
(*node[, clone])Adds one or more nodes to the left of the node this method is called on.
Removing a node from its tree
detach
([retain_child_nodes])Removes the node from its tree.
replace_with
(node[, clone])Removes the node and places the given one in its tree location.
Uncategorized methods
clone
([deep, quick_and_unsafe])- param deep
Clones the whole subtree if
True
.
new_tag_node
(local_name[, attributes, ...])Creates a new
TagNode
instance in the node's context.
- add_following_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the right of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- add_preceding_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the left of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- clone(deep: bool = False, quick_and_unsafe: bool = False) → _ElementWrappingNode¶
- Parameters
deep – Clones the whole subtree if
True
.quick_and_unsafe – Creates a deep clone in a quicker manner where text nodes may get lost. It should be safe with trees that don’t contain subsequent text nodes, e.g. freshly parsed, unaltered documents of after
TagNode.merge_text_nodes()
has been applied.
- Returns
A copy of the node.
- detach(retain_child_nodes: bool = False) → _ElementWrappingNode¶
Removes the node from its tree.
- Parameters
retain_child_nodes – Keeps the node’s descendants in the originating tree if
True
.- Returns
The removed node.
- property document: Optional[Document]¶
The
Document
instances that the node is associated with orNone
.
- fetch_following(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next node in document order that matches all filters or
None
.
- fetch_following_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the right that matches all filters or
None
.
- fetch_preceding(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The previous node in document order that matches all filters or
None
.
- fetch_preceding_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the left that matches all filters or
None
.
- first_child = None¶
- property index: Optional[int]¶
The node’s index within the parent’s collection of child nodes or
None
when the node has no parent.
- iterate_ancestors(*filter: _delb.typing.Filter) → Iterator[TagNode]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the ancestor nodes from bottom to top.
- iterate_children(*filter: _delb.typing.Filter, recurse: bool = False) → Iterator[NodeBase]¶
A generator iterator that yields nothing.
- iterate_descendants(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the descending nodes of the node.
- iterate_following(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the following nodes in document order.
- iterate_following_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s right.
- iterate_preceding(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the previous nodes in document order.
- iterate_preceding_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s left.
- last_child = None¶
- last_descendant = None¶
- new_tag_node(local_name: str, attributes: Optional[Dict[str, str]] = None, namespace: Optional[str] = None, children: Sequence[Union[str, NodeBase, _TagDefinition]] = ()) → TagNode¶
Creates a new
TagNode
instance in the node’s context.- Parameters
local_name – The tag name.
attributes – Optional attributes that are assigned to the new node.
namespace – An optional tag namespace. If none is provided, the context node’s namespace is inherited.
children – An optional sequence of objects that will be appended as child nodes. This can be existing nodes, strings that will be inserted as text nodes and in-place definitions of
TagNode
instances fromtag()
. The latter will be assigned to the same namespace.
- Returns
The newly created tag node.
- replace_with(node: Union[str, NodeBase, _TagDefinition], clone: bool = False) → NodeBase¶
Removes the node and places the given one in its tree location.
The node can be a concrete instance of any node type or a rather abstract description in the form of a string or an object returned from the
tag()
function that is used to derive aTextNode
respectivelyTagNode
instance from.- Parameters
node – The replacing node.
clone – A concrete, replacing node is cloned if
True
.
- Returns
The removed node.
- xpath(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults¶
See Queries with XPath & CSS for details on the extent of the XPath implementation.
- Parameters
expression – A supported XPath 1.0 expression that contains one or more location paths.
namespaces – A mapping of prefixes that are used in the expression to namespaces. If omitted, the node’s definition is used.
- Returns
All nodes that match the evaluation of the provided XPath expression.
Processing instruction¶
- class delb.ProcessingInstructionNode(etree_element: _Element)[source]¶
The instances of this class represent processing instruction nodes of a tree.
To instantiate new nodes use
new_processing_instruction_node()
.Properties
The processing instruction's text.
The depth (or level) of the node in its tree.
The
Document
instances that the node is associated with orNone
.The concatenated contents of all text node descendants in document order.
The node's index within the parent's collection of child nodes or
None
when the node has no parent.The prefix to namespace mapping of the node.
The node's parent or
None
.The processing instruction's target.
Fetching a single relative node
fetch_following
(*filter)- param filter
Any number of filter s.
fetch_following_sibling
(*filter)- param filter
Any number of filter s.
fetch_preceding
(*filter)- param filter
Any number of filter s.
fetch_preceding_sibling
(*filter)- param filter
Any number of filter s.
Iterating over relative nodes
iterate_ancestors
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_children
(*filter[, recurse])A generator iterator that yields nothing.
iterate_descendants
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
Querying nodes
xpath
(expression[, namespaces])See Queries with XPath & CSS for details on the extent of the XPath implementation.
Adding nodes
add_following_siblings
(*node[, clone])Adds one or more nodes to the right of the node this method is called on.
add_preceding_siblings
(*node[, clone])Adds one or more nodes to the left of the node this method is called on.
Removing a node from its tree
detach
([retain_child_nodes])Removes the node from its tree.
replace_with
(node[, clone])Removes the node and places the given one in its tree location.
Uncategorized methods
clone
([deep, quick_and_unsafe])- param deep
Clones the whole subtree if
True
.
new_tag_node
(local_name[, attributes, ...])Creates a new
TagNode
instance in the node's context.
- add_following_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the right of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- add_preceding_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the left of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- clone(deep: bool = False, quick_and_unsafe: bool = False) → _ElementWrappingNode¶
- Parameters
deep – Clones the whole subtree if
True
.quick_and_unsafe – Creates a deep clone in a quicker manner where text nodes may get lost. It should be safe with trees that don’t contain subsequent text nodes, e.g. freshly parsed, unaltered documents of after
TagNode.merge_text_nodes()
has been applied.
- Returns
A copy of the node.
- detach(retain_child_nodes: bool = False) → _ElementWrappingNode¶
Removes the node from its tree.
- Parameters
retain_child_nodes – Keeps the node’s descendants in the originating tree if
True
.- Returns
The removed node.
- property document: Optional[Document]¶
The
Document
instances that the node is associated with orNone
.
- fetch_following(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next node in document order that matches all filters or
None
.
- fetch_following_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the right that matches all filters or
None
.
- fetch_preceding(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The previous node in document order that matches all filters or
None
.
- fetch_preceding_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the left that matches all filters or
None
.
- first_child = None¶
- property index: Optional[int]¶
The node’s index within the parent’s collection of child nodes or
None
when the node has no parent.
- iterate_ancestors(*filter: _delb.typing.Filter) → Iterator[TagNode]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the ancestor nodes from bottom to top.
- iterate_children(*filter: _delb.typing.Filter, recurse: bool = False) → Iterator[NodeBase]¶
A generator iterator that yields nothing.
- iterate_descendants(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the descending nodes of the node.
- iterate_following(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the following nodes in document order.
- iterate_following_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s right.
- iterate_preceding(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the previous nodes in document order.
- iterate_preceding_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s left.
- last_child = None¶
- last_descendant = None¶
- new_tag_node(local_name: str, attributes: Optional[Dict[str, str]] = None, namespace: Optional[str] = None, children: Sequence[Union[str, NodeBase, _TagDefinition]] = ()) → TagNode¶
Creates a new
TagNode
instance in the node’s context.- Parameters
local_name – The tag name.
attributes – Optional attributes that are assigned to the new node.
namespace – An optional tag namespace. If none is provided, the context node’s namespace is inherited.
children – An optional sequence of objects that will be appended as child nodes. This can be existing nodes, strings that will be inserted as text nodes and in-place definitions of
TagNode
instances fromtag()
. The latter will be assigned to the same namespace.
- Returns
The newly created tag node.
- replace_with(node: Union[str, NodeBase, _TagDefinition], clone: bool = False) → NodeBase¶
Removes the node and places the given one in its tree location.
The node can be a concrete instance of any node type or a rather abstract description in the form of a string or an object returned from the
tag()
function that is used to derive aTextNode
respectivelyTagNode
instance from.- Parameters
node – The replacing node.
clone – A concrete, replacing node is cloned if
True
.
- Returns
The removed node.
- xpath(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults¶
See Queries with XPath & CSS for details on the extent of the XPath implementation.
- Parameters
expression – A supported XPath 1.0 expression that contains one or more location paths.
namespaces – A mapping of prefixes that are used in the expression to namespaces. If omitted, the node’s definition is used.
- Returns
All nodes that match the evaluation of the provided XPath expression.
Tag¶
- class delb.TagNode(etree_element: _Element)[source]¶
The instances of this class represent tag node s of a tree, the equivalent of DOM’s elements.
To instantiate new nodes use
Document.new_tag_node
,TagNode.new_tag_node
,TextNode.new_tag_node
ornew_tag_node()
.Some syntactic sugar is baked in:
Attributes and nodes can be tested for membership in a node.
>>> root = Document('<root ham="spam"><child/></root>').root >>> child = root.first_child >>> "ham" in root True >>> child in root True
Nodes can be copied. Note that this relies on
TagNode.clone()
.>>> from copy import copy, deepcopy >>> root = Document("<root>Content</root>").root >>> print(copy(root)) <root/> >>> print(deepcopy(root)) <root>Content</root>
Nodes can be tested for equality regarding their qualified name and attributes.
>>> root = Document('<root><foo x="0"/><foo x="0"/><bar x="0"/></root>').root >>> root[0] == root[1] True >>> root[0] == root[2] False
Attribute values and child nodes can be obtained with the subscript notation.
>>> root = Document('<root x="0"><child_1/>child_2<child_3/></root>').root >>> root["x"] '0' >>> print(root[0]) <child_1/> >>> print(root[-1]) <child_3/> >>> print([str(x) for x in root[1::-1]]) ['child_2', '<child_1/>']
How much child nodes has this node anyway?
>>> root = Document("<root><child_1/><child_2/></root>").root >>> len(root) 2 >>> len(root[0]) 0
As seen in the examples above, a tag nodes string representation yields a serialized XML representation of a sub-/tree.
Properties
A mapping that can be used to query and alter the node's attributes.
The depth (or level) of the node in its tree.
The
Document
instances that the node is associated with orNone
.The node's first child node.
The concatenated contents of all text node descendants in document order.
This is a shortcut to retrieve and set the
id
attribute in the XML namespace.The node's index within the parent's collection of child nodes or
None
when the node has no parent.The node's last child node.
The node's last descendant.
The node's name.
An unambiguous XPath location path that points to this node from its tree root.
The node's namespace.
The prefix to namespace mapping of the node.
The node's parent or
None
.The prefix that the node's namespace is currently mapped to.
The node's qualified name in Clark notation.
Fetching a single relative node
fetch_following
(*filter)- param filter
Any number of filter s.
fetch_following_sibling
(*filter)- param filter
Any number of filter s.
fetch_preceding
(*filter)- param filter
Any number of filter s.
fetch_preceding_sibling
(*filter)- param filter
Any number of filter s.
Iterating over relative nodes
iterate_ancestors
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_children
(*filter[, recurse])- param filter
Any number of filter s that a node must match to be
iterate_descendants
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
Querying nodes
css_select
(expression[, namespaces])See Queries with XPath & CSS regarding the extent of the supported grammar.
fetch_or_create_by_xpath
(expression[, ...])Fetches a single node that is locatable by the provided XPath expression.
xpath
(expression[, namespaces])See Queries with XPath & CSS for details on the extent of the XPath implementation.
Adding nodes
add_following_siblings
(*node[, clone])Adds one or more nodes to the right of the node this method is called on.
add_preceding_siblings
(*node[, clone])Adds one or more nodes to the left of the node this method is called on.
append_children
(*node[, clone])Adds one or more nodes as child nodes after any existing to the child nodes of the node this method is called on.
insert_children
(index, *node[, clone])Inserts one or more child nodes.
prepend_children
(*node[, clone])Adds one or more nodes as child nodes before any existing to the child nodes of the node this method is called on.
Removing a node from its tree
detach
([retain_child_nodes])Removes the node from its tree.
replace_with
(node[, clone])Removes the node and places the given one in its tree location.
Uncategorized methods
clone
([deep, quick_and_unsafe])- param deep
Clones the whole subtree if
True
.
Merges all consecutive text nodes in the subtree into one.
new_tag_node
(local_name[, attributes, ...])Creates a new
TagNode
instance in the node's context.parse
(text[, parser, parser_options, ...])Parses the given string or bytes sequence into a new tree.
- add_following_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the right of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- add_preceding_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the left of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- append_children(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)[source]¶
Adds one or more nodes as child nodes after any existing to the child nodes of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- property attributes: TagAttributes¶
A mapping that can be used to query and alter the node’s attributes.
>>> node = new_tag_node("node", attributes={"foo": "0", "bar": "0"}) >>> node.attributes {'foo': '0', 'bar': '0'} >>> node.attributes.pop("bar") '0' >>> node.attributes["foo"] = "1" >>> node.attributes["peng"] = "1" >>> print(node) <node foo="1" peng="1"/> >>> node.attributes.update({"foo": "2", "zong": "2"}) >>> print(node) <node foo="2" peng="1" zong="2"/>
Namespaced attributes can be accessed by using Python’s slice notation. A default namespace can be provided optionally, but it’s also found without.
>>> node = new_tag_node("node", {}) >>> node.attributes["http://namespace":"foo"] = "0" >>> print(node) <node xmlns:ns0="http://namespace" ns0:foo="0"/> >>> node = Document('<node xmlns="default" foo="0"/>').root >>> node.attributes["default":"foo"] is node.attributes["foo"] True
Attributes behave like strings, but also expose namespace, local name and value for manipulation.
>>> node = new_tag_node("node") >>> node.attributes["foo"] = "0" >>> node.attributes["foo"].local_name = "bar" >>> node.attributes["bar"].namespace = "http://namespace" >>> node.attributes["http://namespace":"bar"].value = "1" >>> print(node) <node xmlns:ns0="http://namespace" ns0:bar="1"/>
Unlike with typical Python mappings, requesting a non-existing attribute doesn’t evoke a
KeyError
, insteadNone
is returned.
- clone(deep: bool = False, quick_and_unsafe: bool = False) → TagNode[source]¶
- Parameters
deep – Clones the whole subtree if
True
.quick_and_unsafe – Creates a deep clone in a quicker manner where text nodes may get lost. It should be safe with trees that don’t contain subsequent text nodes, e.g. freshly parsed, unaltered documents of after
TagNode.merge_text_nodes()
has been applied.
- Returns
A copy of the node.
- css_select(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults[source]¶
See Queries with XPath & CSS regarding the extent of the supported grammar.
Namespace prefixes are delimited with a
|
before a name test, for examplediv svg|metadata
selects all descendants ofdiv
named nodes that belong to the default namespace or have no namespace and whose name ismetadata
and have a namespace that is mapped to thesvg
prefix.- Parameters
expression – A CSS selector expression.
namespaces – A mapping of prefixes that are used in the expression to namespaces. If omitted, the node’s definition is used.
- Returns
All nodes that match the evaluation of the provided CSS selector expression.
- detach(retain_child_nodes: bool = False) → _ElementWrappingNode[source]¶
Removes the node from its tree.
- Parameters
retain_child_nodes – Keeps the node’s descendants in the originating tree if
True
.- Returns
The removed node.
- property document: Optional[Document]¶
The
Document
instances that the node is associated with orNone
.
- fetch_following(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next node in document order that matches all filters or
None
.
- fetch_following_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the right that matches all filters or
None
.
- fetch_or_create_by_xpath(expression: str, namespaces: Union[Namespaces, None, Mapping[Optional[str], str]] = None) → TagNode[source]¶
Fetches a single node that is locatable by the provided XPath expression. If the node doesn’t exist, the non-existing branch will be created. These rules are imperative in your endeavour:
All location steps must use the child axis.
Each step needs to provide a name test.
Attributes must be compared against a literal.
Multiple attribute comparisons must be joined with the and operator and / or more than one predicate expression.
The logical validity of multiple attribute comparisons isn’t checked. E.g. one could provide
foo[@p="her"][@p="him"]
, but expect an undefined behaviour.Other contents in predicate expressions are invalid.
>>> document = Document("<root/>") >>> grandchild = document.root.fetch_or_create_by_xpath( ... "child[@a='b']/grandchild" ... ) >>> grandchild is document.root.fetch_or_create_by_xpath( ... "child[@a='b']/grandchild" ... ) True >>> str(document) '<root><child a="b"><grandchild/></child></root>'
- Parameters
expression – An XPath expression that can unambiguously locate a descending node in a tree that has any state.
namespaces – An optional mapping of prefixes to namespaces. As default the node’s one is used.
- Returns
The existing or freshly created node descibed with
expression
.
- fetch_preceding(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The previous node in document order that matches all filters or
None
.
- fetch_preceding_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the left that matches all filters or
None
.
- property id: Optional[str]¶
This is a shortcut to retrieve and set the
id
attribute in the XML namespace. The client code is responsible to pass properly formed id names.
- property index: Optional[int]¶
The node’s index within the parent’s collection of child nodes or
None
when the node has no parent.
- insert_children(index: int, *node: Union[str, NodeBase, _TagDefinition], clone: bool = False)[source]¶
Inserts one or more child nodes.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
index – The index at which the first of the given nodes will be inserted, the remaining nodes are added afterwards in the given order.
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- iterate_ancestors(*filter: _delb.typing.Filter) → Iterator[TagNode]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the ancestor nodes from bottom to top.
- iterate_children(*filter: _delb.typing.Filter, recurse: bool = False) → Iterator[NodeBase][source]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
recurse – Deprecated. Use
NodeBase.iterate_descendants()
.
- Returns
A generator iterator that yields the child nodes of the node.
- iterate_descendants(*filter: _delb.typing.Filter) → Iterator[NodeBase][source]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the descending nodes of the node.
- iterate_following(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the following nodes in document order.
- iterate_following_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s right.
- iterate_preceding(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the previous nodes in document order.
- iterate_preceding_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s left.
- property location_path: str¶
An unambiguous XPath location path that points to this node from its tree root.
- property namespace: Optional[str]¶
The node’s namespace. Be aware, that while this property can be set to
None
, serializations will continue to render a previous default namespace declaration if the node had such.
- new_tag_node(local_name: str, attributes: Optional[Dict[str, str]] = None, namespace: Optional[str] = None, children: Sequence[Union[str, NodeBase, _TagDefinition]] = ()) → TagNode[source]¶
Creates a new
TagNode
instance in the node’s context.- Parameters
local_name – The tag name.
attributes – Optional attributes that are assigned to the new node.
namespace – An optional tag namespace. If none is provided, the context node’s namespace is inherited.
children – An optional sequence of objects that will be appended as child nodes. This can be existing nodes, strings that will be inserted as text nodes and in-place definitions of
TagNode
instances fromtag()
. The latter will be assigned to the same namespace.
- Returns
The newly created tag node.
- static parse(text: AnyStr, parser: Optional[XMLParser] = None, parser_options: Optional[ParserOptions] = None, collapse_whitespace: Optional[bool] = None) → TagNode[source]¶
Parses the given string or bytes sequence into a new tree.
- Parameters
text – A serialized XML tree.
parser – Deprecated.
parser_options – A
delb.ParserOptions
class to configure the used parser.collapse_whitespace – Deprecated. Use the argument with the same name on the
parser_options
object.
- prepend_children(*node: NodeBase, clone: bool = False) → None[source]¶
Adds one or more nodes as child nodes before any existing to the child nodes of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- replace_with(node: Union[str, NodeBase, _TagDefinition], clone: bool = False) → NodeBase¶
Removes the node and places the given one in its tree location.
The node can be a concrete instance of any node type or a rather abstract description in the form of a string or an object returned from the
tag()
function that is used to derive aTextNode
respectivelyTagNode
instance from.- Parameters
node – The replacing node.
clone – A concrete, replacing node is cloned if
True
.
- Returns
The removed node.
- property universal_name: str¶
The node’s qualified name in Clark notation.
- xpath(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults[source]¶
See Queries with XPath & CSS for details on the extent of the XPath implementation.
- Parameters
expression – A supported XPath 1.0 expression that contains one or more location paths.
namespaces – A mapping of prefixes that are used in the expression to namespaces. If omitted, the node’s definition is used.
- Returns
All nodes that match the evaluation of the provided XPath expression.
Tag attribute¶
- class delb.nodes.Attribute(attributes: TagAttributes, key: str)[source]¶
Attribute objects represent tag node’s attributes. See the
delb.TagNode.attributes()
documentation for capabilities.- property universal_name: str¶
The attribute’s namespace and local name in Clark notation.
Text¶
- class delb.TextNode(reference_or_text: Union[_Element, str, TextNode], position: int = 0)[source]¶
TextNodes contain the textual data of a document. The class shall not be initialized by client code, just throw strings into the trees.
Instances expose all methods of
str
exceptstr.index()
:>>> node = TextNode("Show us the way to the next whisky bar.") >>> node.split() ['Show', 'us', 'the', 'way', 'to', 'the', 'next', 'whisky', 'bar.']
Instances can be tested for inequality with other text nodes and strings:
>>> TextNode("ham") == TextNode("spam") False >>> TextNode("Patsy") == "Patsy" True
And they can be tested for substrings:
>>> "Sir" in TextNode("Sir Bedevere the Wise") True
Attributes that rely to child nodes yield nothing respectively
None
.Properties
The node's text content.
The depth (or level) of the node in its tree.
The
Document
instances that the node is associated with orNone
.The concatenated contents of all text node descendants in document order.
The node's index within the parent's collection of child nodes or
None
when the node has no parent.The prefix to namespace mapping of the node.
The node's parent or
None
.Fetching a single relative node
fetch_following
(*filter)- param filter
Any number of filter s.
fetch_following_sibling
(*filter)- param filter
Any number of filter s.
fetch_preceding
(*filter)- param filter
Any number of filter s.
fetch_preceding_sibling
(*filter)- param filter
Any number of filter s.
Iterating over relative nodes
iterate_ancestors
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_children
(*filter[, recurse])A generator iterator that yields nothing.
iterate_descendants
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_following_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding
(*filter)- param filter
Any number of filter s that a node must match to be
iterate_preceding_siblings
(*filter)- param filter
Any number of filter s that a node must match to be
Querying nodes
xpath
(expression[, namespaces])See Queries with XPath & CSS for details on the extent of the XPath implementation.
Adding nodes
add_following_siblings
(*node[, clone])Adds one or more nodes to the right of the node this method is called on.
add_preceding_siblings
(*node[, clone])Adds one or more nodes to the left of the node this method is called on.
Removing a node from its tree
detach
([retain_child_nodes])Removes the node from its tree.
replace_with
(node[, clone])Removes the node and places the given one in its tree location.
Uncategorized methods
clone
([deep, quick_and_unsafe])- param deep
Clones the whole subtree if
True
.
new_tag_node
(local_name[, attributes, ...])Creates a new
TagNode
instance in the node's context.
- add_following_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the right of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- add_preceding_siblings(*node: Union[str, NodeBase, _TagDefinition], clone: bool = False)¶
Adds one or more nodes to the left of the node this method is called on.
The nodes can be concrete instances of any node type or rather abstract descriptions in the form of strings or objects returned from the
tag()
function that are used to deriveTextNode
respectivelyTagNode
instances from.- Parameters
node – The node(s) to be added.
clone – Clones the concrete nodes before adding if
True
.
- clone(deep: bool = False, quick_and_unsafe: bool = False) → NodeBase[source]¶
- Parameters
deep – Clones the whole subtree if
True
.quick_and_unsafe – Creates a deep clone in a quicker manner where text nodes may get lost. It should be safe with trees that don’t contain subsequent text nodes, e.g. freshly parsed, unaltered documents of after
TagNode.merge_text_nodes()
has been applied.
- Returns
A copy of the node.
- detach(retain_child_nodes: bool = False) → TextNode[source]¶
Removes the node from its tree.
- Parameters
retain_child_nodes – Keeps the node’s descendants in the originating tree if
True
.- Returns
The removed node.
- property document: Optional[Document]¶
The
Document
instances that the node is associated with orNone
.
- fetch_following(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next node in document order that matches all filters or
None
.
- fetch_following_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the right that matches all filters or
None
.
- fetch_preceding(*filter: _delb.typing.Filter) → Optional[NodeBase]¶
- Parameters
filter – Any number of filter s.
- Returns
The previous node in document order that matches all filters or
None
.
- fetch_preceding_sibling(*filter: _delb.typing.Filter) → Optional[NodeBase][source]¶
- Parameters
filter – Any number of filter s.
- Returns
The next sibling to the left that matches all filters or
None
.
- first_child = None¶
- property index: Optional[int]¶
The node’s index within the parent’s collection of child nodes or
None
when the node has no parent.
- iterate_ancestors(*filter: _delb.typing.Filter) → Iterator[TagNode]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the ancestor nodes from bottom to top.
- iterate_children(*filter: _delb.typing.Filter, recurse: bool = False) → Iterator[NodeBase]¶
A generator iterator that yields nothing.
- iterate_descendants(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the descending nodes of the node.
- iterate_following(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the following nodes in document order.
- iterate_following_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s right.
- iterate_preceding(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the previous nodes in document order.
- iterate_preceding_siblings(*filter: _delb.typing.Filter) → Iterator[NodeBase]¶
- Parameters
filter – Any number of filter s that a node must match to be yielded.
- Returns
A generator iterator that yields the siblings to the node’s left.
- last_child = None¶
- last_descendant = None¶
- new_tag_node(local_name: str, attributes: Optional[Dict[str, str]] = None, namespace: Optional[str] = None, children: Sequence[Union[str, NodeBase, _TagDefinition]] = ()) → TagNode¶
Creates a new
TagNode
instance in the node’s context.- Parameters
local_name – The tag name.
attributes – Optional attributes that are assigned to the new node.
namespace – An optional tag namespace. If none is provided, the context node’s namespace is inherited.
children – An optional sequence of objects that will be appended as child nodes. This can be existing nodes, strings that will be inserted as text nodes and in-place definitions of
TagNode
instances fromtag()
. The latter will be assigned to the same namespace.
- Returns
The newly created tag node.
- replace_with(node: Union[str, NodeBase, _TagDefinition], clone: bool = False) → NodeBase¶
Removes the node and places the given one in its tree location.
The node can be a concrete instance of any node type or a rather abstract description in the form of a string or an object returned from the
tag()
function that is used to derive aTextNode
respectivelyTagNode
instance from.- Parameters
node – The replacing node.
clone – A concrete, replacing node is cloned if
True
.
- Returns
The removed node.
- xpath(expression: str, namespaces: Optional[Namespaces] = None) → QueryResults¶
See Queries with XPath & CSS for details on the extent of the XPath implementation.
- Parameters
expression – A supported XPath 1.0 expression that contains one or more location paths.
namespaces – A mapping of prefixes that are used in the expression to namespaces. If omitted, the node’s definition is used.
- Returns
All nodes that match the evaluation of the provided XPath expression.
Node constructors¶
- delb.new_comment_node(content: str) → CommentNode[source]¶
Creates a new
CommentNode
.- Parameters
content – The comment’s content a.k.a. as text.
- Returns
The newly created comment node.
- delb.new_processing_instruction_node(target: str, content: str) → ProcessingInstructionNode[source]¶
Creates a new
ProcessingInstructionNode
.- Parameters
target – The processing instruction’s target name.
content – The processing instruction’s text.
- Returns
The newly created processing instruction node.
- delb.new_tag_node(local_name: str, attributes: Optional[Dict[str, str]] = None, namespace: Optional[str] = None, children: Sequence[Union[str, NodeBase, _TagDefinition]] = ()) → TagNode[source]¶
Creates a new
TagNode
instance outside any context. It is preferable to usenew_tag_node()
, on instances of documents and nodes where the instance is the creation context.- Parameters
local_name – The tag name.
attributes – Optional attributes that are assigned to the new node.
namespace – An optional tag namespace.
children – An optional sequence of objects that will be appended as child nodes. This can be existing nodes, strings that will be inserted as text nodes and in-place definitions of
TagNode
instances fromtag()
. The latter will be assigned to the same namespace.
- Returns
The newly created tag node.
Queries with XPath & CSS¶
delb allows querying of nodes with CSS selector and XPath expressions. CSS selectors are converted to XPath expressions with a third-party library before evaluation and they are only supported as far as their computed XPath equivalents are supported by delb’s very own XPath implementation.
This implementation is not fully compliant with one of the W3C’s XPath specifications. It mostly covers the XPath 1.0 specs, but focuses on the querying via path expressions with simple constraints while it omits a broad employment of computations (that’s what programming languages are for) and has therefore these intended deviations from that standard:
Default namespaces can be addressed in node and attribute names, by simply using no prefix.
The attribute and namespace axes are not supported in location steps (see also below).
In predicates only the attribute axis can be used in its abbreviated form (
@name
).Path evaluations within predicates are not available.
- Only these predicate functions are provided and tested:
boolean
concat
contains
last
not
position
starts-with
text
Behaves as if deployed as a single step location path that only tests for the node type text. Hence it returns the contents of the context node’s first child node that is a text node or an empty string when there is none.
Please refrain from extension requests without a proper, concrete implementation proposal.
If you’re accustomed to retrieve attribute values with XPath expressions, employ the functionality of the higher programming language at hand like this:
>>> [x.attributes["target"] for x in root.xpath(".//foo")
... if "target" in x.attributes ]
Instead of:
>>> root.xpath(".//foo/@target")
See _delb.plugins.PluginManager.register_xpath_function()
regarding the use of
custom functions.
- class _delb.xpath.EvaluationContext(node: NodeBase, position: int, size: int, namespaces: Namespaces)[source]¶
Instances of this type are passed to XPath functions in order to pass contextual information.
- count(value, /)¶
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)¶
Return first index of value.
Raises ValueError if the value is not present.
- property namespaces¶
A mapping of prefixes to namespaces that is used in the whole evaluation.
- property node¶
The node that is evaluated.
- property position¶
The node’s position within all nodes that matched a location step’s node test in order of the step’s axis’ direction. The first position is 1.
- property size¶
The number of all nodes all nodes that matched a location step’s node test.
- class _delb.xpath.QueryResults(results: Iterable[NodeBase])[source]¶
A container that includes the results of a CSS selector or XPath query with some helpers for better readable Python expressions.
- count(value) → integer -- return number of occurrences of value¶
- filtered_by(*filters: _delb.typing.Filter) → QueryResults[source]¶
Returns another
QueryResults
instance that contains all nodes filtered by the provided filter s.
- property first: Optional[NodeBase]¶
The first node from the results or
None
if there are none.
- in_document_order() → QueryResults[source]¶
Returns another
QueryResults
instance where the contained nodes are sorted in document order.
- index(value[, start[, stop]]) → integer -- return first index of value.¶
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- property last: Optional[NodeBase]¶
The last node from the results or
None
if there are none.
Filters¶
Default filters¶
- delb.altered_default_filters(*filter: _delb.typing.Filter, extend: bool = False)[source]¶
This function can be either used as as context manager or decorator to define a set of
default_filters
for the encapsuled code block or callable. These are then applied in all operations that allow node filtering, likeTagNode.next_node()
. Mind that they also affect a node’s index property and indexed access to child nodes.>>> root = Document( ... '<root xmlns="foo"><a/><!--x--><b/><!--y--><c/></root>' ... ).root >>> with altered_default_filters(is_comment_node): ... print([x.content for x in root.iterate_children()]) ['x', 'y']
As the default filters shadow comments and processing instructions by default, use no argument to unset this in order to access all type of nodes.
- Parameters
extend – Extends the currently active filters with the given ones instead of replacing them.
Contributed filters¶
- delb.any_of(*filter: _delb.typing.Filter) → _delb.typing.Filter[source]¶
A node filter wrapper that matches when any of the given filters is matching, like a boolean
or
.
- delb.is_comment_node(node: NodeBase) → bool[source]¶
A node filter that matches
CommentNode
instances.
- delb.is_processing_instruction_node(node: NodeBase) → bool[source]¶
A node filter that matches
ProcessingInstructionNode
instances.
Transformations¶
This module offers a canonical interface with the aim to make re-use of transforming algorithms easier.
Let’s look at it with examples:
from delb.transform import Transformation
class ResolveCopyOf(Transformation):
def transform(self):
for node in self.root.css_select("*[copyOf]"):
source_id = node["copyOf"]
source_node = self.origin_document.xpath(
f'//*[@xml:id="{source_id[1:]}"]'
).first
cloned_node = source_node.clone(deep=True)
cloned_node.id = None
node.replace_with(cloned_node)
From such defined transformations instances can be called with a (sub-)tree and an optional document where that tree originates from:
resolve_copy_of = ResolveCopyOf()
tree = resolve_copy_of(tree) # where tree is an instance of TagNode
typing.NamedTuple
are used to define options for transformations:
from typing import NamedTuple
class ResolveChoiceOptions(NamedTuple):
corr: bool = True
reg: bool = True
class ResolveChoice(Transformation):
options_class = ResolveChoiceOptions
def __init__(self, options):
super().__init__(options)
self.keep_selector = ",".join(
(
"corr" if self.options.corr else "sic",
"reg" if self.options.reg else "orig"
)
)
self.drop_selector = ",".join(
(
"sic" if self.options.corr else "corr",
"orig" if self.options.reg else "reg"
)
)
def transform(self):
for choice_node in self.root.css_select("choice"):
node_to_drop = choice_node.css_select(self.drop_selector).first
node_to_drop.detach()
node_to_keep = choice_node.css_select(self.keep_selector).first
node_to_keep.detach(retain_child_nodes=True)
choice_node.detach(retain_child_nodes=True)
A transformation class that defines an option_class
property can then either be used
with its defaults or with alternate options:
resolve_choice = ResolveChoice()
tree = resolve_choice(tree)
resolve_choice = ResolveChoice(ResolveChoiceOptions(reg=False))
tree = resolve_choice(tree)
Finally, concrete transformations can be chained, both as classes or instances. The interface allows also to chain multiple chains:
from delb.transform import TransformationSequence
tidy_up = TransformationSequence(ResolveCopyOf, resolve_choice)
tree = tidy_up(tree)
Attention
This is an experimental feature. It might change significantly in the future or be removed altogether.
- class delb.transform.Transformation(options: Optional[NamedTuple] = None)[source]¶
This is a base class for any transformation algorithm.
- abstract transform()[source]¶
This method needs to implement the transformation logic. When it is called, the instance has two attributes assigned from its call:
root
is the node that the transformation was called to transform with.origin_document
is the document that was possibly passed as second argument.
- class delb.transform.TransformationBase[source]¶
This base class defines the calling interface of transformations.
- class delb.transform.TransformationSequence(*transformations: Union[TransformationBase, Type[TransformationBase]])[source]¶
A transformation sequence can be used to combine any number of both
Transformation
(provided as class or instantiated with options) and otherTransformationSequence
instances or classes.
Various helpers¶
- delb.first(iterable: Iterable) → Optional[Any][source]¶
Returns the first item of the given iterable or
None
if it’s empty. Note that the first item is consumed when the iterable is an iterator.
- delb.get_traverser(from_left=True, depth_first=True, from_top=True)[source]¶
Returns a function that can be used to traverse a (sub)tree with the given node as root. While traversing the given root node is yielded at some point.
The returned functions have this signature:
def traverser(root: NodeBase, *filters: Filter) -> Iterator[NodeBase]: ...
- Parameters
from_left – The traverser yields sibling nodes from left to right if
True
, or starting from the right ifFalse
.depth_first – The child nodes resp. the parent node are yielded before the siblings of a node by a traverser if
True
. Siblings are favored ifFalse
.from_top – The traverser starts yielding nodes with the lowest depth if
True
. WhenFalse
, again, the opposite is in effect.
- delb.last(iterable: Iterable) → Optional[Any][source]¶
Returns the last item of the given iterable or
None
if it’s empty. Note that the whole iterator is consumed when such is given.
- delb.register_namespace(prefix: str, namespace: str)[source]¶
Registers a namespace prefix that newly created
TagNode
instances in that namespace will use in serializations.The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. It has however no effect on the serialization of existing nodes, see
Document.cleanup_namespace()
for that.- Parameters
prefix – The prefix to register.
namespace – The targeted namespace.
- delb.tag(local_name: str)[source]¶
- delb.tag(local_name: str, attributes: Mapping[str, str])
- delb.tag(local_name: str, child: Union[str, NodeBase, _TagDefinition])
- delb.tag(local_name: str, children: Sequence[Union[str, NodeBase, _TagDefinition]])
- delb.tag(local_name: str, attributes: Mapping[str, str], child: Union[str, NodeBase, _TagDefinition])
- delb.tag(local_name: str, attributes: Mapping[str, str], children: Sequence[Union[str, NodeBase, _TagDefinition]])
This function can be used for in-place creation (or call it templating if you want to) of
TagNode
instances as:node
argument to methods that add nodes to a treeitems in the
children
argument ofnew_tag_node()
andNodeBase.new_tag_node()
The first argument to the function is always the local name of the tag node. Optionally, the second argument can be a mapping that specifies attributes for that node. The optional last argument is either a single object that will be appended as child node or a sequence of such, these objects can be node instances of any type, strings (for derived
TextNode
instances) or other definitions from this function (for derivedTagNode
instances).The actual nodes that are constructed always inherit the namespace of the context node they are created in.
>>> root = new_tag_node('root', children=[ ... tag("head", {"lvl": "1"}, "Hello!"), ... tag("items", ( ... tag("item1"), ... tag("item2"), ... ) ... ) ... ]) >>> str(root) '<root><head lvl="1">Hello!</head><items><item1/><item2/></items></root>' >>> root.append_children(tag("addendum")) >>> str(root)[-26:] '</items><addendum/></root>'
Exceptions¶
- exception delb.exceptions.AmbiguousTreeError(message: str)[source]¶
Raised when a single node shall be fetched or created by an XPath expression in a tree where the target position can’t be clearly determined.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception delb.exceptions.DelbBaseException[source]¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception delb.exceptions.FailedDocumentLoading(source: Any, excuses: Dict[Callable[[Any, SimpleNamespace], Union[_ElementTree, str]], Union[str, Exception]])[source]¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception delb.exceptions.InvalidCodePath[source]¶
Raised when a code path that is not expected to be executed is reached.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception delb.exceptions.InvalidOperation[source]¶
Raised when an invalid operation is attempted by the client code.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception delb.exceptions.XPathEvaluationError(message: str)[source]¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
Extending delb¶
Note
There are actually two packages that are installed with delb:
delb
and _delb
. As the underscore indicates, the latter is exposing
private parts of the API while the first is re-exposing what is deemed to
be public from that one and additional contents.
As a rule of thumb, use the public API in applications and the private API
in delb extensions. By doing so, you can avoid circular dependencies if
your extension (or other code that it depends on) uses contents from the
_delb
package.
delb
offers a plugin system to facilitate the extendability of a few of its
mechanics with Python packages.
A package that extends its functionality must provide entrypoint metadata
for an entrypoint group named delb
that points to modules that contain
extensions. Some extensions have to be decorated with specific methods
of the plugin manager object. Authors are encouraged to prefix their package
names with delb-
in order to increase discoverability.
These extension types are currently available:
document loaders
document mixin classes
document subclasses
XPath functions
Loaders are functions that try to make sense of any given input value, and if they can they return a parsed document.
Mixin classes add functionality / attributes to the delb.Document
class (instead of inheriting from it). That allows applications to rely
optionally on the availability of plugins and to combine various extensions.
Subclasses can be used to provide distinct models of arbitrary aspects for contents that are represented by a specific encoding. They can optionally implement a test method to qualify them as default class for recognized contents.
The designated means of communication between extensions is the config
argument to the loader respectively the instance property of a document instance
with that name.
Warning
A module that contains plugins and any module it is explicitly or implicitly
importing must not import anything from the delb
module itself,
because that would initiate the collection of plugin implementations. And
these wouldn’t have been completely registered at that point. Import from
the _delb
module instead.
Caution
Mind to re-install a package in development when its entrypoint specification changed.
There’s a repository that outlines the mechanics as developer reference: https://github.com/delb-xml/delb-py-reference-plugins
There’s also the snakesist project that implements the loader and document mixin plugin types to interact with eXist-db as storage.
Document loaders¶
Loaders are registered with this decorator:
- _delb.plugins.plugin_manager.register_loader(before: Optional[Union[Callable[[Any, SimpleNamespace], Union[_ElementTree, str]], Iterable[Callable[[Any, SimpleNamespace], Union[_ElementTree, str]]]]] = None, after: Optional[Union[Callable[[Any, SimpleNamespace], Union[_ElementTree, str]], Iterable[Callable[[Any, SimpleNamespace], Union[_ElementTree, str]]]]] = None) → Callable¶
Registers a document loader.
An example module that is specified as
delb
plugin for an IPFS loader might look like this:from os import getenv from types import SimpleNamespace from typing import Any from _delb.plugins import plugin_manager from _delb.plugins.https_loader import https_loader from _delb.typing import LoaderResult IPFS_GATEWAY = getenv("IPFS_GATEWAY_PREFIX", "https://ipfs.io/ipfs/") @plugin_manager.register_loader() def ipfs_loader(source: Any, config: SimpleNamespace) -> LoaderResult: if isinstance(source, str) and source.startswith("ipfs://"): config.source_url = source config.ipfs_gateway_source_url = IPFS_GATEWAY + source[7:] return https_loader(config.ipfs_gateway_source_url, config) # return an indication why this loader didn't attempt to load in order # to support debugging return "The input value is not an URL with the ipfs scheme."
The
source
argument is what aDocument
instance is initialized with as input data.Note that the
config
argument that is passed to a loader function contains configuration data, it’s thedelb.Document.config
property after_init_config
has been processed.Loaders that retrieve a document from an URL should add the origin as string to the
config
object assource_url
.You might want to specify a loader to be considered before or after another one. Let’s assume a loader shall figure out what to load from a remote XML resource that contains a reference to the actual document. That one would have to be considered before the one that loads XML documents from a URL with the https scheme:
from _delb.plugins import plugin_manager from _delb.plugins.https_loader import https_loader @plugin_manager.register_loader(before=https_loader) def mets_loader(source, config) -> LoaderResult: # loading logic here pass
Document extensions¶
Document mixin classes are registered by subclassing them from this base class:
- class _delb.plugins.DocumentMixinBase[source]¶
By deriving a subclass from this one, a document extension class is registered as plugin. These are supposed to add additional attributes to a document, e.g. derived data or methods to interact with storage systems. All attributes of an extension should share a common prefix that terminates with an underscore, e.g. storage_load, storage_save, etc.
This base class also acts as termination for methods that can be implemented by mixin classes. Any implementation of a method must call a base class’ one, e.g.:
from types import SimpleNamespace from _delb.plugins import DocumentMixinBase from magic_wonderland import play_disco class MyExtension(DocumentMixinBase): # this method can be implemented by any extension class @classmethod def _init_config(cls, config, kwargs): config.my_extension = SimpleNamespace(conf=kwargs.pop( "my_extension_conf")) super()._init_config(config, kwargs) # this method is specific to this extension def my_extension_makes_magic(self): play_disco()
- classmethod _init_config(config: SimpleNamespace, kwargs: Dict[str, Any])[source]¶
The
kwargs
argument contains the additional keyword arguments that aDocument
instance is called with. Extension classes that expect configuration data must process their specific arguments by clearing them from thekwargs
dictionary, e.g. withdict.pop()
, and preferably storing the final configuration data in atypes.SimpleNamespace
and adding it to thetypes.SimpleNamespace
passed asconfig
with the extension’s name. The initially mentioned keyword arguments should be prefixed with that name as well. This method is called before the loaders try to read and parse the given source for a document.
Document subclasses¶
Of course one can simply subclass delb.Document
to add functionality.
Beside using a subclass directly, you can let delb.Document
figure out
which subclass is an appropriate representation of the content. Subclasses can
claim that by implementing a staticmethod()
named _class_test__
that
takes the document’s root node and the configuration to return a boolean that
indicates the subclass is suited. The first class to return a True
value
will immediately be chosen, so be aware of the possible ambiguity in complex
setups. It is only ensured that subclasses are considered before others that
they derive from.
Subclasses are registered by importing them into an application, they must not be pointed to by entrypoint definitions.
Here’s an example:
class TEIDocument(Document):
def __init__(self, *args, **kwargs):
super().__init__(*args, **{**kwargs, "collapse_whitespace": True})
@staticmethod
def __class_test__(root: TagNode, config: types.SimpleNamespace) -> bool:
return root.universal_name == "{http://www.tei-c.org/ns/1.0}TEI"
@property
def title(self) -> str:
return self.css_select('titleStmt title[type="main"]').first.full_text
document = Document("""\
<?xml version="1.0" encoding="UTF-8"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0"><teiHeader><fileDesc><titleStmt>
<title type="main">The Document's Title</title>
</titleStmt></fileDesc></teiHeader></TEI>
""")
if isinstance(document, TEIDocument):
print(document.title)
else:
print("Sorry, I don't know how to retrieve the document's title.")
The Document's Title
The recommendations as laid out for DocumentMixinHooks._init_config
also apply for subclasses who
would process configuration arguments in their __init__
method before
calling the super class’ one.
XPath functions¶
Custom XPath functions are registered with this decorator:
- _delb.plugins.PluginManager.register_xpath_function(self, arg: Union[Callable, str]) → Callable¶
Custom XPath functions can be defined as shown in the following example. The first argument to a function is always an instance of
_delb.xpath.EvaluationContext
followed by the expression’s arguments.from delb import Document from _delb.plugins import plugin_manager from _delb.xpath import EvaluationContext @plugin_manager.register_xpath_function("is-last") def is_last(context: EvaluationContext) -> bool: return context.position == context.size @plugin_manager.register_xpath_function def lowercase(_, string: str) -> str: return string.lower() document = Document("<root><node/><node foo='BAR'/></root>") print(document.xpath("/*[is-last() and lowercase(@foo)='bar']").first)
<node foo="BAR"/>
Changes¶
Every time I thought I’d got it made
It seemed the taste was not so sweet
The listed updates resemble rather a Best Of than a full record of changes. Intentionally.
0.4 (2022-11-02)¶
News¶
delb now uses its own XPath implementation, please investigate
_delb.xpath
for details.⚠️Many of the nodes’ methods that relate to relative nodes have been renamed. Watch out for
DeprecationWarning
s!⚠️The method
delb.NodeBase.iterate_descendants()
is added as a replacement for the formerdelb.NodeBase.child_nodes()
invoked with the now deprecated argumentrecurse
.⚠️The
https-loader
extensions is now required for loading documents via plain and secured HTTP connections.Under the hood httpx is now employed as HTTP/S client.
⚠️The contributed loader for FTP connections is marked as deprecated.
⚠️The
parser
argument todelb.Document
anddelb.TagNode.parse()
is deprecated and replaced byparser_options
.⚠
delb.Document.xslt()
is marked as deprecated.⚠️Evoked exceptions changed in various places.
⚠️Document mixin extensions are now facilitated by subclassing
_delb.plugins.DocumentMixinBase
. It replaces_delb.plugins.DocumentExtensionHooks
and_delb.plugins.PluginManager.register_document_mixin()
without a backward-compatible mechanic.Support for the very good Python 3.10 and the even better 3.11 is added.
The code repository is now part of an umbrella namespace for related projects: https://github.com/delb-xml/
A
CITATTION.cff
is available in the repository and shipped with source distributions for researchers that are citing their employed software.
0.3 (2022-01-31)¶
News¶
- Adds the
delb.TagNode.fetch_or_create_by_xpath()
method. ⚠️Because of that a pre-mature parser of XPath expressions has been implemented and you can expect some expressions to cause failures, e.g. with functions that take more than one argument.
- Adds the
Subclasses of
delb.Document
can claim to be the default class based on the evaluation of a document’s content and configuration by implementing__class_test__
.⚠️
_delb.plugins.PluginManager._register_document_extension()
is renamed to_delb.plugins.PluginManager._register_document_mixin()
.⚠️
_delb.plugins.DocumentExtensionHooks()
is renamed to_delb.plugins.DocumentMixinHooks()
.⚠️
_delb.plugins.DocumentMixinHooks._init_config()
is now aclassmethod()
and now also takes the config namespace as first argument.Adds
delb.Document.collapse_whitespace()
and the initialization option fordelb.Document
instances with the same name.Adds the
retain_child_nodes
argument todelb.NodeBase.detach()
.Adds the
delb.NodeBase.last_descendant
property.Adds the
delb.TagNode.id
property.Adds the
delb.TagNode.parse()
method.⚠️
TagNode.qualified_name()
is marked deprecated and the same property is now available asTagNode.universal_name()
.Adds support for Python 3.9 & 3.10.
⚠️ Drops support for Python 3.6
Uses GitHub actions for CI checks.
Fixes¶
Detached
delb.TagNode
s now drop references todelb.TextNode
siblings.Ensures that
delb.TagNode.location_path
always consists of indexed steps (/*[i]
) only.Avoids hitting the interpreter’s recursion limit when iterating in stream dimension.
0.2 (2020-07-26)¶
News¶
Adds a logo. Gracious thanks to sm!
Adds plugin mechanics. Graciae ad infinitum, TC!
CSS and XPath query results are wrapped in
delb.QueryResults
.Adds
delb.Document.head_nodes
anddelb.Document.tail_nodes
that allow access to the siblings of a root node.Adds the
delb.Document.source_url
property.Adds
delb.get_traverser()
and two traverser implementations that yield nodes related to a root node according to their defined order.Document loaders report back the reason why they would or could not load a document from the given object.
Various documentation improvements, including table of contents for class members.
0.1.2 (2019-09-14)¶
There’s nothing super-exciting to report here. It’s just getting better.
0.1.1 (2019-08-15)¶
This was quiet boring, it serves updated dependencies for what it’s worth.
0.1 (2019-05-26)¶
The initial release with a set and sound data model and API.
Glossary¶
- filter¶
Filter functions can be used as arguments with various methods on node instances that return other nodes. They are called with a node instance as only argument and they should return a
bool
to indicate whether the node matches the filter. Have a look at the Filters source code for examples.- tag node¶
Tag nodes are the equivalent to the DOM’s element node. Its name shall make it distinguishable from the ElementTree API and relates to the nodes’ functionality of tagging text.
Index¶
License¶
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.