[Lxml-checkins] r51452 - in lxml/trunk: . src/lxml src/lxml/html
scoder at codespeak.net
scoder at codespeak.net
Wed Feb 13 21:48:40 CET 2008
Author: scoder
Date: Wed Feb 13 21:48:39 2008
New Revision: 51452
Modified:
lxml/trunk/ (props changed)
lxml/trunk/CHANGES.txt
lxml/trunk/Makefile
lxml/trunk/src/lxml/classlookup.pxi
lxml/trunk/src/lxml/docloader.pxi
lxml/trunk/src/lxml/dtd.pxi
lxml/trunk/src/lxml/extensions.pxi
lxml/trunk/src/lxml/html/usedoctest.py
lxml/trunk/src/lxml/iterparse.pxi
lxml/trunk/src/lxml/lxml.etree.pyx
lxml/trunk/src/lxml/lxml.objectify.pyx
lxml/trunk/src/lxml/nsclasses.pxi
lxml/trunk/src/lxml/objectpath.pxi
lxml/trunk/src/lxml/parser.pxi
lxml/trunk/src/lxml/relaxng.pxi
lxml/trunk/src/lxml/schematron.pxi
lxml/trunk/src/lxml/usedoctest.py
lxml/trunk/src/lxml/xinclude.pxi
lxml/trunk/src/lxml/xmlerror.pxi
lxml/trunk/src/lxml/xmlid.pxi
lxml/trunk/src/lxml/xmlschema.pxi
lxml/trunk/src/lxml/xpath.pxi
lxml/trunk/src/lxml/xslt.pxi
Log:
r3463 at delle: sbehnel | 2008-02-13 00:07:06 +0100
huge docstring update to make signatures visible
Modified: lxml/trunk/CHANGES.txt
==============================================================================
--- lxml/trunk/CHANGES.txt (original)
+++ lxml/trunk/CHANGES.txt Wed Feb 13 21:48:39 2008
@@ -8,6 +8,9 @@
Features added
--------------
+* Docstrings now reflect the signature of functions and methods to
+ make them visible in API docs and ``help()``
+
Bugs fixed
----------
Modified: lxml/trunk/Makefile
==============================================================================
--- lxml/trunk/Makefile (original)
+++ lxml/trunk/Makefile Wed Feb 13 21:48:39 2008
@@ -42,7 +42,7 @@
rm -fr doc/html/api
@[ -x "`which epydoc`" ] \
&& (cd src && echo "Generating API docs ..." && \
- PYTHONPATH=. epydoc -v -o ../doc/html/api --name lxml --url http://codespeak.net/lxml/ lxml/) \
+ PYTHONPATH=. epydoc -v --docformat "restructuredtext en" -o ../doc/html/api --name lxml --url http://codespeak.net/lxml/ lxml/) \
|| (echo "not generating epydoc API documentation")
# XXX What should the default be?
Modified: lxml/trunk/src/lxml/classlookup.pxi
==============================================================================
--- lxml/trunk/src/lxml/classlookup.pxi (original)
+++ lxml/trunk/src/lxml/classlookup.pxi Wed Feb 13 21:48:39 2008
@@ -53,7 +53,9 @@
# class to store element class lookup functions
cdef public class ElementClassLookup [ type LxmlElementClassLookupType,
object LxmlElementClassLookup ]:
- """Superclass of Element class lookups.
+ """ElementClassLookup(self)
+
+ Superclass of Element class lookups.
"""
cdef _element_class_lookup_function _lookup_function
def __init__(self):
@@ -62,18 +64,20 @@
cdef public class FallbackElementClassLookup(ElementClassLookup) \
[ type LxmlFallbackElementClassLookupType,
object LxmlFallbackElementClassLookup ]:
- """Superclass of Element class lookups with additional fallback.
+ """FallbackElementClassLookup(self, fallback=None)
+
+ Superclass of Element class lookups with additional fallback.
"""
cdef readonly ElementClassLookup fallback
cdef _element_class_lookup_function _fallback_function
def __init__(self, ElementClassLookup fallback=None):
self._lookup_function = NULL # use default lookup
if fallback is not None:
- self.setFallback(fallback)
+ self._setFallback(fallback)
else:
self._fallback_function = _lookupDefaultElementClass
- def setFallback(self, ElementClassLookup lookup not None):
+ cdef void _setFallback(self, ElementClassLookup lookup):
"""Sets the fallback scheme for this lookup method.
"""
self.fallback = lookup
@@ -81,6 +85,20 @@
if self._fallback_function is NULL:
self._fallback_function = _lookupDefaultElementClass
+ def set_fallback(self, ElementClassLookup lookup not None):
+ """set_fallback(self, lookup)
+
+ Sets the fallback scheme for this lookup method.
+ """
+ self._setFallback(lookup)
+
+ def setFallback(self, ElementClassLookup lookup not None):
+ """Sets the fallback scheme for this lookup method.
+
+ :deprecated: use ``set_fallback()`` instead.
+ """
+ self._setFallback(lookup)
+
cdef object _callFallback(self, _Document doc, xmlNode* c_node):
return self._fallback_function(self.fallback, doc, c_node)
@@ -89,7 +107,8 @@
# Custom Element class lookup schemes
cdef class ElementDefaultClassLookup(ElementClassLookup):
- """Element class lookup scheme that always returns the default Element
+ """ElementDefaultClassLookup(self, element=None, comment=None, pi=None, entity=None)
+ Element class lookup scheme that always returns the default Element
class.
The keyword arguments ``element``, ``comment``, ``pi`` and ``entity``
@@ -163,13 +182,14 @@
assert 0, "Unknown node type: %s" % c_node.type
cdef class AttributeBasedElementClassLookup(FallbackElementClassLookup):
- """Checks an attribute of an Element and looks up the value in a class
- dictionary.
+ """AttributeBasedElementClassLookup(self, attribute_name, class_mapping, fallback=None)
+ Checks an attribute of an Element and looks up the value in a
+ class dictionary.
Arguments:
- * attribute name - '{ns}name' style string
- * class mapping - Python dict mapping attribute values to Element classes
- * fallback - optional fallback lookup mechanism
+ - attribute name - '{ns}name' style string
+ - class mapping - Python dict mapping attribute values to Element classes
+ - fallback - optional fallback lookup mechanism
A None key in the class mapping will be checked if the attribute is
missing.
@@ -207,7 +227,8 @@
cdef class ParserBasedElementClassLookup(FallbackElementClassLookup):
- """Element class lookup based on the XML parser.
+ """ParserBasedElementClassLookup(self, fallback=None)
+ Element class lookup based on the XML parser.
"""
def __init__(self, ElementClassLookup fallback=None):
FallbackElementClassLookup.__init__(self, fallback)
@@ -221,7 +242,8 @@
cdef class CustomElementClassLookup(FallbackElementClassLookup):
- """Element class lookup based on a subclass method.
+ """CustomElementClassLookup(self, fallback=None)
+ Element class lookup based on a subclass method.
You can inherit from this class and override the method::
@@ -240,6 +262,7 @@
self._lookup_function = _custom_class_lookup
def lookup(self, type, doc, namespace, name):
+ "lookup(self, type, doc, namespace, name)"
return None
cdef object _custom_class_lookup(state, _Document doc, xmlNode* c_node):
@@ -291,11 +314,14 @@
LOOKUP_ELEMENT_CLASS = function
def setElementClassLookup(ElementClassLookup lookup = None):
- "@deprecated: use ``set_element_class_lookup(lookup)`` instead"
+ ":deprecated: use ``set_element_class_lookup(lookup)`` instead"
set_element_class_lookup(lookup)
def set_element_class_lookup(ElementClassLookup lookup = None):
- "Set the global default element class lookup method."
+ """set_element_class_lookup(lookup = None)
+
+ Set the global default element class lookup method.
+ """
if lookup is None or lookup._lookup_function is NULL:
_setElementClassLookupFunction(NULL, None)
else:
Modified: lxml/trunk/src/lxml/docloader.pxi
==============================================================================
--- lxml/trunk/src/lxml/docloader.pxi (original)
+++ lxml/trunk/src/lxml/docloader.pxi Wed Feb 13 21:48:39 2008
@@ -15,7 +15,9 @@
cdef class Resolver:
"This is the base class of all resolvers."
def resolve(self, system_url, public_id, context):
- """Override this method to resolve an external source by
+ """resolve(self, system_url, public_id, context)
+
+ Override this method to resolve an external source by
``system_url`` and ``public_id``. The third argument is an
opaque context object.
@@ -24,7 +26,9 @@
return None
def resolve_empty(self, context):
- """Return an empty input document.
+ """resolve_empty(self, context)
+
+ Return an empty input document.
Pass context as parameter.
"""
@@ -34,7 +38,9 @@
return doc_ref
def resolve_string(self, string, context, *, base_url=None):
- """Return a parsable string as input document.
+ """resolve_string(self, string, context, base_url=None)
+
+ Return a parsable string as input document.
Pass data string and context as parameters.
@@ -49,7 +55,9 @@
return doc_ref
def resolve_filename(self, filename, context):
- """Return the name of a parsable file as input document.
+ """resolve_filename(self, filename, context)
+
+ Return the name of a parsable file as input document.
Pass filename and context as parameters.
"""
@@ -60,7 +68,9 @@
return doc_ref
def resolve_file(self, f, context):
- """Return an open file-like object as input document.
+ """resolve_file(self, f, context)
+
+ Return an open file-like object as input document.
Pass open file and context as parameters.
"""
@@ -83,7 +93,9 @@
self._default_resolver = default_resolver
def add(self, Resolver resolver not None):
- """Register a resolver.
+ """add(self, resolver)
+
+ Register a resolver.
For each requested entity, the 'resolve' method of the resolver will
be called and the result will be passed to the parser. If this method
@@ -94,6 +106,7 @@
self._resolvers.add(resolver)
def remove(self, resolver):
+ "remove(self, resolver)"
self._resolvers.discard(resolver)
cdef _ResolverRegistry _copy(self):
@@ -103,9 +116,11 @@
return registry
def copy(self):
+ "copy(self)"
return self._copy()
def resolve(self, system_url, public_id, context):
+ "resolve(self, system_url, public_id, context)"
for resolver in self._resolvers:
result = resolver.resolve(system_url, public_id, context)
if result is not None:
Modified: lxml/trunk/src/lxml/dtd.pxi
==============================================================================
--- lxml/trunk/src/lxml/dtd.pxi (original)
+++ lxml/trunk/src/lxml/dtd.pxi Wed Feb 13 21:48:39 2008
@@ -20,7 +20,8 @@
# DTD
cdef class DTD(_Validator):
- """A DTD validator.
+ """DTD(self, file=None, external_id=None)
+ A DTD validator.
Can load from filesystem directly given a filename or file-like object.
Alternatively, pass the keyword parameter ``external_id`` to load from a
@@ -56,7 +57,9 @@
tree.xmlFreeDtd(self._c_dtd)
def __call__(self, etree):
- """Validate doc using the DTD.
+ """__call__(self, etree)
+
+ Validate doc using the DTD.
Returns true if the document is valid, false if not.
"""
Modified: lxml/trunk/src/lxml/extensions.pxi
==============================================================================
--- lxml/trunk/src/lxml/extensions.pxi (original)
+++ lxml/trunk/src/lxml/extensions.pxi Wed Feb 13 21:48:39 2008
@@ -326,7 +326,9 @@
self._temp_refs.add((<_Element>o)._doc)
def Extension(module, function_mapping=None, *, ns=None):
- """Build a dictionary of extension functions from the functions
+ """Extension(module, function_mapping=None, ns=None)
+
+ Build a dictionary of extension functions from the functions
defined in a module or the methods of an object.
As second argument, you can pass an additional mapping of
Modified: lxml/trunk/src/lxml/html/usedoctest.py
==============================================================================
--- lxml/trunk/src/lxml/html/usedoctest.py (original)
+++ lxml/trunk/src/lxml/html/usedoctest.py Wed Feb 13 21:48:39 2008
@@ -1,3 +1,13 @@
+"""Doctest module for HTML comparison.
+
+Usage::
+
+ >>> import lxml.html.usedoctest
+ >>> # now do your HTML doctests ...
+
+See `lxml.doctestcompare`.
+"""
+
from lxml import doctestcompare
doctestcompare.temp_install(html=True, del_module=__name__)
Modified: lxml/trunk/src/lxml/iterparse.pxi
==============================================================================
--- lxml/trunk/src/lxml/iterparse.pxi (original)
+++ lxml/trunk/src/lxml/iterparse.pxi Wed Feb 13 21:48:39 2008
@@ -239,9 +239,12 @@
origEnd(ctxt, name)
cdef class iterparse(_BaseParser):
- """Incremental parser. Parses XML into a tree and generates tuples
- (event, element) in a SAX-like fashion. ``event`` is any of 'start',
- 'end', 'start-ns', 'end-ns'.
+ """iterparse(self, source, events=("end",), tag=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, remove_blank_text=False, remove_comments=False, remove_pis=False, encoding=None, html=False, schema=None)
+ Incremental parser.
+
+ Parses XML into a tree and generates tuples (event, element) in a
+ SAX-like fashion. ``event`` is any of 'start', 'end', 'start-ns',
+ 'end-ns'.
For 'start' and 'end', ``element`` is the Element that the parser just
found opening or closing. For 'start-ns', it is a tuple (prefix, URI) of
@@ -262,17 +265,17 @@
attribute default values are requested.
Available boolean keyword arguments:
- * attribute_defaults - read default attributes from DTD
- * dtd_validation - validate (if DTD is available)
- * load_dtd - use DTD for parsing
- * no_network - prevent network access for related files
- * remove_blank_text - discard blank text nodes
- * remove_comments - discard comments
- * remove_pis - discard processing instructions
+ - attribute_defaults - read default attributes from DTD
+ - dtd_validation - validate (if DTD is available)
+ - load_dtd - use DTD for parsing
+ - no_network - prevent network access for related files
+ - remove_blank_text - discard blank text nodes
+ - remove_comments - discard comments
+ - remove_pis - discard processing instructions
Other keyword arguments:
- * encoding - override the document encoding
- * schema - an XMLSchema to validate against
+ - encoding - override the document encoding
+ - schema - an XMLSchema to validate against
"""
cdef object _source
cdef readonly object root
@@ -397,8 +400,10 @@
cdef class iterwalk:
- """A tree walker that generates events from an existing tree as if it was
- parsing XML data with ``iterparse()``.
+ """iterwalk(self, element_or_tree, events=("end",), tag=None)
+
+ A tree walker that generates events from an existing tree as if it
+ was parsing XML data with ``iterparse()``.
"""
cdef object _node_stack
cdef object _pop_node
Modified: lxml/trunk/src/lxml/lxml.etree.pyx
==============================================================================
--- lxml/trunk/src/lxml/lxml.etree.pyx (original)
+++ lxml/trunk/src/lxml/lxml.etree.pyx Wed Feb 13 21:48:39 2008
@@ -1,3 +1,9 @@
+"""The lxml.etree module implements the extended ElementTree API for
+XML.
+"""
+
+__docformat__ = "restructuredtext en"
+
cimport tree, python, config
from tree cimport xmlDoc, xmlNode, xmlAttr, xmlNs, _isElement, _getNs
from python cimport callable, _cstr, _isString
@@ -214,7 +220,9 @@
cdef class QName:
- """QName wrapper.
+ """QName(text_or_uri, tag=None)
+
+ QName wrapper.
Pass a tag name by itself or a namespace URI and a tag name to
create a qualified name. The ``text`` property holds the
@@ -510,7 +518,9 @@
cdef public class _Element [ type LxmlElementType, object LxmlElement ]:
- """Element class. References a document object and a libxml node.
+ """Element class.
+
+ References a document object and a libxml node.
By pointing to a Document instance, a reference is kept to
_Document as long as there is some pointer to a node in it.
@@ -522,7 +532,9 @@
cdef object _attrib
def _init(self):
- """Called after object initialisation. Custom subclasses may override
+ """_init(self)
+
+ Called after object initialisation. Custom subclasses may override
this if they recursively call _init() in the superclasses.
"""
@@ -537,7 +549,9 @@
# MANIPULATORS
def __setitem__(self, x, value):
- """Replaces the given subelement index or slice.
+ """__setitem__(self, x, value)
+
+ Replaces the given subelement index or slice.
"""
cdef xmlNode* c_node
cdef xmlNode* c_next
@@ -571,7 +585,9 @@
moveNodeToDocument(self._doc, c_node)
def __delitem__(self, x):
- """Deletes the given subelement or a slice.
+ """__delitem__(self, x)
+
+ Deletes the given subelement or a slice.
"""
cdef xmlNode* c_node
cdef xmlNode* c_next
@@ -599,9 +615,11 @@
_removeNode(self._doc, c_node)
def __deepcopy__(self, memo):
+ "__deepcopy__(self, memo)"
return self.__copy__()
def __copy__(self):
+ "__copy__(self)"
cdef xmlDoc* c_doc
cdef xmlNode* c_node
cdef _Document new_doc
@@ -619,17 +637,23 @@
return _elementFactory(new_doc, c_node)
def set(self, key, value):
- """Sets an element attribute.
+ """set(self, key, value)
+
+ Sets an element attribute.
"""
_setAttributeValue(self, key, value)
def append(self, _Element element not None):
- """Adds a subelement to the end of this element.
+ """append(self, element)
+
+ Adds a subelement to the end of this element.
"""
_appendChild(self, element)
def addnext(self, _Element element):
- """Adds the element as a following sibling directly after this
+ """addnext(self, element)
+
+ Adds the element as a following sibling directly after this
element.
This is normally used to set a processing instruction or comment after
@@ -644,7 +668,9 @@
_appendSibling(self, element)
def addprevious(self, _Element element):
- """Adds the element as a preceding sibling directly before this
+ """addprevious(self, element)
+
+ Adds the element as a preceding sibling directly before this
element.
This is normally used to set a processing instruction or comment
@@ -659,13 +685,17 @@
_prependSibling(self, element)
def extend(self, elements):
- """Extends the current children by the elements in the iterable.
+ """extend(self, elements)
+
+ Extends the current children by the elements in the iterable.
"""
for element in elements:
_appendChild(self, element)
def clear(self):
- """Resets an element. This function removes all subelements, clears
+ """clear(self)
+
+ Resets an element. This function removes all subelements, clears
all attributes and sets the text and tail properties to None.
"""
cdef xmlAttr* c_attr
@@ -693,7 +723,9 @@
c_node = c_node_next
def insert(self, index, _Element element not None):
- """Inserts a subelement at the given position in this element
+ """insert(self, index, element)
+
+ Inserts a subelement at the given position in this element
"""
cdef xmlNode* c_node
cdef xmlNode* c_next
@@ -707,7 +739,9 @@
moveNodeToDocument(self._doc, element._c_node)
def remove(self, _Element element not None):
- """Removes a matching subelement. Unlike the find methods, this
+ """remove(self, element)
+
+ Removes a matching subelement. Unlike the find methods, this
method compares elements based on identity, not on tag value
or contents.
"""
@@ -724,7 +758,9 @@
def replace(self, _Element old_element not None,
_Element new_element not None):
- """Replaces a subelement with the element passed as second argument.
+ """replace(self, old_element, new_element)
+
+ Replaces a subelement with the element passed as second argument.
"""
cdef xmlNode* c_old_node
cdef xmlNode* c_old_next
@@ -862,6 +898,7 @@
# ACCESSORS
def __repr__(self):
+ "__repr__(self)"
return "<Element %s at %x>" % (self.tag, id(self))
def __getitem__(self, x):
@@ -901,11 +938,14 @@
return _elementFactory(self._doc, c_node)
def __len__(self):
- """Returns the number of subelements.
+ """__len__(self)
+
+ Returns the number of subelements.
"""
return _countElements(self._c_node.children)
def __nonzero__(self):
+ "__nonzero__(self)"
import warnings
warnings.warn(
"The behavior of this method will change in future versions. "
@@ -916,6 +956,7 @@
return _hasChild(self._c_node)
def __contains__(self, element):
+ "__contains__(self, element)"
cdef xmlNode* c_node
if not isinstance(element, _Element):
return 0
@@ -923,13 +964,17 @@
return c_node is not NULL and c_node.parent is self._c_node
def __iter__(self):
+ "__iter__(self)"
return ElementChildIterator(self)
def __reversed__(self):
+ "__reversed__(self)"
return ElementChildIterator(self, reversed=True)
def index(self, _Element child not None, start=None, stop=None):
- """Find the position of the child within the parent.
+ """index(self, child, start=None, stop=None)
+
+ Find the position of the child within the parent.
This method is not part of the original ElementTree API.
"""
@@ -1012,40 +1057,52 @@
raise ValueError("list.index(x): x not in list")
def get(self, key, default=None):
- """Gets an element attribute.
+ """get(self, key, default=None)
+
+ Gets an element attribute.
"""
return _getAttributeValue(self, key, default)
def keys(self):
- """Gets a list of attribute names. The names are returned in an
+ """keys(self)
+
+ Gets a list of attribute names. The names are returned in an
arbitrary order (just like for an ordinary Python dictionary).
"""
return _collectAttributes(self._c_node, 1)
def values(self):
- """Gets element attribute values as a sequence of strings. The
+ """values(self)
+
+ Gets element attribute values as a sequence of strings. The
attributes are returned in an arbitrary order.
"""
return _collectAttributes(self._c_node, 2)
def items(self):
- """Gets element attributes, as a sequence. The attributes are returned in
+ """items(self)
+
+ Gets element attributes, as a sequence. The attributes are returned in
an arbitrary order.
"""
return _collectAttributes(self._c_node, 3)
def getchildren(self):
- """Returns all direct children. The elements are returned in document
+ """getchildren(self)
+
+ Returns all direct children. The elements are returned in document
order.
- @deprecated: Note that this method has been deprecated as of
- ElementTree 1.3 and lxml 2.0. New code should use
- ``list(element)`` or simply iterate over elements.
+ :deprecated: Note that this method has been deprecated as of
+ ElementTree 1.3 and lxml 2.0. New code should use
+ ``list(element)`` or simply iterate over elements.
"""
return _collectChildren(self)
def getparent(self):
- """Returns the parent of this element or None for the root element.
+ """getparent(self)
+
+ Returns the parent of this element or None for the root element.
"""
cdef xmlNode* c_node
c_node = _parentElement(self._c_node)
@@ -1055,7 +1112,9 @@
return _elementFactory(self._doc, c_node)
def getnext(self):
- """Returns the following sibling of this element or None.
+ """getnext(self)
+
+ Returns the following sibling of this element or None.
"""
cdef xmlNode* c_node
c_node = _nextElement(self._c_node)
@@ -1064,7 +1123,9 @@
return None
def getprevious(self):
- """Returns the preceding sibling of this element or None.
+ """getprevious(self)
+
+ Returns the preceding sibling of this element or None.
"""
cdef xmlNode* c_node
c_node = _previousElement(self._c_node)
@@ -1073,7 +1134,9 @@
return None
def itersiblings(self, tag=None, *, preceding=False):
- """Iterate over the following or preceding siblings of this element.
+ """itersiblings(self, tag=None, preceding=False)
+
+ Iterate over the following or preceding siblings of this element.
The direction is determined by the 'preceding' keyword which defaults
to False, i.e. forward iteration over the following siblings. The
@@ -1083,7 +1146,9 @@
return SiblingsIterator(self, tag, preceding=preceding)
def iterancestors(self, tag=None):
- """Iterate over the ancestors of this element (from parent to parent).
+ """iterancestors(self, tag=None)
+
+ Iterate over the ancestors of this element (from parent to parent).
The generated elements can be restricted to a specific tag name with
the 'tag' keyword.
@@ -1091,7 +1156,9 @@
return AncestorsIterator(self, tag)
def iterdescendants(self, tag=None):
- """Iterate over the descendants of this element in document order.
+ """iterdescendants(self, tag=None)
+
+ Iterate over the descendants of this element in document order.
As opposed to ``el.iter()``, this iterator does not yield the element
itself. The generated elements can be restricted to a specific tag
@@ -1100,7 +1167,9 @@
return ElementDepthFirstIterator(self, tag, inclusive=False)
def iterchildren(self, tag=None, *, reversed=False):
- """Iterate over the children of this element.
+ """iterchildren(self, tag=None, reversed=False)
+
+ Iterate over the children of this element.
As opposed to using normal iteration on this element, the generated
elements can be restricted to a specific tag name with the 'tag'
@@ -1109,7 +1178,9 @@
return ElementChildIterator(self, tag, reversed=reversed)
def getroottree(self):
- """Return an ElementTree for the root node of the document that
+ """getroottree(self)
+
+ Return an ElementTree for the root node of the document that
contains this element.
This is the same as following element.getparent() up the tree until it
@@ -1118,7 +1189,9 @@
return _elementTreeFactory(self._doc, None)
def getiterator(self, tag=None):
- """Returns a sequence or iterator of all elements in the subtree in
+ """getiterator(self, tag=None)
+
+ Returns a sequence or iterator of all elements in the subtree in
document order (depth first pre-order), starting with this
element.
@@ -1128,18 +1201,20 @@
You can also pass the Element, Comment, ProcessingInstruction and
Entity factory functions to look only for the specific element type.
- @deprecated: Note that this method is deprecated as of
- ElementTree 1.3 and lxml 2.0. It returns an iterator in lxml,
- which diverges from the original ElementTree behaviour. If
- you want an efficient iterator, use the ``element.iter()``
- method instead. You should only use this method in new code
- if you require backwards compatibility with older versions of
- lxml or ElementTree.
+ :deprecated: Note that this method is deprecated as of
+ ElementTree 1.3 and lxml 2.0. It returns an iterator in
+ lxml, which diverges from the original ElementTree
+ behaviour. If you want an efficient iterator, use the
+ ``element.iter()`` method instead. You should only use this
+ method in new code if you require backwards compatibility
+ with older versions of lxml or ElementTree.
"""
return ElementDepthFirstIterator(self, tag)
def iter(self, tag=None):
- """Iterate over all elements in the subtree in document order (depth
+ """iter(self, tag=None)
+
+ Iterate over all elements in the subtree in document order (depth
first pre-order), starting with this element.
Can be restricted to find only elements with a specific tag
@@ -1151,7 +1226,9 @@
return ElementDepthFirstIterator(self, tag)
def itertext(self, tag=None, *, with_tail=True):
- """Iterates over the text content of a subtree.
+ """itertext(self, tag=None, with_tail=True)
+
+ Iterates over the text content of a subtree.
You can pass the ``tag`` keyword argument to restrict text content to
a specific tag name.
@@ -1162,41 +1239,53 @@
return ElementTextIterator(self, tag, with_tail=with_tail)
def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
- """Creates a new element associated with the same document.
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
+
+ Creates a new element associated with the same document.
"""
return _makeElement(_tag, NULL, self._doc, None, None, None,
attrib, nsmap, _extra)
def find(self, path):
- """Finds the first matching subelement, by tag name or path.
+ """find(self, path)
+
+ Finds the first matching subelement, by tag name or path.
"""
if isinstance(path, QName):
path = (<QName>path).text
return _elementpath.find(self, path)
def findtext(self, path, default=None):
- """Finds text for the first matching subelement, by tag name or path.
+ """findtext(self, path, default=None)
+
+ Finds text for the first matching subelement, by tag name or path.
"""
if isinstance(path, QName):
path = (<QName>path).text
return _elementpath.findtext(self, path, default)
def findall(self, path):
- """Finds all matching subelements, by tag name or path.
+ """findall(self, path)
+
+ Finds all matching subelements, by tag name or path.
"""
if isinstance(path, QName):
path = (<QName>path).text
return _elementpath.findall(self, path)
def iterfind(self, path):
- """Iterates over all matching subelements, by tag name or path.
+ """iterfind(self, path)
+
+ Iterates over all matching subelements, by tag name or path.
"""
if isinstance(path, QName):
path = (<QName>path).text
return _elementpath.iterfind(self, path)
def xpath(self, _path, *, namespaces=None, extensions=None, **_variables):
- """Evaluate an xpath expression using the element as context node.
+ """xpath(self, _path, namespaces=None, extensions=None, **_variables)
+
+ Evaluate an xpath expression using the element as context node.
"""
evaluator = XPathElementEvaluator(self, namespaces=namespaces,
extensions=extensions)
@@ -1260,15 +1349,19 @@
raise TypeError("this element does not have children or attributes")
def set(self, key, value):
+ "set(self, key, value)"
self._raiseImmutable()
def append(self, value):
+ "append(self, value)"
self._raiseImmutable()
def insert(self, index, value):
+ "insert(self, index, value)"
self._raiseImmutable()
def __setitem__(self, index, value):
+ "__setitem__(self, index, value)"
self._raiseImmutable()
property attrib:
@@ -1294,24 +1387,30 @@
# ACCESSORS
def __getitem__(self, x):
+ "__getitem__(self, x)"
if python.PySlice_Check(x):
return []
else:
raise IndexError("list index out of range")
def __len__(self):
+ "__len__(self)"
return 0
def get(self, key, default=None):
+ "get(self, key, default=None)"
return None
def keys(self):
+ "keys(self)"
return []
def items(self):
+ "items(self)"
return []
def values(self):
+ "values(self)"
return []
cdef class _Comment(__ContentOnlyElement):
@@ -1390,7 +1489,9 @@
"ElementTree not initialized, missing root"
def parse(self, source, _BaseParser parser=None):
- """Updates self with the content of source and returns its root
+ """parse(self, source, parser=None)
+
+ Updates self with the content of source and returns its root
"""
cdef _Document doc
doc = _parseDocument(source, parser)
@@ -1402,7 +1503,9 @@
return self._context_node
def _setroot(self, _Element root not None):
- """Relocate the ElementTree to a new root node.
+ """_setroot(self, root)
+
+ Relocate the ElementTree to a new root node.
"""
if root._c_node.type != tree.XML_ELEMENT_NODE:
raise TypeError("Only elements can be the root of an ElementTree")
@@ -1410,7 +1513,9 @@
self._doc = None
def getroot(self):
- """Gets the root element for this tree.
+ """getroot(self)
+
+ Gets the root element for this tree.
"""
return self._context_node
@@ -1445,7 +1550,10 @@
def write(self, file, *, encoding=None, method="xml",
pretty_print=False, xml_declaration=None, with_tail=True):
- """Write the tree to a file or file-like object.
+ """write(self, file, encoding=None, method="xml",
+ pretty_print=False, xml_declaration=None, with_tail=True)
+
+ Write the tree to a file or file-like object.
Defaults to ASCII encoding and writing a declaration as needed.
@@ -1470,7 +1578,9 @@
write_declaration, 1, pretty_print, with_tail)
def getpath(self, _Element element not None):
- """Returns a structural, absolute XPath expression to find that element.
+ """getpath(self, element)
+
+ Returns a structural, absolute XPath expression to find that element.
"""
cdef _Document doc
cdef xmlDoc* c_doc
@@ -1488,7 +1598,9 @@
return path
def getiterator(self, tag=None):
- """Returns a sequence or iterator of all elements in document order
+ """getiterator(self, tag=None)
+
+ Returns a sequence or iterator of all elements in document order
(depth first pre-order), starting with the root element.
Can be restricted to find only elements with a specific tag
@@ -1498,13 +1610,13 @@
You can also pass the Element, Comment, ProcessingInstruction and
Entity factory functions to look only for the specific element type.
- @deprecated: Note that this method is deprecated as of
- ElementTree 1.3 and lxml 2.0. It returns an iterator in lxml,
- which diverges from the original ElementTree behaviour. If
- you want an efficient iterator, use the ``tree.iter()`` method
- instead. You should only use this method in new code if you
- require backwards compatibility with older versions of lxml or
- ElementTree.
+ :deprecated: Note that this method is deprecated as of
+ ElementTree 1.3 and lxml 2.0. It returns an iterator in
+ lxml, which diverges from the original ElementTree
+ behaviour. If you want an efficient iterator, use the
+ ``tree.iter()`` method instead. You should only use this
+ method in new code if you require backwards compatibility
+ with older versions of lxml or ElementTree.
"""
root = self.getroot()
if root is None:
@@ -1512,7 +1624,9 @@
return root.getiterator(tag)
def iter(self, tag=None):
- """Creates an iterator for the root element. The iterator loops over
+ """iter(self, tag=None)
+
+ Creates an iterator for the root element. The iterator loops over
all elements in this tree, in document order.
"""
root = self.getroot()
@@ -1521,7 +1635,9 @@
return root.iter(tag)
def find(self, path):
- """Finds the first toplevel element with given tag. Same as
+ """find(self, path)
+
+ Finds the first toplevel element with given tag. Same as
``tree.getroot().find(path)``.
"""
self._assertHasRoot()
@@ -1531,7 +1647,9 @@
return root.find(path)
def findtext(self, path, default=None):
- """Finds the text for the first element matching the ElementPath
+ """findtext(self, path, default=None)
+
+ Finds the text for the first element matching the ElementPath
expression. Same as getroot().findtext(path)
"""
self._assertHasRoot()
@@ -1541,7 +1659,9 @@
return root.findtext(path, default)
def findall(self, path):
- """Finds all elements matching the ElementPath expression. Same as
+ """findall(self, path)
+
+ Finds all elements matching the ElementPath expression. Same as
getroot().findall(path).
"""
self._assertHasRoot()
@@ -1551,7 +1671,9 @@
return root.findall(path)
def iterfind(self, path):
- """Iterates over all elements matching the ElementPath expression.
+ """iterfind(self, path)
+
+ Iterates over all elements matching the ElementPath expression.
Same as getroot().finditer(path).
"""
self._assertHasRoot()
@@ -1561,7 +1683,9 @@
return root.iterfind(path)
def xpath(self, _path, *, namespaces=None, extensions=None, **_variables):
- """XPath evaluate in context of document.
+ """xpath(self, _path, namespaces=None, extensions=None, **_variables)
+
+ XPath evaluate in context of document.
``namespaces`` is an optional dictionary with prefix to namespace URI
mappings, used by XPath. ``extensions`` defines additional extension
@@ -1582,7 +1706,9 @@
return evaluator.evaluate(_path, **_variables)
def xslt(self, _xslt, extensions=None, access_control=None, **_kw):
- """Transform this document using other document.
+ """xslt(self, _xslt, extensions=None, access_control=None, **_kw)
+
+ Transform this document using other document.
xslt is a tree that should be XSLT
keyword parameters are XSLT transformation parameters.
@@ -1599,7 +1725,9 @@
return style(self, **_kw)
def relaxng(self, relaxng):
- """Validate this document using other document.
+ """relaxng(self, relaxng)
+
+ Validate this document using other document.
The relaxng argument is a tree that should contain a Relax NG schema.
@@ -1615,7 +1743,9 @@
return schema.validate(self)
def xmlschema(self, xmlschema):
- """Validate this document using other document.
+ """xmlschema(self, xmlschema)
+
+ Validate this document using other document.
The xmlschema argument is a tree that should contain an XML Schema.
@@ -1631,7 +1761,9 @@
return schema.validate(self)
def xinclude(self):
- """Process the XInclude nodes in this document and include the
+ """xinclude(self)
+
+ Process the XInclude nodes in this document and include the
referenced XML fragments.
There is support for loading files through the file system, HTTP and
@@ -1645,7 +1777,9 @@
XInclude()(self._context_node)
def write_c14n(self, file):
- """C14N write of document. Always writes UTF-8.
+ """write_c14n(self, file)
+
+ C14N write of document. Always writes UTF-8.
"""
self._assertHasRoot()
_tofilelikeC14N(file, self._context_node)
@@ -1666,9 +1800,7 @@
cdef class _Attrib:
- """A proxy for the ``Element.attrib`` property.
-
- Behaves as a normal Python dict.
+ """A dict-like proxy for the ``Element.attrib`` property.
"""
cdef _Element _element
def __init__(self, _Element element not None):
@@ -1895,7 +2027,9 @@
return current_node
cdef class ElementChildIterator(_ElementIterator):
- "Iterates over the children of an element."
+ """ElementChildIterator(self, node, tag=None, reversed=False)
+ Iterates over the children of an element.
+ """
def __init__(self, _Element node not None, tag=None, *, reversed=False):
cdef xmlNode* c_node
self._initTagMatch(tag)
@@ -1916,7 +2050,8 @@
self._node = _elementFactory(node._doc, c_node)
cdef class SiblingsIterator(_ElementIterator):
- """Iterates over the siblings of an element.
+ """SiblingsIterator(self, node, tag=None, preceding=False)
+ Iterates over the siblings of an element.
You can pass the boolean keyword ``preceding`` to specify the direction.
"""
@@ -1929,18 +2064,24 @@
self._storeNext(node)
cdef class AncestorsIterator(_ElementIterator):
- "Iterates over the ancestors of an element (from parent to parent)."
+ """AncestorsIterator(self, node, tag=None)
+ Iterates over the ancestors of an element (from parent to parent).
+ """
def __init__(self, _Element node not None, tag=None):
self._initTagMatch(tag)
self._next_element = _parentElement
self._storeNext(node)
cdef class ElementDepthFirstIterator(_ElementTagMatcher):
- """Iterates over an element and its sub-elements in document order (depth
- first pre-order). Note that this also includes comments, entities and
- processing instructions. To filter them out, check if the ``tag``
- property of the returned element is a string (i.e. not None and not a
- factory function), or pass the ``Element`` factory for the ``tag`` keyword.
+ """ElementDepthFirstIterator(self, node, tag=None, inclusive=True)
+ Iterates over an element and its sub-elements in document order (depth
+ first pre-order).
+
+ Note that this also includes comments, entities and processing
+ instructions. To filter them out, check if the ``tag`` property
+ of the returned element is a string (i.e. not None and not a
+ factory function), or pass the ``Element`` factory for the ``tag``
+ keyword.
If the optional ``tag`` argument is not None, the iterator returns only
the elements that match the respective name and namespace.
@@ -2003,7 +2144,8 @@
return NULL
cdef class ElementTextIterator:
- """Iterates over the text content of a subtree.
+ """ElementTextIterator(self, element, tag=None, with_tail=True)
+ Iterates over the text content of a subtree.
You can pass the ``tag`` keyword argument to restrict text content to a
specific tag name.
@@ -2057,7 +2199,9 @@
# module-level API for ElementTree
def Element(_tag, attrib=None, nsmap=None, **_extra):
- """Element factory. This function returns an object implementing the
+ """Element(_tag, attrib=None, nsmap=None, **_extra)
+
+ Element factory. This function returns an object implementing the
Element interface.
"""
### also look at _Element.makeelement() and _BaseParser.makeelement() ###
@@ -2065,7 +2209,9 @@
attrib, nsmap, _extra)
def Comment(text=None):
- """Comment element factory. This factory function creates a special element that will
+ """Comment(text=None)
+
+ Comment element factory. This factory function creates a special element that will
be serialized as an XML comment.
"""
cdef _Document doc
@@ -2082,7 +2228,9 @@
return _elementFactory(doc, c_node)
def ProcessingInstruction(target, text=None):
- """ProcessingInstruction element factory. This factory function creates a
+ """ProcessingInstruction(target, text=None)
+
+ ProcessingInstruction element factory. This factory function creates a
special element that will be serialized as an XML processing instruction.
"""
cdef _Document doc
@@ -2102,7 +2250,9 @@
PI = ProcessingInstruction
def Entity(name):
- """Entity factory. This factory function creates a special element
+ """Entity(name)
+
+ Entity factory. This factory function creates a special element
that will be serialized as an XML entity reference or character
reference. Note, however, that entities will not be automatically
declared in the document. A document that uses entity references
@@ -2127,13 +2277,17 @@
def SubElement(_Element _parent not None, _tag,
attrib=None, nsmap=None, **_extra):
- """Subelement factory. This function creates an element instance, and
+ """SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra)
+
+ Subelement factory. This function creates an element instance, and
appends it to an existing element.
"""
return _makeSubElement(_parent, _tag, None, None, attrib, nsmap, _extra)
def ElementTree(_Element element=None, *, file=None, _BaseParser parser=None):
- """ElementTree wrapper class.
+ """ElementTree(element=None, file=None, parser=None)
+
+ ElementTree wrapper class.
"""
cdef xmlNode* c_next
cdef xmlNode* c_node
@@ -2156,7 +2310,9 @@
return _elementTreeFactory(doc, element)
def HTML(text, _BaseParser parser=None, *, base_url=None):
- """Parses an HTML document from a string constant. This function can be used
+ """HTML(text, parser=None, base_url=None)
+
+ Parses an HTML document from a string constant. This function can be used
to embed "HTML literals" in Python code.
To override the parser with a different ``HTMLParser`` you can pass it to
@@ -2178,7 +2334,9 @@
return result_container.result
def XML(text, _BaseParser parser=None, *, base_url=None):
- """Parses an XML document from a string constant. This function can be used
+ """XML(text, parser=None, base_url=None)
+
+ Parses an XML document from a string constant. This function can be used
to embed "XML literals" in Python code, like in
>>> root = etree.XML("<root><test/></root>")
@@ -2202,7 +2360,9 @@
return result_container.result
def fromstring(text, _BaseParser parser=None, *, base_url=None):
- """Parses an XML document from a string.
+ """fromstring(text, parser=None, base_url=None)
+
+ Parses an XML document from a string.
To override the default parser with a different parser you can pass it to
the ``parser`` keyword argument.
@@ -2219,7 +2379,9 @@
return result_container.result
def fromstringlist(strings, _BaseParser parser=None):
- """Parses an XML document from a sequence of strings.
+ """fromstringlist(strings, parser=None)
+
+ Parses an XML document from a sequence of strings.
To override the default parser with a different parser you can pass it to
the ``parser`` keyword argument.
@@ -2233,19 +2395,26 @@
return parser.close()
def iselement(element):
- """Checks if an object appears to be a valid element object.
+ """iselement(element)
+
+ Checks if an object appears to be a valid element object.
"""
return isinstance(element, _Element)
def dump(_Element elem not None, *, pretty_print=True, with_tail=True):
- """Writes an element tree or element structure to sys.stdout. This function
+ """dump(elem, pretty_print=True, with_tail=True)
+
+ Writes an element tree or element structure to sys.stdout. This function
should be used for debugging only.
"""
_dumpToFile(sys.stdout, elem._c_node, pretty_print, with_tail)
def tostring(element_or_tree, *, encoding=None, method="xml",
xml_declaration=None, pretty_print=False, with_tail=True):
- """Serialize an element to an encoded string representation of its XML
+ """tostring(element_or_tree, encoding=None, method="xml",
+ xml_declaration=None, pretty_print=False, with_tail=True)
+
+ Serialize an element to an encoded string representation of its XML
tree.
Defaults to ASCII encoding without XML declaration. This behaviour can be
@@ -2292,7 +2461,9 @@
type(element_or_tree))
def tostringlist(element_or_tree, *args, **kwargs):
- """Serialize an element to an encoded string representation of its XML
+ """tostringlist(element_or_tree, *args, **kwargs)
+
+ Serialize an element to an encoded string representation of its XML
tree, stored in a list of partial strings.
This is purely for ElementTree 1.3 compatibility. The result is a
@@ -2302,7 +2473,10 @@
def tounicode(element_or_tree, *, method="xml", pretty_print=False,
with_tail=True):
- """Serialize an element to the Python unicode representation of its XML
+ """tounicode(element_or_tree, method="xml", pretty_print=False,
+ with_tail=True)
+
+ Serialize an element to the Python unicode representation of its XML
tree.
Note that the result does not carry an XML encoding declaration and is
@@ -2318,7 +2492,7 @@
by passing the boolean ``with_tail`` option. This has no impact
on the tail text of children, which will always be serialised.
- @deprecated: use ``tostring(el, encoding=unicode)`` instead.
+ :deprecated: use ``tostring(el, encoding=unicode)`` instead.
"""
if isinstance(element_or_tree, _Element):
return _tounicode(<_Element>element_or_tree, method, 0, pretty_print,
@@ -2331,7 +2505,9 @@
type(element_or_tree))
def parse(source, _BaseParser parser=None):
- """Return an ElementTree object loaded with source elements. If no parser
+ """parse(source, parser=None)
+
+ Return an ElementTree object loaded with source elements. If no parser
is provided as second argument, the default parser is used.
"""
cdef _Document doc
@@ -2366,8 +2542,10 @@
# Validation
class DocumentInvalid(LxmlError):
- """Validation error. Raised by all document validators when their
- ``assertValid(tree)`` method fails.
+ """Validation error.
+
+ Raised by all document validators when their ``assertValid(tree)``
+ method fails.
"""
pass
@@ -2375,28 +2553,39 @@
"Base class for XML validators."
cdef _ErrorLog _error_log
def __init__(self):
+ "__init__(self)"
self._error_log = _ErrorLog()
def validate(self, etree):
- """Validate the document using this schema.
+ """validate(self, etree)
+
+ Validate the document using this schema.
- Returns true if document is valid, false if not."""
+ Returns true if document is valid, false if not.
+ """
return self(etree)
def assertValid(self, etree):
- "Raises DocumentInvalid if the document does not comply with the schema."
+ """assertValid(self, etree)
+
+ Raises `DocumentInvalid` if the document does not comply with the schema.
+ """
if not self(etree):
raise DocumentInvalid(self._error_log._buildExceptionMessage(
"Document does not comply with schema"),
self._error_log)
def assert_(self, etree):
- "Raises AssertionError if the document does not comply with the schema."
+ """assert_(self, etree)
+
+ Raises `AssertionError` if the document does not comply with the schema.
+ """
if not self(etree):
raise AssertionError(self._error_log._buildExceptionMessage(
"Document does not comply with schema"))
property error_log:
+ "The log of validation errors and warnings."
def __get__(self):
return self._error_log.copy()
Modified: lxml/trunk/src/lxml/lxml.objectify.pyx
==============================================================================
--- lxml/trunk/src/lxml/lxml.objectify.pyx (original)
+++ lxml/trunk/src/lxml/lxml.objectify.pyx Wed Feb 13 21:48:39 2008
@@ -153,7 +153,9 @@
return _countSiblings(self._c_node)
def countchildren(self):
- """Return the number of children of this element, regardless of their
+ """countchildren(self)
+
+ Return the number of children of this element, regardless of their
name.
"""
# copied from etree
@@ -168,7 +170,9 @@
return c
def getchildren(self):
- """Returns a sequence of all direct children. The elements are
+ """getchildren(self)
+
+ Returns a sequence of all direct children. The elements are
returned in document order.
"""
cdef tree.xmlNode* c_node
@@ -217,7 +221,9 @@
self.remove(child)
def addattr(self, tag, value):
- """Add a child value to the element.
+ """addattr(self, tag, value)
+
+ Add a child value to the element.
As opposed to append(), it sets a data value, not an element.
"""
@@ -331,18 +337,21 @@
parent.remove(sibling)
def iterfind(self, path):
+ "iterfind(self, path)"
# Reimplementation of Element.iterfind() to make it work without child
# iteration.
xpath = etree.ETXPath(path)
return iter(xpath(self))
def findall(self, path):
+ "findall(self, path)"
# Reimplementation of Element.findall() to make it work without child
# iteration.
xpath = etree.ETXPath(path)
return xpath(self)
def find(self, path):
+ "find(self, path)"
# Reimplementation of Element.find() to make it work without child
# iteration.
result = self.findall(path)
@@ -354,6 +363,7 @@
return None
def findtext(self, path, default=None):
+ "findtext(self, path, default=None)"
# Reimplementation of Element.findtext() to make it work without child
# iteration.
result = self.find(path)
@@ -363,7 +373,9 @@
return default
def descendantpaths(self, prefix=None):
- """Returns a list of object path expressions for all descendants.
+ """descendantpaths(self, prefix=None)
+
+ Returns a list of object path expressions for all descendants.
"""
if prefix is not None and not python._isString(prefix):
prefix = '.'.join(prefix)
@@ -853,7 +865,8 @@
# Python type registry
cdef class PyType:
- """User defined type.
+ """PyType(self, name, type_check, type_class, stringify=None)
+ User defined type.
Named type that contains a type check function and a type class that
inherits from ObjectifiedDataElement. The type check must take a string
@@ -862,6 +875,7 @@
guessing.
Example::
+
PyType('int', int, MyIntClass).register()
Note that the order in which types are registered matters. The first
@@ -894,7 +908,9 @@
return "PyType(%s, %s)" % (self.name, self._type.__name__)
def register(self, before=None, after=None):
- """Register the type.
+ """register(self, before=None, after=None)
+
+ Register the type.
The additional keyword arguments 'before' and 'after' accept a
sequence of type names that must appear before/after the new type in
@@ -933,6 +949,7 @@
_SCHEMA_TYPE_DICT[xs_type] = self
def unregister(self):
+ "unregister(self)"
if _PYTYPE_DICT.get(self.name) is self:
del _PYTYPE_DICT[self.name]
for xs_type, pytype in _SCHEMA_TYPE_DICT.items():
@@ -989,7 +1006,9 @@
return _typename(obj)
def pytypename(obj):
- """Find the name of the corresponding PyType for a Python object.
+ """pytypename(obj)
+
+ Find the name of the corresponding PyType for a Python object.
"""
return _pytypename(obj)
@@ -1035,7 +1054,9 @@
_registerPyTypes()
def getRegisteredTypes():
- """Returns a list of the currently registered PyType objects.
+ """getRegisteredTypes()
+
+ Returns a list of the currently registered PyType objects.
To add a new type, retrieve this list and call unregister() for all
entries. Then add the new type at a suitable position (possibly replacing
@@ -1099,6 +1120,8 @@
cdef _ObjectifyElementMakerCaller NEW_ELEMENT_MAKER "PY_NEW" (object t)
cdef class ElementMaker:
+ """ElementMaker(self, namespace=None, nsmap=None, annotate=True, makeelement=None)
+ """
cdef object _makeelement
cdef object _namespace
cdef object _nsmap
@@ -1137,6 +1160,7 @@
cdef bint _annotate
def __call__(self, *children, **attrib):
+ "__call__(self, *children, **attrib)"
cdef _ObjectifyElementMakerCaller elementMaker
cdef python.PyObject* pytype
cdef _Element element
@@ -1214,14 +1238,18 @@
__RECURSIVE_STR = 0 # default: off
def enableRecursiveStr(on=True):
- """Enable a recursively generated tree representation for str(element),
+ """enableRecursiveStr(on=True)
+
+ Enable a recursively generated tree representation for str(element),
based on objectify.dump(element).
"""
global __RECURSIVE_STR
__RECURSIVE_STR = on
def dump(_Element element not None):
- """Return a recursively generated string representation of an element.
+ """dump(_Element element not None)
+
+ Return a recursively generated string representation of an element.
"""
return _dump(element, 0)
@@ -1268,6 +1296,7 @@
copy_reg.pickle(ObjectifiedElement, reduceFunction, fromstring)
def pickleReduce(obj):
+ "pickleReduce(obj)"
return (fromstring, (etree.tostring(obj),))
_setupPickle(pickleReduce)
@@ -1277,7 +1306,8 @@
# Element class lookup
cdef class ObjectifyElementClassLookup(ElementClassLookup):
- """Element class lookup method that uses the objectify classes.
+ """ObjectifyElementClassLookup(self, tree_class=None, empty_data_class=None)
+ Element class lookup method that uses the objectify classes.
"""
cdef object empty_data_class
cdef object tree_class
@@ -1363,7 +1393,9 @@
def pyannotate(element_or_tree, *, ignore_old=False, ignore_xsi=False,
empty_pytype=None):
- """Recursively annotates the elements of an XML tree with 'pytype'
+ """pyannotate(element_or_tree, ignore_old=False, ignore_xsi=False, empty_pytype=None)
+
+ Recursively annotates the elements of an XML tree with 'pytype'
attributes.
If the 'ignore_old' keyword argument is True (the default), current 'pytype'
@@ -1384,7 +1416,9 @@
def xsiannotate(element_or_tree, *, ignore_old=False, ignore_pytype=False,
empty_type=None):
- """Recursively annotates the elements of an XML tree with 'xsi:type'
+ """xsiannotate(element_or_tree, ignore_old=False, ignore_pytype=False, empty_type=None)
+
+ Recursively annotates the elements of an XML tree with 'xsi:type'
attributes.
If the 'ignore_old' keyword argument is True (the default), current
@@ -1411,7 +1445,9 @@
def annotate(element_or_tree, *, ignore_old=True, ignore_xsi=False,
empty_pytype=None, empty_type=None, annotate_xsi=0,
annotate_pytype=1):
- """Recursively annotates the elements of an XML tree with 'xsi:type'
+ """annotate(element_or_tree, ignore_old=True, ignore_xsi=False, empty_pytype=None, empty_type=None, annotate_xsi=0, annotate_pytype=1)
+
+ Recursively annotates the elements of an XML tree with 'xsi:type'
and/or 'py:pytype' attributes.
If the 'ignore_old' keyword argument is True (the default), current
@@ -1597,7 +1633,9 @@
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
def deannotate(element_or_tree, *, pytype=True, xsi=True):
- """Recursively de-annotate the elements of an XML tree by removing 'pytype'
+ """deannotate(element_or_tree, pytype=True, xsi=True)
+
+ Recursively de-annotate the elements of an XML tree by removing 'pytype'
and/or 'type' attributes.
If the 'pytype' keyword argument is True (the default), 'pytype' attributes
@@ -1642,11 +1680,13 @@
objectify_parser = __DEFAULT_PARSER
def setDefaultParser(new_parser = None):
- "This function is deprecated, use ``set_default_parser()`` instead."
+ ":deprecated: use ``set_default_parser()`` instead."
set_default_parser(new_parser)
def set_default_parser(new_parser = None):
- """Replace the default parser used by objectify's Element() and
+ """set_default_parser(new_parser = None)
+
+ Replace the default parser used by objectify's Element() and
fromstring() functions.
The new parser must be an etree.XMLParser.
@@ -1662,7 +1702,9 @@
raise TypeError("parser must inherit from lxml.etree.XMLParser")
def makeparser(**kw):
- """Create a new XML parser for objectify trees.
+ """makeparser(remove_blank_text=True, **kw)
+
+ Create a new XML parser for objectify trees.
You can pass all keyword arguments that are supported by
``etree.XMLParser()``. Note that this parser defaults to removing
@@ -1685,7 +1727,9 @@
_fromstring = etree.fromstring
def fromstring(xml, parser=None):
- """Objectify specific version of the lxml.etree fromstring() function
+ """fromstring(xml, parser=None)
+
+ Objectify specific version of the lxml.etree fromstring() function
that uses the objectify parser.
You can pass a different parser as second argument.
@@ -1700,7 +1744,9 @@
_parse = etree.parse
def parse(f, parser=None):
- """Parse a file or file-like object with the objectify parser.
+ """parse(f, parser=None)
+
+ Parse a file or file-like object with the objectify parser.
You can pass a different parser as second argument.
"""
@@ -1716,7 +1762,9 @@
E = ElementMaker()
def Element(_tag, attrib=None, nsmap=None, *, _pytype=None, **_attributes):
- """Objectify specific version of the lxml.etree Element() factory that
+ """Element(_tag, attrib=None, nsmap=None, _pytype=None, **_attributes)
+
+ Objectify specific version of the lxml.etree Element() factory that
always creates a structural (tree) element.
NOTE: requires parser based element class lookup activated in lxml.etree!
@@ -1734,7 +1782,9 @@
def DataElement(_value, attrib=None, nsmap=None, *, _pytype=None, _xsi=None,
**_attributes):
- """Create a new element from a Python value and XML attributes taken from
+ """DataElement(_value, attrib=None, nsmap=None, _pytype=None, _xsi=None, **_attributes)
+
+ Create a new element from a Python value and XML attributes taken from
keyword arguments or a dictionary passed as second argument.
Automatically adds a 'pytype' attribute for the Python type of the value,
Modified: lxml/trunk/src/lxml/nsclasses.pxi
==============================================================================
--- lxml/trunk/src/lxml/nsclasses.pxi (original)
+++ lxml/trunk/src/lxml/nsclasses.pxi Wed Feb 13 21:48:39 2008
@@ -28,10 +28,14 @@
self._entries = {}
def update(self, class_dict_iterable):
- """Forgivingly update the registry. If registered values do not match
- the required type for this registry, or if their name starts with '_',
- they will be silently discarded. This allows registrations at the
- module or class level using vars(), globals() etc."""
+ """update(self, class_dict_iterable)
+
+ Forgivingly update the registry.
+
+ If registered values do not match the required type for this
+ registry, or if their name starts with '_', they will be
+ silently discarded. This allows registrations at the module or
+ class level using vars(), globals() etc."""
if hasattr(class_dict_iterable, 'items'):
class_dict_iterable = class_dict_iterable.items()
for name, item in class_dict_iterable:
@@ -89,7 +93,9 @@
cdef class ElementNamespaceClassLookup(FallbackElementClassLookup):
- """Element class lookup scheme that searches the Element class in the
+ """ElementNamespaceClassLookup(self, fallback=None)
+
+ Element class lookup scheme that searches the Element class in the
Namespace registry.
"""
cdef object _namespace_registries
@@ -99,8 +105,11 @@
self._lookup_function = _find_nselement_class
def get_namespace(self, ns_uri):
- """Retrieve the namespace object associated with the given URI. Creates a
- new one if it does not yet exist."""
+ """get_namespace(self, ns_uri)
+
+ Retrieve the namespace object associated with the given URI.
+
+ Creates a new one if it does not yet exist."""
if ns_uri:
ns_utf = _utf8(ns_uri)
else:
@@ -156,9 +165,13 @@
__FUNCTION_NAMESPACE_REGISTRIES = {}
def FunctionNamespace(ns_uri):
- """Retrieve the function namespace object associated with the given
- URI. Creates a new one if it does not yet exist. A function namespace can
- only be used to register extension functions."""
+ """FunctionNamespace(ns_uri)
+
+ Retrieve the function namespace object associated with the given
+ URI.
+
+ Creates a new one if it does not yet exist. A function namespace
+ can only be used to register extension functions."""
if ns_uri:
ns_utf = _utf8(ns_uri)
else:
Modified: lxml/trunk/src/lxml/objectpath.pxi
==============================================================================
--- lxml/trunk/src/lxml/objectpath.pxi (original)
+++ lxml/trunk/src/lxml/objectpath.pxi Wed Feb 13 21:48:39 2008
@@ -8,7 +8,8 @@
cdef class ObjectPath:
- """Immutable object that represents a compiled object path.
+ """ObjectPath(path)
+ Immutable object that represents a compiled object path.
Example for a path: 'root.child[1].{other}child[25]'
"""
@@ -54,6 +55,7 @@
default, use_default)
def hasattr(self, _Element root not None):
+ "hasattr(self, root)"
try:
_findObjectPath(root, self._c_path, self._path_len, None, 0)
except AttributeError:
@@ -61,14 +63,18 @@
return True
def setattr(self, _Element root not None, value):
- """Set the value of the target element in a subtree.
+ """setattr(self, root, value)
+
+ Set the value of the target element in a subtree.
If any of the children on the path does not exist, it is created.
"""
_createObjectPath(root, self._c_path, self._path_len, 1, value)
def addattr(self, _Element root not None, value):
- """Append a value to the target element in a subtree.
+ """addattr(self, root, value)
+
+ Append a value to the target element in a subtree.
If any of the children on the path does not exist, it is created.
"""
Modified: lxml/trunk/src/lxml/parser.pxi
==============================================================================
--- lxml/trunk/src/lxml/parser.pxi (original)
+++ lxml/trunk/src/lxml/parser.pxi Wed Feb 13 21:48:39 2008
@@ -668,6 +668,7 @@
return context._error_log.copy()
property resolvers:
+ "The custom resolver registry of this parser."
def __get__(self):
return self._resolvers
@@ -681,7 +682,9 @@
self.set_element_class_lookup(lookup)
def set_element_class_lookup(self, ElementClassLookup lookup = None):
- """Set a lookup scheme for element classes generated from this parser.
+ """set_element_class_lookup(self, lookup = None)
+
+ Set a lookup scheme for element classes generated from this parser.
Reset it by passing None or nothing.
"""
@@ -702,11 +705,16 @@
return parser
def copy(self):
- "Create a new parser with the same configuration."
+ """copy(self)
+
+ Create a new parser with the same configuration.
+ """
return self._copy()
def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
- """Creates a new element associated with this parser.
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
+
+ Creates a new element associated with this parser.
"""
return _makeElement(_tag, NULL, None, self, None, None,
attrib, nsmap, _extra)
@@ -861,7 +869,9 @@
return context._error_log.copy()
def feed(self, data):
- """Feeds data to the parser. The argument should be an 8-bit string
+ """feed(self, data)
+
+ Feeds data to the parser. The argument should be an 8-bit string
buffer containing encoded data, although Unicode is supported as long
as both string types are not mixed.
@@ -942,7 +952,9 @@
context.cleanup()
def close(self):
- """Terminates feeding data to this parser. This tells the parser to
+ """close(self)
+
+ Terminates feeding data to this parser. This tells the parser to
process any remaining data in the feed buffer, and then returns the
root Element of the tree that was parsed.
@@ -1303,7 +1315,8 @@
############################################################
cdef class TreeBuilder(_SaxParserTarget):
- """Parser target that builds a tree.
+ """TreeBuilder(self, element_factory=None, parser=None)
+ Parser target that builds a tree.
The final tree is returned by the ``close()`` method.
"""
@@ -1343,7 +1356,9 @@
# Python level event handlers
def close(self):
- """Flushes the builder buffers, and returns the toplevel document
+ """close(self)
+
+ Flushes the builder buffers, and returns the toplevel document
element.
"""
assert python.PyList_GET_SIZE(self._element_stack) == 0, "missing end tags"
@@ -1351,19 +1366,27 @@
return self._last
def data(self, data):
- """Adds text to the current element. The value should be either an
+ """data(self, data)
+
+ Adds text to the current element. The value should be either an
8-bit string containing ASCII text, or a Unicode string.
"""
self._handleSaxData(data)
def start(self, tag, attrs, nsmap=None):
- "Opens a new element."
+ """start(self, tag, attrs, nsmap=None)
+
+ Opens a new element.
+ """
if nsmap is None:
nsmap = EMPTY_READ_ONLY_DICT
return self._handleSaxStart(tag, attrs, nsmap)
def end(self, tag):
- "Closes the current element."
+ """end(self, tag)
+
+ Closes the current element.
+ """
element = self._handleSaxEnd(tag)
assert self._last.tag == tag,\
"end tag mismatch (expected %s, got %s)" % (
@@ -1371,9 +1394,13 @@
return element
def pi(self, target, data):
+ """pi(self, target, data)
+ """
return self._handleSaxPi(target, data)
def comment(self, comment):
+ """comment(self, comment)
+ """
return self._handleSaxComment(comment)
# internal SAX event handlers
@@ -1432,33 +1459,36 @@
)
cdef class XMLParser(_FeedParser):
- """The XML parser. Parsers can be supplied as additional argument to
- various parse functions of the lxml API. A default parser is always
- available and can be replaced by a call to the global function
- 'set_default_parser'. New parsers can be created at any time without a
- major run-time overhead.
+ """XMLParser(self, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, remove_blank_text=False, compact=True, resolve_entities=True, remove_comments=False, remove_pis=False, target=None, encoding=None, schema=None)
+ The XML parser.
+
+ Parsers can be supplied as additional argument to various parse
+ functions of the lxml API. A default parser is always available
+ and can be replaced by a call to the global function
+ 'set_default_parser'. New parsers can be created at any time
+ without a major run-time overhead.
The keyword arguments in the constructor are mainly based on the libxml2
parser configuration. A DTD will also be loaded if validation or
attribute default values are requested.
Available boolean keyword arguments:
- * attribute_defaults - read default attributes from DTD
- * dtd_validation - validate (if DTD is available)
- * load_dtd - use DTD for parsing
- * no_network - prevent network access for related files (default: True)
- * ns_clean - clean up redundant namespace declarations
- * recover - try hard to parse through broken XML
- * remove_blank_text - discard blank text nodes
- * remove_comments - discard comments
- * remove_pis - discard processing instructions
- * compact - safe memory for short text content (default: True)
- * resolve_entities - replace entities by their text value (default: True)
+ - attribute_defaults - read default attributes from DTD
+ - dtd_validation - validate (if DTD is available)
+ - load_dtd - use DTD for parsing
+ - no_network - prevent network access for related files (default: True)
+ - ns_clean - clean up redundant namespace declarations
+ - recover - try hard to parse through broken XML
+ - remove_blank_text - discard blank text nodes
+ - remove_comments - discard comments
+ - remove_pis - discard processing instructions
+ - compact - safe memory for short text content (default: True)
+ - resolve_entities - replace entities by their text value (default: True)
Other keyword arguments:
- * encoding - override the document encoding
- * target - a parser target object that will receive the parse events
- * schema - an XMLSchema to validate against
+ - encoding - override the document encoding
+ - target - a parser target object that will receive the parse events
+ - schema - an XMLSchema to validate against
Note that you should avoid sharing parsers between threads. While this is
not harmful, it is more efficient to use separate parsers. This does not
@@ -1498,8 +1528,10 @@
target, None, encoding)
cdef class ETCompatXMLParser(XMLParser):
- """An XML parser with an ElementTree compatible default setup. See the
- XMLParser class for details.
+ """ETCompatXMLParser(self, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, remove_blank_text=False, compact=True, resolve_entities=True, remove_comments=True, remove_pis=True, target=None, encoding=None, schema=None)
+ An XML parser with an ElementTree compatible default setup.
+
+ See the XMLParser class for details.
This parser has ``remove_comments`` and ``remove_pis`` enabled by default
and thus ignores comments and processing instructions.
@@ -1532,15 +1564,17 @@
__GLOBAL_PARSER_CONTEXT.setDefaultParser(__DEFAULT_XML_PARSER)
def setDefaultParser(parser=None):
- "@deprecated: please use set_default_parser instead."
+ ":deprecated: please use set_default_parser instead."
set_default_parser(parser)
def getDefaultParser():
- "@deprecated: please use get_default_parser instead."
+ ":deprecated: please use get_default_parser instead."
return get_default_parser()
def set_default_parser(_BaseParser parser=None):
- """Set a default parser for the current thread. This parser is used
+ """set_default_parser(parser=None)
+
+ Set a default parser for the current thread. This parser is used
globally whenever no parser is supplied to the various parse functions of
the lxml API. If this function is called without a parser (or if it is
None), the default parser is reset to the original configuration.
@@ -1554,6 +1588,7 @@
__GLOBAL_PARSER_CONTEXT.setDefaultParser(parser)
def get_default_parser():
+ "get_default_parser()"
return __GLOBAL_PARSER_CONTEXT.getDefaultParser()
############################################################
@@ -1568,22 +1603,26 @@
)
cdef class HTMLParser(_FeedParser):
- """The HTML parser. This parser allows reading HTML into a normal XML
- tree. By default, it can read broken (non well-formed) HTML, depending on
- the capabilities of libxml2. Use the 'recover' option to switch this off.
+ """HTMLParser(self, recover=True, no_network=True, remove_blank_text=False, compact=True, remove_comments=False, remove_pis=False, target=None, encoding=None, schema=None)
+ The HTML parser.
+
+ This parser allows reading HTML into a normal XML tree. By
+ default, it can read broken (non well-formed) HTML, depending on
+ the capabilities of libxml2. Use the 'recover' option to switch
+ this off.
Available boolean keyword arguments:
- * recover - try hard to parse through broken HTML (default: True)
- * no_network - prevent network access for related files (default: True)
- * remove_blank_text - discard empty text nodes
- * remove_comments - discard comments
- * remove_pis - discard processing instructions
- * compact - safe memory for short text content (default: True)
+ - recover - try hard to parse through broken HTML (default: True)
+ - no_network - prevent network access for related files (default: True)
+ - remove_blank_text - discard empty text nodes
+ - remove_comments - discard comments
+ - remove_pis - discard processing instructions
+ - compact - safe memory for short text content (default: True)
Other keyword arguments:
- * encoding - override the document encoding
- * target - a parser target object that will receive the parse events
- * schema - an XMLSchema to validate against
+ - encoding - override the document encoding
+ - target - a parser target object that will receive the parse events
+ - schema - an XMLSchema to validate against
Note that you should avoid sharing parsers between threads for performance
reasons.
Modified: lxml/trunk/src/lxml/relaxng.pxi
==============================================================================
--- lxml/trunk/src/lxml/relaxng.pxi (original)
+++ lxml/trunk/src/lxml/relaxng.pxi Wed Feb 13 21:48:39 2008
@@ -20,7 +20,8 @@
# RelaxNG
cdef class RelaxNG(_Validator):
- """Turn a document into a Relax NG validator.
+ """RelaxNG(self, etree=None, file=None)
+ Turn a document into a Relax NG validator.
Either pass a schema as Element or ElementTree, or pass a file or
filename through the ``file`` keyword argument.
@@ -91,7 +92,9 @@
relaxng.xmlRelaxNGFree(self._c_schema)
def __call__(self, etree):
- """Validate doc using Relax NG.
+ """__call__(self, etree)
+
+ Validate doc using Relax NG.
Returns true if document is valid, false if not."""
cdef _Document doc
Modified: lxml/trunk/src/lxml/schematron.pxi
==============================================================================
--- lxml/trunk/src/lxml/schematron.pxi (original)
+++ lxml/trunk/src/lxml/schematron.pxi Wed Feb 13 21:48:39 2008
@@ -66,14 +66,15 @@
# Schematron
cdef class Schematron(_Validator):
- """A Schematron validator.
+ """Schematron(self, etree=None, file=None)
+ A Schematron validator.
Pass a root Element or an ElementTree to turn it into a validator.
Alternatively, pass a filename as keyword argument 'file' to parse from
the file system.
"""
cdef schematron.xmlSchematron* _c_schema
- def __init__(self, etree=None, file=None):
+ def __init__(self, etree=None, *, file=None):
cdef _Document doc
cdef _Element root_node
cdef xmlNode* c_node
@@ -120,7 +121,9 @@
schematron.xmlSchematronFree(self._c_schema)
def __call__(self, etree):
- """Validate doc using Schematron.
+ """__call__(self, etree)
+
+ Validate doc using Schematron.
Returns true if document is valid, false if not."""
cdef _Document doc
Modified: lxml/trunk/src/lxml/usedoctest.py
==============================================================================
--- lxml/trunk/src/lxml/usedoctest.py (original)
+++ lxml/trunk/src/lxml/usedoctest.py Wed Feb 13 21:48:39 2008
@@ -1,3 +1,13 @@
+"""Doctest module for XML comparison.
+
+Usage::
+
+ >>> import lxml.usedoctest
+ >>> # now do your XML doctests ...
+
+See `lxml.doctestcompare`
+"""
+
from lxml import doctestcompare
doctestcompare.temp_install(del_module=__name__)
Modified: lxml/trunk/src/lxml/xinclude.pxi
==============================================================================
--- lxml/trunk/src/lxml/xinclude.pxi (original)
+++ lxml/trunk/src/lxml/xinclude.pxi Wed Feb 13 21:48:39 2008
@@ -8,7 +8,8 @@
pass
cdef class XInclude:
- """XInclude processor.
+ """XInclude(self)
+ XInclude processor.
Create an instance and call it on an Element to run XInclude
processing.
@@ -22,6 +23,7 @@
return self._error_log.copy()
def __call__(self, _Element node not None):
+ "__call__(self, node)"
# We cannot pass the XML_PARSE_NOXINCNODE option as this would free
# the XInclude nodes - there may still be Python references to them!
# Therefore, we allow XInclude nodes to be converted to
Modified: lxml/trunk/src/lxml/xmlerror.pxi
==============================================================================
--- lxml/trunk/src/lxml/xmlerror.pxi (original)
+++ lxml/trunk/src/lxml/xmlerror.pxi Wed Feb 13 21:48:39 2008
@@ -5,7 +5,9 @@
# module level API functions
def clear_error_log():
- """Clear the global error log. Note that this log is already bound to a
+ """clear_error_log()
+
+ Clear the global error log. Note that this log is already bound to a
fixed size.
"""
__GLOBAL_ERROR_LOG.clear()
@@ -14,7 +16,7 @@
"""Clear the global error log. Note that this log is already bound to a
fixed size.
- @deprecated: use ``clear_error_log()`` instead.
+ :deprecated: use ``clear_error_log()`` instead.
"""
__GLOBAL_ERROR_LOG.clear()
@@ -233,8 +235,10 @@
return _ListErrorLog(filtered, None, None)
def filter_types(self, types):
- """Filter the errors by the given types and return a new error log
- containing the matches.
+ """filter_types(self, types)
+
+ Filter the errors by the given types and return a new error
+ log containing the matches.
"""
cdef _LogEntry entry
if not python.PySequence_Check(types):
@@ -246,8 +250,10 @@
return _ListErrorLog(filtered, None, None)
def filter_levels(self, levels):
- """Filter the errors by the given error levels and return a new error
- log containing the matches.
+ """filter_levels(self, levels)
+
+ Filter the errors by the given error levels and return a new
+ error log containing the matches.
"""
cdef _LogEntry entry
if not python.PySequence_Check(levels):
@@ -259,7 +265,10 @@
return _ListErrorLog(filtered, None, None)
def filter_from_level(self, level):
- "Return a log with all messages of the requested level of worse."
+ """filter_from_level(self, level)
+
+ Return a log with all messages of the requested level of worse.
+ """
cdef _LogEntry entry
filtered = []
for entry in self._entries:
@@ -268,15 +277,24 @@
return _ListErrorLog(filtered, None, None)
def filter_from_fatals(self):
- "Convenience method to get all fatal error messages."
+ """filter_from_fatals(self)
+
+ Convenience method to get all fatal error messages.
+ """
return self.filter_from_level(ErrorLevels.FATAL)
def filter_from_errors(self):
- "Convenience method to get all error messages or worse."
+ """filter_from_errors(self)
+
+ Convenience method to get all error messages or worse.
+ """
return self.filter_from_level(ErrorLevels.ERROR)
def filter_from_warnings(self):
- "Convenience method to get all warnings or worse."
+ """filter_from_warnings(self)
+
+ Convenience method to get all warnings or worse.
+ """
return self.filter_from_level(ErrorLevels.WARNING)
cdef class _ErrorLog(_ListErrorLog):
@@ -331,7 +349,8 @@
python.PyList_Append(entries, entry)
cdef class PyErrorLog(_BaseErrorLog):
- """A global error log that connects to the Python stdlib logging package.
+ """PyErrorLog(self, logger_name=None)
+ A global error log that connects to the Python stdlib logging package.
The constructor accepts an optional logger name.
@@ -395,12 +414,14 @@
Note that this disables access to the global error log from exceptions.
Parsers, XSLT etc. will continue to provide their normal local error log.
- @deprecated: use ``use_global_python_log()`` instead.
+ :deprecated: use ``use_global_python_log()`` instead.
"""
use_global_python_log(log)
def use_global_python_log(PyErrorLog log not None):
- """Replace the global error log by an etree.PyErrorLog that uses the
+ """use_global_python_log(log)
+
+ Replace the global error log by an etree.PyErrorLog that uses the
standard Python logging package.
Note that this disables access to the global error log from exceptions.
Modified: lxml/trunk/src/lxml/xmlid.pxi
==============================================================================
--- lxml/trunk/src/lxml/xmlid.pxi (original)
+++ lxml/trunk/src/lxml/xmlid.pxi Wed Feb 13 21:48:39 2008
@@ -1,7 +1,9 @@
cdef object _find_id_attributes
def XMLID(text):
- """Parse the text and return a tuple (root node, ID dictionary). The root
+ """XMLID(text)
+
+ Parse the text and return a tuple (root node, ID dictionary). The root
node is the same as returned by the XML() function. The dictionary
contains string-element pairs. The dictionary keys are the values of 'id'
attributes. The elements referenced by the ID are stored as dictionary
@@ -19,7 +21,9 @@
return (root, dic)
def XMLDTDID(text):
- """Parse the text and return a tuple (root node, ID dictionary). The root
+ """XMLDTDID(text)
+
+ Parse the text and return a tuple (root node, ID dictionary). The root
node is the same as returned by the XML() function. The dictionary
contains string-element pairs. The dictionary keys are the values of ID
attributes as defined by the DTD. The elements referenced by the ID are
@@ -37,7 +41,9 @@
return (root, _IDDict(root))
def parseid(source, parser=None):
- """Parses the source into a tuple containing an ElementTree object and an
+ """parseid(source, parser=None)
+
+ Parses the source into a tuple containing an ElementTree object and an
ID dictionary. If no parser is provided as second argument, the default
parser is used.
@@ -49,7 +55,8 @@
return (_elementTreeFactory(doc, None), _IDDict(doc))
cdef class _IDDict:
- """A dictionary-like proxy class that mapps ID attributes to elements.
+ """IDDict(self, etree)
+ A dictionary-like proxy class that mapps ID attributes to elements.
The dictionary must be instantiated with the root element of a parsed XML
document, otherwise the behaviour is undefined. Elements and XML trees
Modified: lxml/trunk/src/lxml/xmlschema.pxi
==============================================================================
--- lxml/trunk/src/lxml/xmlschema.pxi (original)
+++ lxml/trunk/src/lxml/xmlschema.pxi Wed Feb 13 21:48:39 2008
@@ -20,7 +20,8 @@
# XMLSchema
cdef class XMLSchema(_Validator):
- """Turn a document into an XML Schema validator.
+ """XMLSchema(self, etree=None, file=None)
+ Turn a document into an XML Schema validator.
Either pass a schema as Element or ElementTree, or pass a file or
filename through the ``file`` keyword argument.
@@ -83,7 +84,9 @@
xmlschema.xmlSchemaFree(self._c_schema)
def __call__(self, etree):
- """Validate doc using XML Schema.
+ """__call__(self, etree)
+
+ Validate doc using XML Schema.
Returns true if document is valid, false if not.
"""
Modified: lxml/trunk/src/lxml/xpath.pxi
==============================================================================
--- lxml/trunk/src/lxml/xpath.pxi (original)
+++ lxml/trunk/src/lxml/xpath.pxi Wed Feb 13 21:48:39 2008
@@ -127,13 +127,17 @@
self._context.set_context(xpathCtxt)
def evaluate(self, _eval_arg, **_variables):
- """Evaluate an XPath expression.
+ """evaluate(self, _eval_arg, **_variables)
+
+ Evaluate an XPath expression.
Instead of calling this method, you can also call the evaluator object
itself.
Variables may be provided as keyword arguments. Note that namespaces
are currently not supported for variables.
+
+ :deprecated: call the object, not its method.
"""
return self(_eval_arg, **_variables)
@@ -207,7 +211,8 @@
cdef class XPathElementEvaluator(_XPathEvaluatorBase):
- """Create an XPath evaluator for an element.
+ """XPathElementEvaluator(self, element, namespaces=None, extensions=None, regexp=True)
+ Create an XPath evaluator for an element.
Absolute XPath expressions (starting with '/') will be evaluated against
the ElementTree as returned by getroottree().
@@ -232,17 +237,34 @@
def registerNamespace(self, prefix, uri):
"""Register a namespace with the XPath context.
+
+ :deprecated: use ``register_namespace()`` instead
+ """
+ self._context.addNamespace(prefix, uri)
+
+ def register_namespace(self, prefix, uri):
+ """Register a namespace with the XPath context.
"""
self._context.addNamespace(prefix, uri)
def registerNamespaces(self, namespaces):
"""Register a prefix -> uri dict.
+
+ :deprecated: use ``register_namespaces()`` instead
+ """
+ for prefix, uri in namespaces.items():
+ self._context.addNamespace(prefix, uri)
+
+ def register_namespaces(self, namespaces):
+ """Register a prefix -> uri dict.
"""
for prefix, uri in namespaces.items():
self._context.addNamespace(prefix, uri)
def __call__(self, _path, **_variables):
- """Evaluate an XPath expression on the document.
+ """__call__(self, _path, **_variables)
+
+ Evaluate an XPath expression on the document.
Variables may be provided as keyword arguments. Note that namespaces
are currently not supported for variables.
@@ -276,7 +298,8 @@
cdef class XPathDocumentEvaluator(XPathElementEvaluator):
- """Create an XPath evaluator for an ElementTree.
+ """XPathDocumentEvaluator(self, etree, namespaces=None, extensions=None, regexp=True)
+ Create an XPath evaluator for an ElementTree.
Additional namespace declarations can be passed with the 'namespace'
keyword argument. EXSLT regular expression support can be disabled with
@@ -289,7 +312,9 @@
extensions=extensions, regexp=regexp)
def __call__(self, _path, **_variables):
- """Evaluate an XPath expression on the document.
+ """__call__(self, _path, **_variables)
+
+ Evaluate an XPath expression on the document.
Variables may be provided as keyword arguments. Note that namespaces
are currently not supported for variables.
@@ -327,7 +352,9 @@
def XPathEvaluator(etree_or_element, *, namespaces=None, extensions=None,
regexp=True):
- """Creates an XPath evaluator for an ElementTree or an Element.
+ """XPathEvaluator(etree_or_element, namespaces=None, extensions=None, regexp=True)
+
+ Creates an XPath evaluator for an ElementTree or an Element.
The resulting object can be called with an XPath expression as argument
and XPath variables provided as keyword arguments.
@@ -347,8 +374,8 @@
cdef class XPath(_XPathEvaluatorBase):
- """A compiled XPath expression that can be called on Elements and
- ElementTrees.
+ """XPath(self, path, namespaces=None, extensions=None, regexp=True)
+ A compiled XPath expression that can be called on Elements and ElementTrees.
Besides the XPath expression, you can pass prefix-namespace mappings and
extension functions to the constructor through the keyword arguments
@@ -374,6 +401,7 @@
self._raise_parse_error()
def __call__(self, _etree_or_element, **_variables):
+ "__call__(self, _etree_or_element, **_variables)"
cdef xpath.xmlXPathObject* xpathObj
cdef _Document document
cdef _Element element
@@ -414,8 +442,8 @@
_find_namespaces = re.compile('({[^}]+})').findall
cdef class ETXPath(XPath):
- """Special XPath class that supports the ElementTree {uri} notation for
- namespaces.
+ """ETXPath(self, path, extensions=None, regexp=True)
+ Special XPath class that supports the ElementTree {uri} notation for namespaces.
Note that this class does not accept the ``namespace`` keyword
argument. All namespaces must be passed as part of the path string.
Modified: lxml/trunk/src/lxml/xslt.pxi
==============================================================================
--- lxml/trunk/src/lxml/xslt.pxi (original)
+++ lxml/trunk/src/lxml/xslt.pxi Wed Feb 13 21:48:39 2008
@@ -167,16 +167,18 @@
# XSLT file/network access control
cdef class XSLTAccessControl:
- """Access control for XSLT: reading/writing files, directories and network
- I/O. Access to a type of resource is granted or denied by passing any of
- the following keyword arguments. All of them default to True to allow
- access.
-
- * read_file
- * write_file
- * create_dir
- * read_network
- * write_network
+ """XSLTAccessControl(self, read_file=True, write_file=True, create_dir=True, read_network=True, write_network=True)
+
+ Access control for XSLT: reading/writing files, directories and
+ network I/O. Access to a type of resource is granted or denied by
+ passing any of the following boolean keyword arguments. All of
+ them default to True to allow access.
+
+ - read_file
+ - write_file
+ - create_dir
+ - read_network
+ - write_network
"""
cdef xslt.xsltSecurityPrefs* _prefs
def __init__(self, *, read_file=True, write_file=True, create_dir=True,
@@ -252,16 +254,25 @@
cdef class XSLT:
- """Turn a document into an XSLT object.
+ """XSLT(self, xslt_input, extensions=None, regexp=True, access_control=None)
+
+ Turn an XSL document into an XSLT object.
+
+ Calling this object on a tree or Element will execute the XSLT::
+
+ >>> transform = etree.XSLT(xsl_tree)
+ >>> result = transform(xml_tree)
Keyword arguments of the constructor:
- * regexp - enable exslt regular expression support in XPath (default: True)
- * access_control - access restrictions for network or file system
+ - regexp: enable exslt regular expression support in XPath
+ (default: True)
+ - access_control: access restrictions for network or file
+ system (see `XSLTAccessControl`)
- Keyword arguments of the XSLT run:
- * profile_run - enable XSLT profiling
+ Keyword arguments of the XSLT call:
+ - profile_run: enable XSLT profiling (default: False)
- Other keyword arguments are passed to the stylesheet.
+ Other keyword arguments of the call are passed to the stylesheet.
"""
cdef _XSLTContext _context
cdef xslt.xsltStylesheet* _c_style
@@ -328,14 +339,22 @@
xslt.xsltFreeStylesheet(self._c_style)
property error_log:
+ "The log of errors and warnings of an XSLT execution."
def __get__(self):
return self._error_log.copy()
def apply(self, _input, *, profile_run=False, **_kw):
+ """apply(self, _input, profile_run=False, **_kw)
+
+ :deprecated: call the object, not this method."""
return self(_input, profile_run=profile_run, **_kw)
def tostring(self, _ElementTree result_tree):
- """Save result doc to string based on stylesheet output method.
+ """tostring(self, result_tree)
+
+ Save result doc to string based on stylesheet output method.
+
+ :deprecated: use str(result_tree) instead.
"""
return str(result_tree)
@@ -346,6 +365,14 @@
return _copyXSLT(self)
def __call__(self, _input, *, profile_run=False, **_kw):
+ """__call__(self, _input, profile_run=False, **_kw)
+
+ Execute the XSL transformation on a tree or Element.
+
+ Pass the ``profile_run`` option to get profile information
+ about the XSLT. The result of the XSLT will have a property
+ xslt_profile that holds an XML tree with profiling data.
+ """
cdef _XSLTContext context
cdef _XSLTResolverContext resolver_context
cdef _Document input_doc
More information about the lxml-checkins
mailing list