This module contains all the central XML tree classes, the namespace classes, exception and warning classes and a few helper classes and functions.
def tonode(value):
convert value to an XIST Node.
If value is a tuple or list, it will be (recursively) converted to a
Frag. Integers, strings, etc. will be converted to a Text.
If value is a Node already, it will be returned unchanged.
In the case of None the XIST Null (ll.xist.xsc.Null) will be
returned. If value is iterable, a Frag will be generated
from the items. Anything else will raise an IllegalObjectError
exception.
class ThreadLocalNodeHander(thread._local):
class build(object):
A build object can be used as a with block handler to create a
new XIST tree:
with xsc.build():
with html.ul() as e:
+html.li("gurk")
+html.li("hurz")def __init__(self):
selfdef __enter__(self):
selfdef __exit__(self, type, value, traceback):
selfdef enter(self, node):
selfdef exit(self):
selfdef add(self, *args, **kwargs):
selfclass addattr(object):
An addattr object can be used as a with block handler to modify
an attribute of an element:
with xsc.build():
with html.div() as e:
with xsc.addattr("align"):
+xsc.Text("right")def __init__(self, attrname):
selfCreate an addattr object for adding to the attribute named
attrname (which can be the Python name of an attribute or an
attribute class).
def __enter__(self):
selfdef __exit__(self, type, value, traceback):
selfdef add(self, *args):
selfdef add(*args, **kwargs):
add appends items in args and sets attributes in
kwargs in the currenly active node in the with stack.
class WalkFilter(object):
A WalkFilter can be passed to the walk method of nodes to
specify how to traverse the tree and which nodes to output.
def filternode(self, *args, **kwargs):
selfdef filterpath(self, path):
selfclass FindType(WalkFilter):
Tree traversal filter that finds nodes of a certain type on the first level of the tree without decending further down.
def __init__(self, *types):
selfdef filternode(self, node):
selfclass FindTypeAll(WalkFilter):
Tree traversal filter that finds nodes of a certain type searching the complete tree.
def __init__(self, *types):
selfdef filternode(self, node):
selfclass FindTypeAllAttrs(WalkFilter):
Tree traversal filter that finds nodes of a certain type searching the complete tree (including attributes).
def __init__(self, *types):
selfdef filternode(self, node):
selfclass FindTypeTop(WalkFilter):
Tree traversal filter that finds nodes of a certain type searching the complete tree, but traversal of the children of a node is skipped if this node is of the specified type.
def __init__(self, *types):
selfdef filternode(self, node):
selfclass CallableWalkFilter(WalkFilter):
Tree traversal filter that returns the result of a function call.
def __init__(self, func):
selfdef filterpath(self, path):
selfclass ConstantWalkFilter(WalkFilter):
Tree traversal filter that returns the same value for all nodes.
def __init__(self, value):
selfdef filterpath(self, path):
selfdef makewalkfilter(obj):
class Context(object):
This is an empty class that can be used by the convert method to
hold element or namespace specific data during the convert call.
The method Converter.__getitem__ will return a unique instance of
this class.
class Error(exceptions.Exception):
Base class for all XIST exceptions
class Warning(exceptions.UserWarning):
Base class for all warning exceptions (i.e. those that won't result in a program termination.)
class IllegalAttrValueWarning(Warning):
Warning that is issued when an attribute has an illegal value when parsing or publishing.
def __init__(self, attr):
selfdef __str__(self):
selfclass RequiredAttrMissingWarning(Warning):
Warning that is issued when a required attribute is missing during parsing or publishing.
def __init__(self, attrs, reqattrs):
selfdef __str__(self):
selfclass IllegalPrefixError(Error, exceptions.LookupError):
Exception that is raised when a namespace prefix is undefined.
def __init__(self, prefix):
selfdef __str__(self):
selfclass IllegalElementError(Error, exceptions.LookupError):
Exception that is raised when an illegal element class is requested
def __init__(self, name, xmlns, xml=False):
selfdef __str__(self):
selfclass IllegalProcInstError(Error, exceptions.LookupError):
Exception that is raised when an illegal procinst class is requested
def __init__(self, name, xml=False):
selfdef __str__(self):
selfclass IllegalEntityError(Error, exceptions.LookupError):
Exception that is raised when an illegal entity class is requested
def __init__(self, name, xml=False):
selfdef __str__(self):
selfclass IllegalCharRefError(Error, exceptions.LookupError):
Exception that is raised when an illegal charref class is requested
def __init__(self, name, xml=False):
selfdef __str__(self):
selfclass IllegalAttrError(Error, exceptions.LookupError):
Exception that is raised when an illegal attribute is requested.
def __init__(self, name, cls, xml=False):
selfdef __str__(self):
selfclass MultipleRootsError(Error):
def __str__(self):
selfclass ElementNestingError(Error):
Exception that is raised when an element has an illegal nesting
(e.g. <a><b></a></b>)
def __init__(self, expectedelement, foundelement):
selfdef __str__(self):
selfclass FileNotFoundWarning(Warning):
Warning that is issued when a file can't be found.
def __init__(self, message, filename, exc):
selfdef __str__(self):
selfclass IllegalObjectError(Error, exceptions.TypeError):
Exception that is raised when an XIST constructor gets passed an unconvertable object.
def __init__(self, object):
selfdef __str__(self):
selfclass IllegalCommentContentWarning(Warning):
Warning that is issued when there is an illegal comment, i.e. one containing
-- or ending in -. (This can only happen when the comment was created
by code, not when parsed from an XML file.)
def __init__(self, comment):
selfdef __str__(self):
selfclass IllegalProcInstFormatError(Error):
Exception that is raised when there is an illegal processing instruction,
i.e. one containing ?>. (This can only happen when the processing
instruction was created by code, not when parsed from an XML file.)
def __init__(self, procinst):
selfdef __str__(self):
selfclass _Node_Meta(type):
def __repr__(self):
selfdef __div__(self, other):
selfdef __floordiv__(self, other):
selfdef __mul__(self, other):
selfdef __pow__(self, other):
selfdef __and__(self, other):
selfdef __or__(self, other):
selfdef __getitem__(self, index):
selfdef __invert__(self):
selfclass Node(object):
base class for nodes in the document tree. Derived classes may
overwrite convert or publish.
class Context(object):
This is an empty class that can be used by the convert method to
hold element or namespace specific data during the convert call.
The method Converter.__getitem__ will return a unique instance of
this class.
class __metaclass__(type):
def __repr__(self):
selfdef __div__(self, other):
selfdef __floordiv__(self, other):
selfdef __mul__(self, other):
selfdef __pow__(self, other):
selfdef __and__(self, other):
selfdef __or__(self, other):
selfdef __getitem__(self, index):
selfdef __invert__(self):
selfdef __repr__(self):
selfdef __ne__(self, other):
selfdef _strbase(cls, fullname, xml):
clsdef __pos__(self):
selfdef __div__(self, other):
selfdef __floordiv__(self, other):
selfdef __pow__(self, other):
selfdef __and__(self, other):
selfdef __or__(self, other):
selfdef clone(self):
selfreturn a clone of self. Compared to deepcopy clone
will create multiple instances of objects that can be found in the tree
more than once. clone can't clone trees that contain cycles.
def copy(self):
selfReturn a shallow copy of self.
def __copy__(self):
selfdef deepcopy(self):
selfReturn a deep copy of self.
def __deepcopy__(self, memo=None):
selfdef present(self, *args, **kwargs):
selfpresent is used as a central dispatch method for the
presenter classes. Normally it is not called by the user, but internally
by the presenter. The user should use the appropriate presenter class
directly.
def conv(self, converter=None, root=None, mode=None, stage=None, target=None, lang=None, function=None, makeaction=None, makeproject=None):
selfConvenience method for calling convert.
conv will automatically set :var:`converter`.node to self
to remember the "document root node" for which conv has been
called, this means that you should not call conv in any of the
recursive calls, as you would loose this information. Call convert
directly instead.
def convert(self, *args, **kwargs):
selfimplementation of the conversion method. When you define your own element classes you have to overwrite this method and implement the desired conversion.
This method must return an instance of Node. It may not change
self.
def __unicode__(self, *args, **kwargs):
selfReturn the character content of self as a unicode string. This
means that comments and processing instructions will be filtered out.
For elements you'll get the element content.
__unicode__ can be used everywhere where a plain string
representation of the node is required.
def __str__(self):
selfReturn the character content of self as a string (if possible, i.e.
there are no characters that are unencodable in the default encoding).
def __int__(self):
selfConvert the character content of self to an int.
def __long__(self):
selfConvert the character content of self to an long.
def asFloat(self, decimal='.', ignore=''):
selfConvert the character content of self to an float.
decimal specifies which decimal separator is used in the value
(e.g. "." (the default) or ","). ignore specifies which
characters will be ignored.
def __float__(self):
selfConvert the character content of self to an float.
def __complex__(self):
selfConvert the character content of self to an complex.
def parsed(self, parser, start=None):
selfThis method will be called by the parser parser once after
self is created by the parser and must return the node that is to
be put into the tree (in most cases this is self, it's used e.g.
by URLAttr to incorporate the base URL into the attribute).
For elements parsed will be called twice: Once at the beginning
(i.e. before the content is parsed) with start being True
and once at the end after parsing of the content is finished with
start being False. For the second call the return value
will be ignored.
def checkvalid(self):
selfThis method will be called when parsing or publishing to check whether :var`self` is valid.
If self is found to be invalid a warning should be issued through
the Python warning framework.
def publish(self, *args, **kwargs):
selfGenerate unicode strings for the node. publisher must be an
instance of ll.xist.publishers.Publisher.
The encoding and xhtml specification are taken from the publisher.
def iterbytes(self, base=None, publisher=None, **publishargs):
selfA generator that will produce this node as a serialized byte string.
For the possible parameters see the ll.xist.publishers.Publisher
constructor.
def bytes(self, base=None, publisher=None, **publishargs):
selfReturn self as a serialized byte string.
For the possible parameters see the ll.xist.publishers.Publisher
constructor.
def iterstring(self, base=None, publisher=None, **publishargs):
selfA generator that will produce a serialized byte string of self.
For the possible parameters see the ll.xist.publishers.Publisher
constructor.
def string(self, base=None, publisher=None, **publishargs):
selfReturn a serialized unicode string for self.
For the possible parameters see the ll.xist.publishers.Publisher
constructor.
def write(self, stream, base=None, publisher=None, **publishargs):
selfWrite self to the file-like object stream (which must provide
a write method).
For the rest of the parameters see the ll.xist.publishers.Publisher
constructor.
def _walk(self, walkfilter, path):
selfInternal helper for walk.
def walk(self, walkfilter=(True, ll.misc.entercontent)):
selfReturn an iterator for traversing the tree rooted at self.
walkfilter is used for specifying whether or not a node should be
yielded and when the children of this node should be traversed. If
walkfilter is callable, it will be called for each node visited
during the traversal. A path (i.e. a list of all nodes from the root to
the current node) will be passed to the filter on each call and the
filter must return a sequence of "node handling options". If
walkfilter is not callable, it must be a sequence of node
handling options that will be used for all visited nodes.
Entries in this returned sequence can be the following:
TrueThis tells
walkto yield this node from the iterator.FalseDon't yield this node from the iterator.
enterattrsThis is a global constant in
ll.xist.xscand tellswalkto traverse the attributes of this node (if it's anElement, otherwise this option will be ignored).entercontentThis is a global constant in
ll.xist.xscand tellswalkto traverse the child nodes of this node (if it's anElement, otherwise this option will be ignored).
These options will be executed in the order they are specified in the
sequence, so to get a top down traversal of a tree (without entering
attributes), (True, xsc.entercontent) can be used. For a bottom up
traversal (xsc.entercontent, True) can be used.
Each item produced by the iterator is a path list. walk reuses
this list, so you can't rely on the value of the list being the same
across calls to next.
def walknode(self, walkfilter=(True, ll.misc.entercontent)):
selfReturn an iterator for traversing the tree. filter works the same
as the walkfilter argument for walk. The items produced
by the iterator are the nodes themselves.
def walkpath(self, walkfilter=(True, ll.misc.entercontent)):
selfReturn an iterator for traversing the tree. walkfilter works
the same as the walkfilter argument for walk. The items
produced by the iterator are copies of the path.
def compact(self):
selfReturn a version of self, where textnodes or character references
that contain only linefeeds are removed, i.e. potentially useless
whitespace is removed.
def _decoratenode(self, node):
selfdef mapped(self, function, converter=None, **converterargs):
selfReturn the node mapped through the function function. This call
works recursively (for Frag and Element).
When you want an unmodified node you simply can return self.
mapped will make a copy of it and fill the content recursively.
Note that element attributes will not be mapped. When you return a
different node from function this node will be incorporated
into the result as-is.
def normalized(self):
selfReturn a normalized version of self, which means that consecutive
Text nodes are merged.
def __mul__(self, factor):
selfReturn a Frag with factor times the node as an entry.
Note that the node will not be copied, i.e. this is a
"shallow __mul__".
def __rmul__(self, factor):
selfReturn a Frag with factor times the node as an entry.
def pretty(self, level=0, indent='\t'):
selfReturn a prettyfied version of self, i.e. one with properly nested
and indented tags (as far as possible). If an element has mixed content
(i.e. Text and non-Text nodes) the content will be
returned as is.
Note that whitespace will prevent pretty printing too, so you might want
to call normalized and compact before calling
pretty to remove whitespace.
class CharacterData(Node):
Base class for XML character data (Text, ProcInst,
Comment and DocType).
(Provides nearly the same functionality as UserString,
but omits a few methods.)
def __init__(self, *content):
selfdef __getstate__(self):
selfdef __setstate__(self, content):
selfproperty content:
The text content of the node as a unicode object.
def __get__(self):
def __hash__(self):
selfdef __eq__(self, other):
selfdef __len__(self):
selfdef __getitem__(self, index):
selfdef __add__(self, other):
selfdef __radd__(self, other):
selfdef __mul__(self, n):
selfdef __rmul__(self, n):
selfdef __getslice__(self, index1, index2):
selfdef capitalize(self):
selfdef center(self, width):
selfdef count(self, sub, start=0, end=2147483647):
selfdef endswith(self, suffix, start=0, end=2147483647):
selfdef index(self, sub, start=0, end=2147483647):
selfdef isalpha(self):
selfdef isalnum(self):
selfdef isdecimal(self):
selfdef isdigit(self):
selfdef islower(self):
selfdef isnumeric(self):
selfdef isspace(self):
selfdef istitle(self):
selfdef isupper(self):
selfdef join(self, frag):
selfdef ljust(self, width, fill=u' '):
selfdef lower(self):
selfdef lstrip(self, chars=None):
selfdef replace(self, old, new, maxsplit=-1):
selfdef rjust(self, width, fill=u' '):
selfdef rstrip(self, chars=None):
selfdef rfind(self, sub, start=0, end=2147483647):
selfdef rindex(self, sub, start=0, end=2147483647):
selfdef split(self, sep=None, maxsplit=-1):
selfdef splitlines(self, keepends=0):
selfdef startswith(self, prefix, start=0, end=2147483647):
selfdef strip(self, chars=None):
selfdef swapcase(self):
selfdef title(self):
selfdef translate(self, table):
selfdef upper(self):
selfdef __repr__(self):
selfclass Text(CharacterData):
A text node. The characters <, >, & (and " inside
attributes) will be "escaped" with the appropriate character entities when
this node is published.
def convert(self, converter):
selfdef __unicode__(self):
selfdef publish(self, publisher):
selfdef present(self, presenter):
selfdef compact(self):
selfdef pretty(self, level=0, indent='\t'):
selfclass Frag(Node, list):
A fragment contains a list of nodes and can be used for dynamically
constructing content. The attribute content of an Element
is a Frag.
def __init__(self, *content):
selfdef __enter__(self):
selfdef __exit__(self, type, value, traceback):
selfdef __call__(self, *content):
selfdef _str(cls, fullname=True, xml=True, decorate=True):
clsdef _create(self):
selfinternal helper that is used to create an empty clone of self.
def clear(self):
selfMake self empty.
def convert(self, converter):
selfdef clone(self):
selfdef __copy__(self):
selfhelper for the copy module.
def __deepcopy__(self, memo=None):
selfhelper for the copy module.
def present(self, presenter):
selfdef __unicode__(self):
selfdef __eq__(self, other):
selfdef publish(self, publisher):
selfdef __getitem__(self, index):
selfReturn the index'th node of the content of the fragment. If
index is a list __getitem__ will work recursively.
If index is an empty list, self will be returned.
__getitem__ also supports walk filters.
def __setitem__(self, index, value):
selfAllows you to replace the index'th content node of the fragment
with the new value value (which will be converted to a node).
If index is a list __setitem__ will be applied to the
innermost index after traversing the rest of index recursively.
If index is an empty list, an exception will be raised.
__setitem__ also supports walk filters.
def __delitem__(self, index):
selfRemove the index'th content node from the fragment. If index
is a list, the innermost index will be deleted, after traversing the rest
of index recursively. If index is an empty list, an
exception will be raised. Anything except list, int and
slice objects will be turned into a walk filter and any child
node matching this filter will be deleted from self.
def __getslice__(self, index1, index2):
selfReturns a slice of the content of the fragment.
def __setslice__(self, index1, index2, sequence):
selfReplace a slice of the content of the fragment
def __mul__(self, factor):
selfReturn a Frag with factor times the content of self.
Note that no copies of the content will be generated, so this is a
"shallow __mul__".
__rmul__ = def __mul__(self, factor):
selfReturn a Frag with factor times the content of self.
Note that no copies of the content will be generated, so this is a
"shallow __mul__".
def __iadd__(self, other):
selfdef append(self, *others):
selfAppend every item in others to self.
def extend(self, items):
selfAppend all items from the sequence items to self.
def insert(self, index, *others):
selfInsert all items in others at the position index. (this is
the same as self[index:index] = others)
def _walk(self, filter, path):
selfdef compact(self):
selfdef withsep(self, separator, clone=False):
selfReturn a version of self with a separator node between the nodes of
self.
if clone is false, one node will be inserted several times, if
clone is true, clones of this node will be used.
def sorted(self, cmp=None, key=None, reverse=False):
selfReturn a sorted version of the self. cmp, key and
reverse have to same meaning as for the builtin function
sorted.
def reversed(self):
selfReturn a reversed version of the self.
def filtered(self, function):
selfReturn a filtered version of the self, i.e. a copy of self,
where only content nodes for which function returns true will
be copied.
def shuffled(self):
selfReturn a shuffled version of self, i.e. a copy of self where the
content nodes are randomly reshuffled.
def mapped(self, function, converter=None, **converterargs):
selfdef normalized(self):
selfdef pretty(self, level=0, indent='\t'):
selfdef __repr__(self):
selfclass Comment(CharacterData):
An XML comment.
def convert(self, converter):
selfdef __unicode__(self):
selfdef present(self, presenter):
selfdef publish(self, publisher):
selfclass _DocType_Meta(_Node_Meta):
def __repr__(self):
selfclass DocType(CharacterData):
An XML document type declaration.
class __metaclass__(_Node_Meta):
def __repr__(self):
selfdef convert(self, converter):
selfdef present(self, presenter):
selfdef publish(self, publisher):
selfdef __unicode__(self):
selfclass _ProcInst_Meta(_Node_Meta):
def __repr__(self):
selfclass ProcInst(CharacterData):
Base class for processing instructions.
Processing instructions for specific targets must be implemented as
subclasses of ProcInst.
class __metaclass__(_Node_Meta):
def __repr__(self):
selfdef _str(cls, fullname=True, xml=True, decorate=True):
clsdef convert(self, converter):
selfdef present(self, presenter):
selfdef publish(self, publisher):
selfdef __unicode__(self):
selfdef __repr__(self):
selfdef __mul__(self, n):
selfdef __rmul__(self, n):
selfclass AttrProcInst(ProcInst):
Special subclass of ProcInst.
When an AttrProcInst node is the first node in an attribute, it
takes over publishing of the attribute (via the methods publishattr
and publishboolattr). In all other cases the processing instruction
disappears completely.
def publish(self, publisher):
selfdef publishattr(self, *args, **kwargs):
selfPublish the attribute attr to the publisher publisher.
(Note that attr[0] is self).
def publishboolattr(self, *args, **kwargs):
selfPublish the boolean attribute attr to the publisher
publisher. (Note that attr[0] is self).
class _Attr_Meta(_Node_Meta):
def __repr__(self):
selfclass Attr(Frag):
Base class of all attribute classes.
The content of an attribute may be any other XIST node. This is different from a normal DOM, where only text and character references are allowed. The reason for this is to allow dynamic content (implemented as elements or processing instructions) to be put into attributes.
Of course, this dynamic content when finally converted to HTML should normally result in a fragment consisting only of text and character references. But note that it is allowed to have elements and processing instructions inside of attributes even when publishing. Processing instructions will be published as is and for elements their content will be published:
>>> from ll.xist.ns import html, php
>>> node = html.img(
... src=php.php("echo 'eggs.gif'"),
... alt=html.abbr(
... "EGGS",
... title="Extensible Graphics Generation System",
... lang="en"
... )
... )
>>> print node.bytes()
<img alt="EGGS" src="<?php echo 'eggs.gif'?>" />class __metaclass__(_Node_Meta):
def __repr__(self):
selfdef isfancy(self):
selfReturn whether self contains nodes other than Text.
def _str(cls, fullname=True, xml=True, decorate=True):
clsdef present(self, presenter):
selfdef checkvalid(self):
selfCheck whether self has an allowed value, i.e. one that is specified
in the class attribute values. If the value is not allowed a warning
will be issued through the Python warning framework.
If self is "fancy" (i.e. contains non-Text nodes), no
check will be done.
def _walk(self, walkfilter, path):
selfdef _publishname(self, publisher):
selfdef _publishattrvalue(self, publisher):
selfdef publish(self, publisher):
selfdef pretty(self, level=0, indent='\t'):
selfdef __repr__(self):
selfclass TextAttr(Attr):
Attribute class that is used for normal text attributes.
class IDAttr(Attr):
Attribute used for ids.
class NumberAttr(Attr):
Attribute class that is used for when the attribute value may be any kind of number.
class IntAttr(NumberAttr):
Attribute class that is used when the attribute value may be an integer.
class FloatAttr(NumberAttr):
Attribute class that is used when the attribute value may be a floating point value.
class BoolAttr(Attr):
Attribute class that is used for boolean attributes. When publishing the value will always be the attribute name, regardless of the real value.
def publish(self, publisher):
selfclass ColorAttr(Attr):
Attribute class that is used for a color attributes.
class StyleAttr(Attr):
Attribute class that is used for CSS style attributes.
def _transform(self, replacer):
selfdef replaceurls(self, replacer):
selfReplace each URL in the style. Each URL will be passed to the callable
replacer and replaced with the returned value.
def parsed(self, parser, start=None):
selfdef _publishattrvalue(self, publisher):
selfdef urls(self, base=None):
selfReturn a list of all the URLs (as URL objects) found in the style
attribute.
class URLAttr(Attr):
Attribute class that is used for URLs. See the module ll.url for more
information about URL handling.
def parsed(self, parser, start=None):
selfdef _publishattrvalue(self, publisher):
selfdef asURL(self):
selfReturn self as a URL object (note that non-Text
content will be filtered out).
def forInput(self, root=None):
selfreturn a URL pointing to the real location of the referenced
resource. root must be the root URL relative to which self
will be interpreted and usually comes from the root attribute of the
converter argument in convert.
def imagesize(self, root=None):
selfReturn the size of an image as a tuple.
def contentlength(self, root=None):
selfReturn the size of a file in bytes.
def lastmodified(self, root=None):
selfreturns the timestamp for the last modification to the file
def openread(self, root=None):
selfReturn a Resource for reading from the URL.
def openwrite(self, root=None):
selfReturn a Resource for writing to the URL.
class _Attrs_Meta(_Node_Meta):
def __repr__(self):
selfdef __contains__(self, key):
selfclass Attrs(Node, dict):
An attribute map. Allowed entries are specified through nested subclasses
of Attr.
class __metaclass__(_Node_Meta):
def __repr__(self):
selfdef __contains__(self, key):
selfdef __init__(self, _content=None, **attrs):
selfdef __eq__(self, other):
selfdef _str(cls, fullname=True, xml=True, decorate=True):
clsdef add(cls, value):
clsdef _create(self):
selfdef clone(self):
selfdef __copy__(self):
selfdef __deepcopy__(self, memo=None):
selfdef convert(self, converter):
selfdef compact(self):
selfdef normalized(self):
selfdef _walk(self, filter, path):
selfdef present(self, presenter):
selfdef checkvalid(self):
selfdef publish(self, publisher):
selfdef __unicode__(self):
selfdef isallowed(cls, name):
clsdef isallowed_xml(cls, name, xmlns=None):
clsdef __getattribute__(self, name):
selfdef __setattr__(self, name, value):
selfdef __delattr__(self, name):
selfdef __getitem__(self, name):
selfdef __setitem__(self, name, value):
selfdef __delitem__(self, name):
selfdef has(self, name):
selfReturn whether self has an attribute with a Python name name.
name may also be an attribute class (either from self.Attrs
or a global attribute).
def has_xml(self, name):
selfSimilar to has, but name is treated as the XML name
instead of the Python name.
def __contains__(self, name):
selfdef get(self, name, default=None):
selfworks like the dictionary method get, it returns the attribute
with the Python name name, or default if self has no
such attribute. name may also be an attribute class (either from
self.Attrs or a global attribute).
def get_xml(self, name, default=None):
selfSimilar to get, but name is treated as the XML name
instead of the Python name.
def set(self, name, value):
selfSet the attribute with the Python name to the value value.
name may be a string or an attribute class. The newly set attribute
will be returned.
def set_xml(self, name, value):
selfSimilar to set, but name is treated as the XML name
instead of the Python name.
def setdefault(self, name, default):
selfWorks like the dictionary method setdefault, it returns the
attribute with the Python name name. If self has no such
attribute, it will be set to default and default will be
returned as the new attribute value.
def setdefault_xml(self, name, default):
selfSimilar to setdefault, but name is treated as the XML name
instead of the Python name.
def update(self, *args, **kwargs):
selfCopies attributes over from all mappings in args and from
kwargs.
def allowedattrs(cls):
clsReturn an iterator over all allowed attribute classes.
def allowedattr(cls, name):
clsdef allowedattr_xml(cls, name):
clsdef __len__(self):
self__iter__ = def keys(self):
selfiterkeys = def keys(self):
selfdef keys(self):
selfitervalues = def values(self):
selfdef values(self):
selfdef items(self):
selfiteritems = def items(self):
selfdef _iterallvalues(self):
selfIterate through all values, even the unset ones.
def attr(self, name):
selfdef attr_xml(self, name):
selfdef filtered(self, function):
selfReturn a filtered version of self.
def _fixnames(self, names):
selfdef _fixnames_xml(self, names):
selfdef withnames(self, *names):
selfReturn a copy of self where only the attributes with Python names
in names are kept, all others are removed.
def withnames_xml(self, *names):
selfReturn a copy of self where only the attributes with XML names
in names are kept, all others are removed.
def withoutnames(self, *names):
selfReturn a copy of self where all the attributes with Python names
in names are removed.
def withoutnames_xml(self, *names):
selfReturn a copy of self where all the attributes with XML names
in names are removed.
def __repr__(self):
selfdef _patchclassnames(dict, name):
class _Element_Meta(_Node_Meta):
def __repr__(self):
selfclass Element(Node):
This class represents XML/XIST elements. All elements implemented by the user must be derived from this class.
Elements support the following class variables:
model(object withcheckvalidmethod)This is an object that is used for validating the content of the element. See the module
ll.xist.simsfor more info. IfmodelisNonevalidation will be skipped, otherwise it will be performed when parsing or publishing.Attrs(Element.Attrssubclass)This is a class derived from
Element.Attrsand must define all attributes as classes nested inside thisAttrsclass.xmlns(string)This is the name of the namespace this element belong to.
register(bool)If
registeris false the element will never be registered in aPool. The default isTrue.xmlname(string)If the class name has to be different from the XML name (e.g. because the XML name is not a valid Python identifier)
xmlnamecan be used to specify the real XML name. Otherwise the XML name will be the Python name.
class Attrs(Node, dict):
An attribute map. Allowed entries are specified through nested subclasses
of Attr.
class __metaclass__(_Node_Meta):
def __repr__(self):
selfdef __contains__(self, key):
selfdef __init__(self, _content=None, **attrs):
selfdef __eq__(self, other):
selfdef _str(cls, fullname=True, xml=True, decorate=True):
clsdef add(cls, value):
clsdef _create(self):
selfdef clone(self):
selfdef __copy__(self):
selfdef __deepcopy__(self, memo=None):
selfdef convert(self, converter):
selfdef compact(self):
selfdef normalized(self):
selfdef _walk(self, filter, path):
selfdef present(self, presenter):
selfdef checkvalid(self):
selfdef publish(self, publisher):
selfdef __unicode__(self):
selfdef isallowed(cls, name):
clsdef isallowed_xml(cls, name, xmlns=None):
clsdef __getattribute__(self, name):
selfdef __setattr__(self, name, value):
selfdef __delattr__(self, name):
selfdef __getitem__(self, name):
selfdef __setitem__(self, name, value):
selfdef __delitem__(self, name):
selfdef has(self, name):
selfReturn whether self has an attribute with a Python name name.
name may also be an attribute class (either from self.Attrs
or a global attribute).
def has_xml(self, name):
selfSimilar to has, but name is treated as the XML name
instead of the Python name.
def __contains__(self, name):
selfdef get(self, name, default=None):
selfworks like the dictionary method get, it returns the attribute
with the Python name name, or default if self has no
such attribute. name may also be an attribute class (either from
self.Attrs or a global attribute).
def get_xml(self, name, default=None):
selfSimilar to get, but name is treated as the XML name
instead of the Python name.
def set(self, name, value):
selfSet the attribute with the Python name to the value value.
name may be a string or an attribute class. The newly set attribute
will be returned.
def set_xml(self, name, value):
selfSimilar to set, but name is treated as the XML name
instead of the Python name.
def setdefault(self, name, default):
selfWorks like the dictionary method setdefault, it returns the
attribute with the Python name name. If self has no such
attribute, it will be set to default and default will be
returned as the new attribute value.
def setdefault_xml(self, name, default):
selfSimilar to setdefault, but name is treated as the XML name
instead of the Python name.
def update(self, *args, **kwargs):
selfCopies attributes over from all mappings in args and from
kwargs.
def allowedattrs(cls):
clsReturn an iterator over all allowed attribute classes.
def allowedattr(cls, name):
clsdef allowedattr_xml(cls, name):
clsdef __len__(self):
self__iter__ = def keys(self):
selfiterkeys = def keys(self):
selfdef keys(self):
selfitervalues = def values(self):
selfdef values(self):
selfdef items(self):
selfiteritems = def items(self):
selfdef _iterallvalues(self):
selfIterate through all values, even the unset ones.
def attr(self, name):
selfdef attr_xml(self, name):
selfdef filtered(self, function):
selfReturn a filtered version of self.
def _fixnames(self, names):
selfdef _fixnames_xml(self, names):
selfdef withnames(self, *names):
selfReturn a copy of self where only the attributes with Python names
in names are kept, all others are removed.
def withnames_xml(self, *names):
selfReturn a copy of self where only the attributes with XML names
in names are kept, all others are removed.
def withoutnames(self, *names):
selfReturn a copy of self where all the attributes with Python names
in names are removed.
def withoutnames_xml(self, *names):
selfReturn a copy of self where all the attributes with XML names
in names are removed.
def __repr__(self):
selfclass __metaclass__(_Node_Meta):
def __repr__(self):
selfdef __init__(self, *content, **attrs):
selfCreate a new Element instance.
Positional arguments are treated as content nodes. Keyword arguments and dictionaries are treated as attributes.
def __getstate__(self):
selfdef __setstate__(self, contentattrs):
selfdef __enter__(self):
selfElement nodes can be used in with blocks to build XIST trees.
Inside a with block + and add can be used to append node
to the currently active element in the with block:
with xsc.build():
with html.ul() as node:
+html.li("I hear and I forget.")
+html.li("I see and I believe.")
+html.li("I do and I understand.")
xsc.add(class_="quote")
print node.bytes()def __exit__(self, type, value, traceback):
selfdef __call__(self, *content, **attrs):
selfCalling an element add items in content to the element content
and set attributes from attrs. The element itself will be returned.
def __eq__(self, other):
selfdef _str(cls, fullname=True, xml=True, decorate=True):
clsdef checkvalid(self):
selfdef append(self, *items):
selfAppend every item in items to the elements content.
def extend(self, items):
selfAppend all items in items to the elements content.
def insert(self, index, *items):
selfInsert every item in items at the position index.
def convert(self, converter):
selfdef clone(self):
selfdef __copy__(self):
selfdef __deepcopy__(self, memo=None):
selfdef __unicode__(self):
selfdef _addimagesizeattributes(self, url, widthattr=None, heightattr=None):
selfAutomatically set image width and height attributes.
The size of the image with the URL url will be determined and the
width of the image will be put into the attribute with the name
widthattr if widthattr is not None and the
attribute is not set already. The same will happen for the height, which
will be put into the attribute named heighattr.
def present(self, presenter):
selfdef _publishname(self, publisher):
selfdef _publishfull(self, publisher):
selfDoes the full publication of the element. If you need full elements
inside attributes (e.g. for JSP tag libraries), you can overwrite
publish and simply call this method.
def publish(self, publisher):
selfdef __getitem__(self, index):
selfIf index is a string, return the attribute with this (Python)
name. If index is an attribute class, return the attribute
that is an instance of this class. If index is a number or slice
return the appropriate content node. index may also be a list, in
with case __getitem__ will be applied recusively.
__getitem__ also supports walk filters.
def __setitem__(self, index, value):
selfSet an attribute or content node to the value value. For possible
types for index see __getitem__.
def __delitem__(self, index):
selfRemove an attribute or content node. For possible types for index
see __getitem__.
def __getslice__(self, index1, index2):
selfReturn a copy of the element that contains a slice of the content.
def __setslice__(self, index1, index2, sequence):
selfReplace a slice of the content of the element.
def __delslice__(self, index1, index2):
selfRemove a slice of the content of the element.
def __iadd__(self, other):
selfdef __len__(self):
selfReturn the number of children.
def __iter__(self):
selfdef compact(self):
selfdef _walk(self, walkfilter, path):
selfdef withsep(self, separator, clone=False):
selfReturn a version of self with a separator node between the child
nodes of self. For more info see Frag.withsep.
def sorted(self, cmp=None, key=None, reverse=False):
selfReturn a sorted version of self. compare is a comparison
function. The arguments cmp, key and reverse have
the same meaning as fot the builtin sorted function.
def reversed(self):
selfReturn a reversed version of self.
def filtered(self, function):
selfReturn a filtered version of the self.
def shuffled(self):
selfReturn a shuffled version of the self.
def mapped(self, function, converter=None, **converterargs):
selfdef normalized(self):
selfdef pretty(self, level=0, indent='\t'):
selfdef __repr__(self):
selfclass _Entity_Meta(_Node_Meta):
def __repr__(self):
selfclass Entity(Node):
Class for entities. Derive your own entities from it and overwrite
convert.
class __metaclass__(_Node_Meta):
def __repr__(self):
selfdef _str(cls, fullname=True, xml=True, decorate=True):
clsdef __eq__(self, other):
selfdef compact(self):
selfdef present(self, presenter):
selfdef publish(self, publisher):
selfdef __repr__(self):
selfclass _CharRef_Meta(_Entity_Meta):
def __repr__(self):
selfclass CharRef(Text, Entity):
A simple named character reference, the codepoint is in the class attribute
codepoint.
class __metaclass__(_Entity_Meta):
def __repr__(self):
selfdef __init__(self):
selfdef __getnewargs__(self):
selfdef present(self, presenter):
selfdef __getitem__(self, index):
selfdef __add__(self, other):
selfdef __radd__(self, other):
selfdef __mul__(self, n):
selfdef __rmul__(self, n):
selfdef __getslice__(self, index1, index2):
selfdef capitalize(self):
selfdef center(self, width):
selfdef ljust(self, width, fill=u' '):
selfdef lower(self):
selfdef lstrip(self, chars=None):
selfdef replace(self, old, new, maxsplit=-1):
selfdef rjust(self, width, fill=u' '):
selfdef rstrip(self, chars=None):
selfdef strip(self, chars=None):
selfdef swapcase(self):
selfdef title(self):
selfdef translate(self, table):
selfdef upper(self):
selfclass Pool(ll.misc.Pool):
A Pool stores a collection of XIST classes and can be passed to a
parser. The parser will ask the pool which classes to use when elements,
processing instructions etc. have to be instantiated.
def __init__(self, *objects):
selfCreate a Pool object. All items in objects will be
registered in the pool.
def register(self, object):
selfRegister object in the pool. object can be:
a
Element,ProcInst,Entity, orCharRefclass;an
Attrclass for a global attribute;an
Attrsclass containing global attributes;a
dict(all values will be registered, this makes it possible to e.g. register all local variables by passingvars());a module (all attributes in the module will be registered).
def __enter__(self):
selfdef __exit__(self, type, value, traceback):
selfdef elements(self):
selfReturn an iterator for all registered element classes.
def elementclass(self, name, xmlns):
selfReturn the element class for the element with the Python name name
and the namespace xmlns. If the element can't be found an
IllegalElementError will be raised.
def elementclass_xml(self, name, xmlns):
selfReturn the element class for the element type with the XML name
name and the namespace xmlns. If the element can't
be found an IllegalElementError will be raised.
def element(self, name, xmlns):
selfReturn an element object for the element type with the Python name
name and the namespace xmlns.
def element_xml(self, name, xmlns):
selfReturn an element object for the element type with the XML name
name and the namespace xmlns.
def haselement(self, name, xmlns):
selfIs there a registered element class in self for the element type
with the Python name name and the namespace xmlns?
def haselement_xml(self, name, xmlns):
selfIs there a registered element class in self for the element type
with the XML name name and the namespace xmlns?
def procinsts(self):
selfReturn an iterator for all registered processing instruction classes.
def procinstclass(self, name):
selfReturn the processing instruction class for the PI with the Python name
name. If the processing instruction can't be found an
IllegalProcInstError will be raised.
def procinstclass_xml(self, name):
selfReturn the processing instruction class for the PI with the XML name
name. If the processing instruction can't be found an
IllegalProcInstError will be raised.
def procinst(self, name, content):
selfReturn a processing instruction object for the PI type with the Python
target name name.
def procinst_xml(self, name, content):
selfReturn a processing instruction object for the PI type with the XML
target name name.
def hasprocinst(self, name):
selfIs there a registered processing instruction class in self for the
PI with the Python name name?
def hasprocinst_xml(self, name):
selfIs there a registered processing instruction class in self for the
PI with the XML name name?
def entities(self):
selfReturn an iterator for all registered entity classes.
def entityclass(self, name):
selfReturn the entity class for the entity with the Python name name.
If the entity can't be found an IllegalEntityError will be raised.
def entityclass_xml(self, name):
selfReturn the entity class for the entity with the XML name name.
If the entity can't be found an IllegalEntityError will be raised.
def entity(self, name):
selfReturn an entity object for the entity with the Python name name.
def entity_xml(self, name):
selfReturn an entity object for the entity with the XML name name.
def hasentity(self, name):
selfIs there a registered entity class in self for the entity with the
Python name name?
def hasentity_xml(self, name):
selfIs there a registered entity class in self for the entity with the
XML name name?
def charrefs(self):
selfReturn an iterator for all character entity classes.
def charrefclass(self, name):
selfReturn the character entity with the Python name name.
name can also be an int specifying the codepoint.
If the character entity can't be found a IllegalEntityError
will be raised.
def charrefclass_xml(self, name):
selfReturn the character entity with the XML name name.
name can also be an int specifying the codepoint.
If the character entity can't be found a IllegalEntityError
will be raised.
def charref(self, name):
selfReturn a character entity object for the character with the Python name
or codepoint name.
def charref_xml(self, name):
selfReturn a character entity object for the character with the XML name
or codepoint name.
def hascharref(self, name):
selfIs there a registered character entity class in self with the
Python name or codepoint name?
def hascharref_xml(self, name):
selfIs there a registered character entity class in self with the XML
name or codepoint name?
def attrclass(self, name, xmlns):
selfReturn the attribute class for the global attribute with the Python name
name and the namespace xmlns. If the attribute can't
be found a IllegalAttrError will be raised.
def attrclass_xml(self, name, xmlns):
selfReturn the attribute class for the global attribute with the XML name
name and the namespace xmlns. If the attribute can't
be found a IllegalAttrError will be raised.
def text(self, content):
selfCreate a text node with the content content.
def comment(self, content):
selfCreate a comment node with the content content.
def __getattr__(self, key):
selfdef clear(self):
selfMake self empty.
def clone(self):
selfReturn a copy of self.
class ThreadLocalPool(thread._local):
def docprefixes():
Return a prefix mapping suitable for parsing XIST docstrings.
def nsname(xmlns):
If xmlns is a module, return xmlns.xmlns, else return
xmlns unchanged.
def nsclark(xmlns):
Return a namespace name in Clark notation. xmlns can be None,
a string or a module.
class quot(CharRef):
quotation mark = APL quote, U+0022 ISOnum
class amp(CharRef):
ampersand, U+0026 ISOnum
class lt(CharRef):
less-than sign, U+003C ISOnum
class gt(CharRef):
greater-than sign, U+003E ISOnum
class apos(CharRef):
apostrophe mark, U+0027 ISOnum
class Location(object):
Represents a location in an XML entity.
def __init__(self, url=None, line=None, col=None):
selfCreate a new Location object using the arguments passed in.
url is the URL/filename. line is the line number and
col is the column number (both starting at 0).
def offset(self, offset):
selfReturn a location where the line number is incremented by offset (and the column number is reset to 0).
def __str__(self):
selfdef __repr__(self):
selfdef __eq__(self, other):
selfdef __ne__(self, other):
selfdef __xattrs__(self, mode='default'):
selfdef __xrepr__(self, mode='default'):
self