index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
71,922 |
elementpath.exceptions
|
MissingContextError
|
Raised when the dynamic context is required for evaluate the XPath expression.
|
class MissingContextError(ElementPathError):
"""Raised when the dynamic context is required for evaluate the XPath expression."""
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,925 |
elementpath.xpath_nodes
|
NamespaceNode
|
A class for processing XPath namespace nodes.
:param prefix: the namespace prefix.
:param uri: the namespace URI.
:param parent: the parent element node.
:param position: the position of the node in the document.
|
class NamespaceNode(XPathNode):
"""
A class for processing XPath namespace nodes.
:param prefix: the namespace prefix.
:param uri: the namespace URI.
:param parent: the parent element node.
:param position: the position of the node in the document.
"""
attributes: None
children: None = None
base_uri: None
document_uri: None
is_id: None
is_idrefs: None
namespace_nodes: None
nilled: None
parent: Optional['ElementNode']
type_name: None
kind = 'namespace'
__slots__ = 'prefix', 'uri'
def __init__(self,
prefix: Optional[str], uri: str,
parent: Optional['ElementNode'] = None,
position: int = 1) -> None:
self.prefix = prefix
self.uri = uri
self.parent = parent
self.position = position
@property
def name(self) -> Optional[str]:
return self.prefix
@property
def value(self) -> str:
return self.uri
def as_item(self) -> Tuple[Optional[str], str]:
return self.prefix, self.uri
def __repr__(self) -> str:
return '%s(prefix=%r, uri=%r)' % (self.__class__.__name__, self.prefix, self.uri)
@property
def string_value(self) -> str:
return self.uri
@property
def typed_value(self) -> str:
return self.uri
|
(prefix: Optional[str], uri: str, parent: Optional[elementpath.xpath_nodes.ElementNode] = None, position: int = 1) -> None
|
71,926 |
elementpath.xpath_nodes
|
__init__
| null |
def __init__(self,
prefix: Optional[str], uri: str,
parent: Optional['ElementNode'] = None,
position: int = 1) -> None:
self.prefix = prefix
self.uri = uri
self.parent = parent
self.position = position
|
(self, prefix: Optional[str], uri: str, parent: Optional[elementpath.xpath_nodes.ElementNode] = None, position: int = 1) -> NoneType
|
71,927 |
elementpath.xpath_nodes
|
__repr__
| null |
def __repr__(self) -> str:
return '%s(prefix=%r, uri=%r)' % (self.__class__.__name__, self.prefix, self.uri)
|
(self) -> str
|
71,928 |
elementpath.xpath_nodes
|
as_item
| null |
def as_item(self) -> Tuple[Optional[str], str]:
return self.prefix, self.uri
|
(self) -> Tuple[Optional[str], str]
|
71,931 |
elementpath.xpath_nodes
|
ProcessingInstructionNode
|
A class for XPath processing instructions nodes.
:param elem: the wrapped Processing Instruction Element.
:param parent: the parent element node.
:param position: the position of the node in the document.
|
class ProcessingInstructionNode(XPathNode):
"""
A class for XPath processing instructions nodes.
:param elem: the wrapped Processing Instruction Element.
:param parent: the parent element node.
:param position: the position of the node in the document.
"""
attributes: None
children: None = None
document_uri: None
is_id: None
is_idrefs: None
namespace_nodes: None
nilled: None
type_name: None
kind = 'processing-instruction'
__slots__ = 'elem',
def __init__(self,
elem: ElementProtocol,
parent: Union['ElementNode', 'DocumentNode', None] = None,
position: int = 1) -> None:
self.elem = elem
self.parent = parent
self.position = position
def __repr__(self) -> str:
return '%s(elem=%r)' % (self.__class__.__name__, self.elem)
@property
def value(self) -> ElementProtocol:
return self.elem
@property
def name(self) -> str:
try:
# an lxml PI
return cast(str, self.elem.target) # type: ignore[attr-defined]
except AttributeError:
return cast(str, self.elem.text).split(' ', maxsplit=1)[0]
@property
def string_value(self) -> str:
if hasattr(self.elem, 'target'):
return self.elem.text or ''
try:
return cast(str, self.elem.text).split(' ', maxsplit=1)[1]
except IndexError:
return ''
@property
def typed_value(self) -> str:
return self.string_value
|
(elem: elementpath.protocols.ElementProtocol, parent: Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode, NoneType] = None, position: int = 1) -> None
|
71,936 |
elementpath.regex.unicode_subsets
|
RegexError
|
Error in a regular expression or in a character class specification.
This exception is derived from `Exception` base class and is raised
only by the regex subpackage.
|
class RegexError(Exception):
"""
Error in a regular expression or in a character class specification.
This exception is derived from `Exception` base class and is raised
only by the regex subpackage.
"""
| null |
71,937 |
elementpath.xpath_nodes
|
SchemaElementNode
|
An element node class for wrapping the XSD schema and its elements.
The resulting structure can be a tree or a set of disjoint trees.
With more roots only one of them is the schema node.
|
class SchemaElementNode(ElementNode):
"""
An element node class for wrapping the XSD schema and its elements.
The resulting structure can be a tree or a set of disjoint trees.
With more roots only one of them is the schema node.
"""
__slots__ = ()
ref: Optional['SchemaElementNode'] = None
elem: SchemaElemType
def __iter__(self) -> Iterator[ChildNodeType]:
if self.ref is None:
yield from self.children
else:
yield from self.ref.children
@property
def attributes(self) -> List['AttributeNode']:
if self._attributes is None:
position = self.position + len(self.nsmap) + int('xml' not in self.nsmap)
self._attributes = [
AttributeNode(name, attr, self, pos, attr.type)
for pos, (name, attr) in enumerate(self.elem.attrib.items(), position)
]
return self._attributes
@property
def base_uri(self) -> Optional[str]:
base_uri = self.uri.strip() if self.uri is not None else None
if self.parent is None:
return base_uri
elif base_uri is None:
return self.parent.base_uri
else:
return urljoin(self.parent.base_uri or '', base_uri)
@property
def string_value(self) -> str:
if not hasattr(self.elem, 'type'):
return ''
schema_node = cast(XsdElementProtocol, self.elem)
return str(get_atomic_value(schema_node.type))
@property
def typed_value(self) -> Optional[AtomicValueType]:
if not hasattr(self.elem, 'type'):
return UntypedAtomic('')
schema_node = cast(XsdElementProtocol, self.elem)
return get_atomic_value(schema_node.type)
def iter(self) -> Iterator[XPathNode]:
yield self
iterators: List[Any] = []
children: Iterator[Any] = iter(self.children)
if self._namespace_nodes:
yield from self._namespace_nodes
if self._attributes:
yield from self._attributes
elements = {self}
while True:
for child in children:
if child in elements:
continue
yield child
elements.add(child)
if isinstance(child, ElementNode):
if child._namespace_nodes:
yield from child._namespace_nodes
if child._attributes:
yield from child._attributes
if child.children:
iterators.append(children)
children = iter(child.children)
break
else:
try:
children = iterators.pop()
except IndexError:
return
def iter_descendants(self, with_self: bool = True) -> Iterator[ChildNodeType]:
if with_self:
yield self
iterators: List[Any] = []
children: Iterator[Any] = iter(self.children)
elements = {self}
while True:
for child in children:
if child.ref is not None:
child = child.ref
if child in elements:
continue
yield child
elements.add(child)
if child.children:
iterators.append(children)
children = iter(child.children)
break
else:
try:
children = iterators.pop()
except IndexError:
return
|
(elem: Union[elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol], parent: Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode, NoneType] = None, position: int = 1, nsmap: MutableMapping[Optional[str], str] = None, xsd_type: Optional[elementpath.protocols.XsdTypeProtocol] = None) -> None
|
71,940 |
elementpath.xpath_nodes
|
__iter__
| null |
def __iter__(self) -> Iterator[ChildNodeType]:
if self.ref is None:
yield from self.children
else:
yield from self.ref.children
|
(self) -> Iterator[Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]
|
71,946 |
elementpath.xpath_nodes
|
iter
| null |
def iter(self) -> Iterator[XPathNode]:
yield self
iterators: List[Any] = []
children: Iterator[Any] = iter(self.children)
if self._namespace_nodes:
yield from self._namespace_nodes
if self._attributes:
yield from self._attributes
elements = {self}
while True:
for child in children:
if child in elements:
continue
yield child
elements.add(child)
if isinstance(child, ElementNode):
if child._namespace_nodes:
yield from child._namespace_nodes
if child._attributes:
yield from child._attributes
if child.children:
iterators.append(children)
children = iter(child.children)
break
else:
try:
children = iterators.pop()
except IndexError:
return
|
(self) -> Iterator[elementpath.xpath_nodes.XPathNode]
|
71,947 |
elementpath.xpath_nodes
|
iter_descendants
| null |
def iter_descendants(self, with_self: bool = True) -> Iterator[ChildNodeType]:
if with_self:
yield self
iterators: List[Any] = []
children: Iterator[Any] = iter(self.children)
elements = {self}
while True:
for child in children:
if child.ref is not None:
child = child.ref
if child in elements:
continue
yield child
elements.add(child)
if child.children:
iterators.append(children)
children = iter(child.children)
break
else:
try:
children = iterators.pop()
except IndexError:
return
|
(self, with_self: bool = True) -> Iterator[Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]
|
71,950 |
elementpath.xpath_selectors
|
Selector
|
XPath selector class. Create an instance of this class if you want to apply an XPath
selector to several target data.
:param path: the XPath expression.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param parser: the parser class to use, that is :class:`XPath2Parser` for default.
:param kwargs: other optional parameters for the XPath parser instance.
:ivar path: the XPath expression.
:vartype path: str
:ivar parser: the parser instance.
:vartype parser: XPath1Parser or XPath2Parser
:ivar root_token: the root of tokens tree compiled from path.
:vartype root_token: XPathToken
|
class Selector(object):
"""
XPath selector class. Create an instance of this class if you want to apply an XPath
selector to several target data.
:param path: the XPath expression.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param parser: the parser class to use, that is :class:`XPath2Parser` for default.
:param kwargs: other optional parameters for the XPath parser instance.
:ivar path: the XPath expression.
:vartype path: str
:ivar parser: the parser instance.
:vartype parser: XPath1Parser or XPath2Parser
:ivar root_token: the root of tokens tree compiled from path.
:vartype root_token: XPathToken
"""
def __init__(self, path: str,
namespaces: Optional[NamespacesType] = None,
parser: Optional[ParserType] = None,
**kwargs: Any) -> None:
self._variables = kwargs.pop('variables', None) # For backward compatibility
self.parser = (parser or XPath2Parser)(namespaces, **kwargs)
self.path = path
self.root_token = self.parser.parse(path)
def __repr__(self) -> str:
return '%s(path=%r, parser=%s)' % (
self.__class__.__name__, self.path, self.parser.__class__.__name__
)
@property
def namespaces(self) -> Dict[str, str]:
"""A dictionary with mapping from namespace prefixes into URIs."""
return self.parser.namespaces
def select(self, root: Optional[RootArgType], **kwargs: Any) -> Any:
"""
Applies the instance's XPath expression on *root* Element.
:param root: the root of the XML document, usually an ElementTree instance \
or an Element.
:param kwargs: other optional parameters for the XPath dynamic context.
:return: a list with XPath nodes or a basic type for expressions based on \
a function or literal.
"""
if 'variables' not in kwargs and self._variables:
kwargs['variables'] = self._variables
context = XPathContext(root, **kwargs)
return self.root_token.get_results(context)
def iter_select(self, root: Optional[RootArgType], **kwargs: Any) -> Iterator[Any]:
"""
Creates an XPath selector generator for apply the instance's XPath expression
on *root* Element.
:param root: the root of the XML document, usually an ElementTree instance \
or an Element.
:param kwargs: other optional parameters for the XPath dynamic context.
:return: a generator of the XPath expression results.
"""
if 'variables' not in kwargs and self._variables:
kwargs['variables'] = self._variables
context = XPathContext(root, **kwargs)
return self.root_token.select_results(context)
|
(path: str, namespaces: Optional[MutableMapping[str, str]] = None, parser: Optional[elementpath.xpath2.xpath2_parser.XPath2Parser] = None, **kwargs: Any) -> None
|
71,951 |
elementpath.xpath_selectors
|
__init__
| null |
def __init__(self, path: str,
namespaces: Optional[NamespacesType] = None,
parser: Optional[ParserType] = None,
**kwargs: Any) -> None:
self._variables = kwargs.pop('variables', None) # For backward compatibility
self.parser = (parser or XPath2Parser)(namespaces, **kwargs)
self.path = path
self.root_token = self.parser.parse(path)
|
(self, path: str, namespaces: Optional[MutableMapping[str, str]] = None, parser: Optional[elementpath.xpath2.xpath2_parser.XPath2Parser] = None, **kwargs: Any) -> NoneType
|
71,952 |
elementpath.xpath_selectors
|
__repr__
| null |
def __repr__(self) -> str:
return '%s(path=%r, parser=%s)' % (
self.__class__.__name__, self.path, self.parser.__class__.__name__
)
|
(self) -> str
|
71,953 |
elementpath.xpath_selectors
|
iter_select
|
Creates an XPath selector generator for apply the instance's XPath expression
on *root* Element.
:param root: the root of the XML document, usually an ElementTree instance or an Element.
:param kwargs: other optional parameters for the XPath dynamic context.
:return: a generator of the XPath expression results.
|
def iter_select(self, root: Optional[RootArgType], **kwargs: Any) -> Iterator[Any]:
"""
Creates an XPath selector generator for apply the instance's XPath expression
on *root* Element.
:param root: the root of the XML document, usually an ElementTree instance \
or an Element.
:param kwargs: other optional parameters for the XPath dynamic context.
:return: a generator of the XPath expression results.
"""
if 'variables' not in kwargs and self._variables:
kwargs['variables'] = self._variables
context = XPathContext(root, **kwargs)
return self.root_token.select_results(context)
|
(self, root: Union[elementpath.protocols.DocumentProtocol, elementpath.protocols.ElementProtocol, elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol, ForwardRef('DocumentNode'), ForwardRef('ElementNode'), NoneType], **kwargs: Any) -> Iterator[Any]
|
71,954 |
elementpath.xpath_selectors
|
select
|
Applies the instance's XPath expression on *root* Element.
:param root: the root of the XML document, usually an ElementTree instance or an Element.
:param kwargs: other optional parameters for the XPath dynamic context.
:return: a list with XPath nodes or a basic type for expressions based on a function or literal.
|
def select(self, root: Optional[RootArgType], **kwargs: Any) -> Any:
"""
Applies the instance's XPath expression on *root* Element.
:param root: the root of the XML document, usually an ElementTree instance \
or an Element.
:param kwargs: other optional parameters for the XPath dynamic context.
:return: a list with XPath nodes or a basic type for expressions based on \
a function or literal.
"""
if 'variables' not in kwargs and self._variables:
kwargs['variables'] = self._variables
context = XPathContext(root, **kwargs)
return self.root_token.get_results(context)
|
(self, root: Union[elementpath.protocols.DocumentProtocol, elementpath.protocols.ElementProtocol, elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol, ForwardRef('DocumentNode'), ForwardRef('ElementNode'), NoneType], **kwargs: Any) -> Any
|
71,955 |
elementpath.xpath_nodes
|
TextNode
|
A class for processing XPath text nodes. An Element's property
(elem.text or elem.tail) with a `None` value is not a text node.
:param value: a string value.
:param parent: the parent element node.
:param position: the position of the node in the document.
|
class TextNode(XPathNode):
"""
A class for processing XPath text nodes. An Element's property
(elem.text or elem.tail) with a `None` value is not a text node.
:param value: a string value.
:param parent: the parent element node.
:param position: the position of the node in the document.
"""
attributes: None
children: None = None
document_uri: None
is_id: None
is_idrefs: None
namespace_nodes: None
nilled: None
name: None
parent: Optional['ElementNode']
type_name: None
kind = 'text'
value: str
__slots__ = 'value',
def __init__(self,
value: str,
parent: Optional['ElementNode'] = None,
position: int = 1) -> None:
self.value = value
self.parent = parent
self.position = position
def __repr__(self) -> str:
return '%s(value=%r)' % (self.__class__.__name__, self.value)
@property
def string_value(self) -> str:
return self.value
@property
def typed_value(self) -> UntypedAtomic:
return UntypedAtomic(self.value)
|
(value: str, parent: Optional[elementpath.xpath_nodes.ElementNode] = None, position: int = 1) -> None
|
71,956 |
elementpath.xpath_nodes
|
__init__
| null |
def __init__(self,
value: str,
parent: Optional['ElementNode'] = None,
position: int = 1) -> None:
self.value = value
self.parent = parent
self.position = position
|
(self, value: str, parent: Optional[elementpath.xpath_nodes.ElementNode] = None, position: int = 1) -> NoneType
|
71,957 |
elementpath.xpath_nodes
|
__repr__
| null |
def __repr__(self) -> str:
return '%s(value=%r)' % (self.__class__.__name__, self.value)
|
(self) -> str
|
71,960 |
elementpath.xpath1.xpath1_parser
|
XPath1Parser
|
XPath 1.0 expression parser class. Provide a *namespaces* dictionary argument for
mapping namespace prefixes to URI inside expressions. If *strict* is set to `False`
the parser enables also the parsing of QNames, like the ElementPath library.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param strict: a strict mode is `False` the parser enables parsing of QNames in extended format, like the Python's ElementPath library. Default is `True`.
|
class XPath1Parser(Parser[XPathToken]):
"""
XPath 1.0 expression parser class. Provide a *namespaces* dictionary argument for
mapping namespace prefixes to URI inside expressions. If *strict* is set to `False`
the parser enables also the parsing of QNames, like the ElementPath library.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param strict: a strict mode is `False` the parser enables parsing of QNames \
in extended format, like the Python's ElementPath library. Default is `True`.
"""
version = '1.0'
"""The XPath version string."""
token_base_class: Type[Token[Any]] = XPathToken
literals_pattern = re.compile(
r"""'(?:[^']|'')*'|"(?:[^"]|"")*"|(?:\d+|\.\d+)(?:\.\d*)?(?:[Ee][+-]?\d+)?"""
)
name_pattern = re.compile(r'[^\d\W][\w.\-\xb7\u0300-\u036F\u203F\u2040]*')
RESERVED_FUNCTION_NAMES = {
'comment', 'element', 'node', 'processing-instruction', 'text'
}
DEFAULT_NAMESPACES: ClassVar[Dict[str, str]] = {'xml': XML_NAMESPACE}
"""Namespaces known statically by default."""
# Labels and symbols admitted after a path step
PATH_STEP_LABELS: ClassVar[Tuple[str, ...]] = ('axis', 'kind test')
PATH_STEP_SYMBOLS: ClassVar[Set[str]] = {
'(integer)', '(string)', '(float)', '(decimal)', '(name)', '*', '@', '..', '.', '{'
}
# Class attributes for compatibility with XPath 2.0+
schema: Optional[AbstractSchemaProxy] = None
variable_types: Optional[Dict[str, str]] = None
base_uri: Optional[str] = None
function_namespace = XPATH_FUNCTIONS_NAMESPACE
function_signatures: Dict[Tuple[QName, int], str] = {}
parse_arguments: bool = True
compatibility_mode: bool = True
"""XPath 1.0 compatibility mode."""
default_namespace: Optional[str] = None
"""
The default namespace. For XPath 1.0 this value is always `None` because the default
namespace is ignored (see https://www.w3.org/TR/1999/REC-xpath-19991116/#node-tests).
"""
def __init__(self, namespaces: Optional[NamespacesType] = None,
strict: bool = True) -> None:
super(XPath1Parser, self).__init__()
self.namespaces: Dict[str, str] = self.DEFAULT_NAMESPACES.copy()
if namespaces is not None:
self.namespaces.update(namespaces)
self.strict: bool = strict
def __str__(self) -> str:
args = []
if self.namespaces != self.DEFAULT_NAMESPACES:
args.append(str(self.other_namespaces))
if not self.strict:
args.append('strict=False')
return f"{self.__class__.__name__}({', '.join(args)})"
@property
def other_namespaces(self) -> Dict[str, str]:
"""The subset of namespaces not known by default."""
return {k: v for k, v in self.namespaces.items()
if k not in self.DEFAULT_NAMESPACES or self.DEFAULT_NAMESPACES[k] != v}
@property
def xsd_version(self) -> str:
return '1.0' # Use XSD 1.0 datatypes for default
def xsd_qname(self, local_name: str) -> str:
"""Returns a prefixed QName string for XSD namespace."""
if self.namespaces.get('xs') == XSD_NAMESPACE:
return 'xs:%s' % local_name
for pfx, uri in self.namespaces.items():
if uri == XSD_NAMESPACE:
return '%s:%s' % (pfx, local_name) if pfx else local_name
raise xpath_error('XPST0081', 'Missing XSD namespace registration')
@classmethod
def create_restricted_parser(cls, name: str, symbols: Sequence[str]) \
-> Type['XPath1Parser']:
"""Get a parser subclass with a restricted set of symbols.s"""
symbol_table = {
k: v for k, v in cls.symbol_table.items() if k in symbols
}
return cast(Type['XPath1Parser'], ABCMeta(
f"{name}{cls.__name__}", (cls,), {'symbol_table': symbol_table}
))
@staticmethod
def unescape(string_literal: str) -> str:
if string_literal.startswith("'"):
return string_literal[1:-1].replace("''", "'")
else:
return string_literal[1:-1].replace('""', '"')
@classmethod
def proxy(cls, symbol: str, label: str = 'proxy', bp: int = 90) -> Type[ProxyToken]:
"""Register a proxy token for a symbol."""
if symbol in cls.symbol_table and not issubclass(cls.symbol_table[symbol], ProxyToken):
# Move the token class before register the proxy token
token_cls = cls.symbol_table.pop(symbol)
cls.symbol_table[f'{{{token_cls.namespace}}}{symbol}'] = token_cls
proxy_class = cls.register(symbol, bases=(ProxyToken,), label=label, lbp=bp, rbp=bp)
return cast(Type[ProxyToken], proxy_class)
@classmethod
def axis(cls, symbol: str, reverse_axis: bool = False, bp: int = 80) -> Type[XPathAxis]:
"""Register a token for a symbol that represents an XPath *axis*."""
token_class = cls.register(symbol, label='axis', bases=(XPathAxis,),
reverse_axis=reverse_axis, lbp=bp, rbp=bp)
return cast(Type[XPathAxis], token_class)
@classmethod
def function(cls, symbol: str,
prefix: Optional[str] = None,
label: str = 'function',
nargs: NargsType = None,
sequence_types: Tuple[str, ...] = (),
bp: int = 90) -> Type[XPathFunction]:
"""
Registers a token class for a symbol that represents an XPath function.
"""
kwargs = {
'bases': (XPathFunction,),
'label': label,
'nargs': nargs,
'lbp': bp,
'rbp': bp,
}
if 'function' not in label:
# kind test or sequence type
return cast(Type[XPathFunction], cls.register(symbol, **kwargs))
elif symbol in cls.RESERVED_FUNCTION_NAMES:
raise ElementPathValueError(f'{symbol!r} is a reserved function name')
if prefix:
namespace = cls.DEFAULT_NAMESPACES[prefix]
qname = QName(namespace, '%s:%s' % (prefix, symbol))
kwargs['lookup_name'] = qname.expanded_name
kwargs['class_name'] = '_%s%s%s' % (
prefix.capitalize(),
symbol.capitalize(),
str(label).title().replace(' ', '')
)
kwargs['namespace'] = namespace
cls.proxy(symbol, label='proxy function', bp=bp)
else:
qname = QName(XPATH_FUNCTIONS_NAMESPACE, 'fn:%s' % symbol)
kwargs['namespace'] = XPATH_FUNCTIONS_NAMESPACE
if sequence_types:
# Register function signature(s)
kwargs['sequence_types'] = sequence_types
if nargs is None:
pass # pragma: no cover
elif isinstance(nargs, int):
assert len(sequence_types) == nargs + 1
cls.function_signatures[(qname, nargs)] = 'function({}) as {}'.format(
', '.join(sequence_types[:-1]), sequence_types[-1]
)
elif nargs[1] is None:
assert len(sequence_types) == nargs[0] + 1
cls.function_signatures[(qname, nargs[0])] = 'function({}, ...) as {}'.format(
', '.join(sequence_types[:-1]), sequence_types[-1]
)
else:
assert len(sequence_types) == nargs[1] + 1
for arity in range(nargs[0], nargs[1] + 1):
cls.function_signatures[(qname, arity)] = 'function({}) as {}'.format(
', '.join(sequence_types[:arity]), sequence_types[-1]
)
return cast(Type[XPathFunction], cls.register(symbol, **kwargs))
def parse(self, source: str) -> XPathToken:
root_token = super(XPath1Parser, self).parse(source)
try:
root_token.evaluate() # Static context evaluation
except MissingContextError:
pass
return root_token
def expected_next(self, *symbols: str, message: Optional[str] = None) -> None:
"""
Checks the next token with a list of symbols. Replaces the next token with
a '(name)' token if the check fails and the next token can be a name,
otherwise raises a syntax error.
:param symbols: a sequence of symbols.
:param message: optional error message.
"""
if self.next_token.symbol in symbols:
return
elif '(name)' in symbols and \
not isinstance(self.next_token, (XPathFunction, XPathAxis)) and \
self.name_pattern.match(self.next_token.symbol) is not None:
# Disambiguation replacing the next token with a '(name)' token
self.next_token = self.symbol_table['(name)'](self, self.next_token.symbol)
else:
raise self.next_token.wrong_syntax(message)
def check_variables(self, values: MutableMapping[str, Any]) -> None:
"""Checks the sequence types of the XPath dynamic context's variables."""
for varname, value in values.items():
if not match_sequence_type(
value, 'item()*' if isinstance(value, list) else 'item()', self
):
message = "Unmatched sequence type for variable {!r}".format(varname)
raise xpath_error('XPDY0050', message)
def get_function(self, name: str, arity: Optional[int],
context: ContextArgType = None) -> XPathFunction:
"""
Returns an XPathFunction object suitable for stand-alone usage.
:param name: the name of the function.
:param arity: the arity of the function object, must be compatible \
with the signature of the XPath function.
:param context: an optional context to bound to the function.
"""
if ':' not in name:
qname = QName(XPATH_FUNCTIONS_NAMESPACE, f'fn:{name}')
elif name.startswith('fn:'):
qname = QName(XPATH_FUNCTIONS_NAMESPACE, name)
name = name[3:]
else:
prefix, name = name.split(':')
try:
namespace = self.namespaces[prefix]
except KeyError:
raise ElementPathKeyError(f"Unknown namespace {prefix!r}") from None
else:
qname = QName(namespace, f'{prefix}:{name}')
if qname.expanded_name in self.symbol_table:
token_class = self.symbol_table[qname.expanded_name]
elif name in self.symbol_table:
token_class = self.symbol_table[name]
else:
raise ElementPathNameError(f'unknown function {name!r}')
if not issubclass(token_class, XPathFunction):
raise ElementPathNameError(f'{name!r} is not an XPath function')
if token_class.namespace != qname.namespace:
raise ElementPathNameError(f'namespace mismatch: {token_class.namespace}')
try:
func = token_class(self, nargs=arity)
except TypeError:
msg = f"unknown function {qname.qname}#{arity}"
raise xpath_error('XPST0017', msg) from None
else:
if context is not None:
func.context = context
return func
|
(namespaces: Optional[MutableMapping[str, str]] = None, strict: bool = True) -> None
|
71,961 |
elementpath.tdop
|
__eq__
| null |
def __eq__(self, other: object) -> bool:
return isinstance(other, Parser) and \
self.token_base_class is other.token_base_class and \
self.symbol_table == other.symbol_table
|
(self, other: object) -> bool
|
71,962 |
elementpath.xpath1.xpath1_parser
|
__init__
| null |
def __init__(self, namespaces: Optional[NamespacesType] = None,
strict: bool = True) -> None:
super(XPath1Parser, self).__init__()
self.namespaces: Dict[str, str] = self.DEFAULT_NAMESPACES.copy()
if namespaces is not None:
self.namespaces.update(namespaces)
self.strict: bool = strict
|
(self, namespaces: Optional[MutableMapping[str, str]] = None, strict: bool = True) -> NoneType
|
71,963 |
elementpath.tdop
|
__repr__
| null |
def __repr__(self) -> str:
return '<%s object at %#x>' % (self.__class__.__name__, id(self))
|
(self) -> str
|
71,964 |
elementpath.xpath1.xpath1_parser
|
__str__
| null |
def __str__(self) -> str:
args = []
if self.namespaces != self.DEFAULT_NAMESPACES:
args.append(str(self.other_namespaces))
if not self.strict:
args.append('strict=False')
return f"{self.__class__.__name__}({', '.join(args)})"
|
(self) -> str
|
71,965 |
elementpath.tdop
|
advance
|
The Pratt's function for advancing to next token.
:param symbols: Optional arguments tuple. If not empty one of the provided symbols is expected. If the next token's symbol differs the parser raises a parse error.
:param message: Optional custom message for unexpected symbols.
:return: The current token instance.
|
def advance(self, *symbols: str, message: Optional[str] = None) -> TK_co:
"""
The Pratt's function for advancing to next token.
:param symbols: Optional arguments tuple. If not empty one of the provided \
symbols is expected. If the next token's symbol differs the parser raises a \
parse error.
:param message: Optional custom message for unexpected symbols.
:return: The current token instance.
"""
value: Any
if self.next_token.symbol == '(end)':
raise self.next_token.wrong_syntax()
elif symbols and self.next_token.symbol not in symbols:
raise self.next_token.wrong_syntax(message)
self.token = self.next_token
for self.next_match in self.tokens:
assert self.next_match is not None
if not self.next_match.group().isspace():
break
else:
self.next_token = self.symbol_table['(end)'](self)
return self.token
literal, symbol, name, unknown = self.next_match.groups()
if symbol is not None:
try:
self.next_token = self.symbol_table[symbol](self)
except KeyError:
if self.name_pattern.match(symbol) is None:
self.next_token = self.symbol_table['(unknown)'](self, symbol)
raise self.next_token.wrong_syntax()
self.next_token = self.symbol_table['(name)'](self, symbol)
elif literal is not None:
if literal[0] in '\'"':
value = self.unescape(literal)
self.next_token = self.symbol_table['(string)'](self, value)
elif 'e' in literal or 'E' in literal:
try:
value = float(literal)
except ValueError as err:
self.next_token = self.symbol_table['(invalid)'](self, literal)
raise self.next_token.wrong_syntax(message=str(err))
else:
self.next_token = self.symbol_table['(float)'](self, value)
elif '.' in literal:
try:
value = Decimal(literal)
except DecimalException as err:
self.next_token = self.symbol_table['(invalid)'](self, literal)
raise self.next_token.wrong_syntax(message=str(err))
else:
self.next_token = self.symbol_table['(decimal)'](self, value)
else:
self.next_token = self.symbol_table['(integer)'](self, int(literal))
elif name is not None:
self.next_token = self.symbol_table['(name)'](self, name)
elif unknown is not None:
self.next_token = self.symbol_table['(unknown)'](self, unknown)
else:
msg = "unexpected matching %r: incompatible tokenizer"
raise RuntimeError(msg % self.next_match.group())
return self.token
|
(self, *symbols: str, message: Optional[str] = None) -> +TK_co
|
71,966 |
elementpath.tdop
|
advance_until
|
Advances until one of the symbols is found or the end of source is reached,
returning the raw source string placed before. Useful for raw parsing of
comments and references enclosed between specific symbols.
:param stop_symbols: The symbols that have to be found for stopping advance.
:return: The source string chunk enclosed between the initial position and the first stop symbol.
|
def advance_until(self, *stop_symbols: str) -> str:
"""
Advances until one of the symbols is found or the end of source is reached,
returning the raw source string placed before. Useful for raw parsing of
comments and references enclosed between specific symbols.
:param stop_symbols: The symbols that have to be found for stopping advance.
:return: The source string chunk enclosed between the initial position \
and the first stop symbol.
"""
if not stop_symbols:
raise self.next_token.wrong_type("at least a stop symbol required!")
elif self.next_token.symbol == '(end)':
raise self.next_token.wrong_syntax()
self.token = self.next_token
source_chunk: List[str] = []
while True:
try:
self.next_match = next(self.tokens)
except StopIteration:
self.next_token = self.symbol_table['(end)'](self)
break
else:
symbol = self.next_match.group(2)
if symbol is not None:
symbol = symbol.strip()
if symbol not in stop_symbols:
source_chunk.append(symbol)
else:
try:
self.next_token = self.symbol_table[symbol](self)
break
except KeyError:
self.next_token = self.symbol_table['(unknown)'](self)
raise self.next_token.wrong_syntax()
else:
source_chunk.append(self.next_match.group())
return ''.join(source_chunk)
|
(self, *stop_symbols: str) -> str
|
71,967 |
elementpath.xpath1.xpath1_parser
|
check_variables
|
Checks the sequence types of the XPath dynamic context's variables.
|
def check_variables(self, values: MutableMapping[str, Any]) -> None:
"""Checks the sequence types of the XPath dynamic context's variables."""
for varname, value in values.items():
if not match_sequence_type(
value, 'item()*' if isinstance(value, list) else 'item()', self
):
message = "Unmatched sequence type for variable {!r}".format(varname)
raise xpath_error('XPDY0050', message)
|
(self, values: MutableMapping[str, Any]) -> NoneType
|
71,968 |
elementpath.xpath1.xpath1_parser
|
expected_next
|
Checks the next token with a list of symbols. Replaces the next token with
a '(name)' token if the check fails and the next token can be a name,
otherwise raises a syntax error.
:param symbols: a sequence of symbols.
:param message: optional error message.
|
def expected_next(self, *symbols: str, message: Optional[str] = None) -> None:
"""
Checks the next token with a list of symbols. Replaces the next token with
a '(name)' token if the check fails and the next token can be a name,
otherwise raises a syntax error.
:param symbols: a sequence of symbols.
:param message: optional error message.
"""
if self.next_token.symbol in symbols:
return
elif '(name)' in symbols and \
not isinstance(self.next_token, (XPathFunction, XPathAxis)) and \
self.name_pattern.match(self.next_token.symbol) is not None:
# Disambiguation replacing the next token with a '(name)' token
self.next_token = self.symbol_table['(name)'](self, self.next_token.symbol)
else:
raise self.next_token.wrong_syntax(message)
|
(self, *symbols: str, message: Optional[str] = None) -> NoneType
|
71,969 |
elementpath.tdop
|
expression
|
Pratt's function for parsing an expression. It calls token.nud() and then advances
until the right binding power is less the left binding power of the next
token, invoking the led() method on the following token.
:param rbp: right binding power for the expression.
:return: left token.
|
def expression(self, rbp: int = 0) -> TK_co:
"""
Pratt's function for parsing an expression. It calls token.nud() and then advances
until the right binding power is less the left binding power of the next
token, invoking the led() method on the following token.
:param rbp: right binding power for the expression.
:return: left token.
"""
self.advance()
left = self.token.nud()
while rbp < self.next_token.lbp:
self.advance()
left = self.token.led(left)
return cast(TK_co, left)
|
(self, rbp: int = 0) -> +TK_co
|
71,970 |
elementpath.xpath1.xpath1_parser
|
get_function
|
Returns an XPathFunction object suitable for stand-alone usage.
:param name: the name of the function.
:param arity: the arity of the function object, must be compatible with the signature of the XPath function.
:param context: an optional context to bound to the function.
|
def get_function(self, name: str, arity: Optional[int],
context: ContextArgType = None) -> XPathFunction:
"""
Returns an XPathFunction object suitable for stand-alone usage.
:param name: the name of the function.
:param arity: the arity of the function object, must be compatible \
with the signature of the XPath function.
:param context: an optional context to bound to the function.
"""
if ':' not in name:
qname = QName(XPATH_FUNCTIONS_NAMESPACE, f'fn:{name}')
elif name.startswith('fn:'):
qname = QName(XPATH_FUNCTIONS_NAMESPACE, name)
name = name[3:]
else:
prefix, name = name.split(':')
try:
namespace = self.namespaces[prefix]
except KeyError:
raise ElementPathKeyError(f"Unknown namespace {prefix!r}") from None
else:
qname = QName(namespace, f'{prefix}:{name}')
if qname.expanded_name in self.symbol_table:
token_class = self.symbol_table[qname.expanded_name]
elif name in self.symbol_table:
token_class = self.symbol_table[name]
else:
raise ElementPathNameError(f'unknown function {name!r}')
if not issubclass(token_class, XPathFunction):
raise ElementPathNameError(f'{name!r} is not an XPath function')
if token_class.namespace != qname.namespace:
raise ElementPathNameError(f'namespace mismatch: {token_class.namespace}')
try:
func = token_class(self, nargs=arity)
except TypeError:
msg = f"unknown function {qname.qname}#{arity}"
raise xpath_error('XPST0017', msg) from None
else:
if context is not None:
func.context = context
return func
|
(self, name: str, arity: Optional[int], context: Optional[elementpath.xpath_context.XPathContext] = None) -> elementpath.xpath_tokens.XPathFunction
|
71,971 |
elementpath.tdop
|
is_line_start
|
Returns `True` if the parser is positioned at the start
of a source line, ignoring the spaces.
|
def is_line_start(self) -> bool:
"""
Returns `True` if the parser is positioned at the start
of a source line, ignoring the spaces.
"""
return self.token.is_line_start()
|
(self) -> bool
|
71,972 |
elementpath.tdop
|
is_source_start
|
Returns `True` if the parser is positioned at the start
of the source, ignoring the spaces.
|
def is_source_start(self) -> bool:
"""
Returns `True` if the parser is positioned at the start
of the source, ignoring the spaces.
"""
return self.token.is_source_start()
|
(self) -> bool
|
71,973 |
elementpath.tdop
|
is_spaced
|
Returns `True` if the source has an extra space (whitespace, tab or newline)
immediately before or after the current position of the parser.
:param before: if `True` considers also the extra spaces before the current token symbol.
:param after: if `True` considers also the extra spaces after the current token symbol.
|
def is_spaced(self, before: bool = True, after: bool = True) -> bool:
"""
Returns `True` if the source has an extra space (whitespace, tab or newline)
immediately before or after the current position of the parser.
:param before: if `True` considers also the extra spaces before \
the current token symbol.
:param after: if `True` considers also the extra spaces after \
the current token symbol.
"""
return self.token.is_spaced(before, after)
|
(self, before: bool = True, after: bool = True) -> bool
|
71,974 |
elementpath.xpath1.xpath1_parser
|
parse
| null |
def parse(self, source: str) -> XPathToken:
root_token = super(XPath1Parser, self).parse(source)
try:
root_token.evaluate() # Static context evaluation
except MissingContextError:
pass
return root_token
|
(self, source: str) -> elementpath.xpath_tokens.XPathToken
|
71,975 |
elementpath.xpath1.xpath1_parser
|
unescape
| null |
@staticmethod
def unescape(string_literal: str) -> str:
if string_literal.startswith("'"):
return string_literal[1:-1].replace("''", "'")
else:
return string_literal[1:-1].replace('""', '"')
|
(string_literal: str) -> str
|
71,976 |
elementpath.xpath1.xpath1_parser
|
xsd_qname
|
Returns a prefixed QName string for XSD namespace.
|
def xsd_qname(self, local_name: str) -> str:
"""Returns a prefixed QName string for XSD namespace."""
if self.namespaces.get('xs') == XSD_NAMESPACE:
return 'xs:%s' % local_name
for pfx, uri in self.namespaces.items():
if uri == XSD_NAMESPACE:
return '%s:%s' % (pfx, local_name) if pfx else local_name
raise xpath_error('XPST0081', 'Missing XSD namespace registration')
|
(self, local_name: str) -> str
|
71,977 |
elementpath.xpath2.xpath2_parser
|
XPath2Parser
|
XPath 2.0 expression parser class. This is the default parser used by XPath selectors.
A parser instance represents also the XPath static context. With *variable_types* you
can pass a dictionary with the types of the in-scope variables.
Provide a *namespaces* dictionary argument for mapping namespace prefixes to URI inside
expressions. If *strict* is set to `False` the parser enables also the parsing of QNames,
like the ElementPath library. There are some additional XPath 2.0 related arguments.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param variable_types: a dictionary with the static context's in-scope variable types. It defines the associations between variables and static types.
:param strict: if strict mode is `False` the parser enables parsing of QNames, like the ElementPath library. Default is `True`.
:param compatibility_mode: if set to `True` the parser instance works with XPath 1.0 compatibility rules.
:param default_namespace: the default namespace to apply to unprefixed names. For default no namespace is applied (empty namespace '').
:param function_namespace: the default namespace to apply to unprefixed function names. For default the namespace "http://www.w3.org/2005/xpath-functions" is used.
:param schema: the schema proxy class or instance to use for types, attributes and elements lookups. If an `AbstractSchemaProxy` subclass is provided then a schema proxy instance is built without the optional argument, that involves a mapping of only XSD builtin types. If it's not provided the XPath 2.0 schema's related expressions cannot be used.
:param base_uri: an absolute URI maybe provided, used when necessary in the resolution of relative URIs.
:param default_collation: the default string collation to use. If not set the environment's default locale setting is used.
:param document_types: statically known documents, that is a dictionary from absolute URIs onto types. Used for type check when calling the *fn:doc* function with a sequence of URIs. The default type of a document is 'document-node()'.
:param collection_types: statically known collections, that is a dictionary from absolute URIs onto types. Used for type check when calling the *fn:collection* function with a sequence of URIs. The default type of a collection is 'node()*'.
:param default_collection_type: this is the type of the sequence of nodes that would result from calling the *fn:collection* function with no arguments. Default is 'node()*'.
|
class XPath2Parser(XPath1Parser):
"""
XPath 2.0 expression parser class. This is the default parser used by XPath selectors.
A parser instance represents also the XPath static context. With *variable_types* you
can pass a dictionary with the types of the in-scope variables.
Provide a *namespaces* dictionary argument for mapping namespace prefixes to URI inside
expressions. If *strict* is set to `False` the parser enables also the parsing of QNames,
like the ElementPath library. There are some additional XPath 2.0 related arguments.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs.
:param variable_types: a dictionary with the static context's in-scope variable \
types. It defines the associations between variables and static types.
:param strict: if strict mode is `False` the parser enables parsing of QNames, \
like the ElementPath library. Default is `True`.
:param compatibility_mode: if set to `True` the parser instance works with \
XPath 1.0 compatibility rules.
:param default_namespace: the default namespace to apply to unprefixed names. \
For default no namespace is applied (empty namespace '').
:param function_namespace: the default namespace to apply to unprefixed function \
names. For default the namespace "http://www.w3.org/2005/xpath-functions" is used.
:param schema: the schema proxy class or instance to use for types, attributes and \
elements lookups. If an `AbstractSchemaProxy` subclass is provided then a schema \
proxy instance is built without the optional argument, that involves a mapping of \
only XSD builtin types. If it's not provided the XPath 2.0 schema's related \
expressions cannot be used.
:param base_uri: an absolute URI maybe provided, used when necessary in the \
resolution of relative URIs.
:param default_collation: the default string collation to use. If not set the \
environment's default locale setting is used.
:param document_types: statically known documents, that is a dictionary from \
absolute URIs onto types. Used for type check when calling the *fn:doc* function \
with a sequence of URIs. The default type of a document is 'document-node()'.
:param collection_types: statically known collections, that is a dictionary from \
absolute URIs onto types. Used for type check when calling the *fn:collection* \
function with a sequence of URIs. The default type of a collection is 'node()*'.
:param default_collection_type: this is the type of the sequence of nodes that \
would result from calling the *fn:collection* function with no arguments. \
Default is 'node()*'.
"""
version = '2.0'
default_collation = UNICODE_CODEPOINT_COLLATION
DEFAULT_NAMESPACES: ClassVar[Dict[str, str]] = {
'xml': XML_NAMESPACE,
'xs': XSD_NAMESPACE,
'fn': XPATH_FUNCTIONS_NAMESPACE,
'err': XQT_ERRORS_NAMESPACE
}
PATH_STEP_LABELS = ('axis', 'function', 'kind test')
PATH_STEP_SYMBOLS = {
'(integer)', '(string)', '(float)', '(decimal)', '(name)', '*', '@', '..', '.', '(', '{'
}
# https://www.w3.org/TR/xpath20/#id-reserved-fn-names
RESERVED_FUNCTION_NAMES = {
'attribute', 'comment', 'document-node', 'element', 'empty-sequence',
'if', 'item', 'node', 'processing-instruction', 'schema-attribute',
'schema-element', 'text', 'typeswitch',
}
function_signatures: Dict[Tuple[QName, int], str] = XPath1Parser.function_signatures.copy()
namespaces: Dict[str, str]
token: XPathToken
next_token: XPathToken
@staticmethod
def tracer(trace_data: str) -> None:
"""Trace data collector"""
def __init__(self, namespaces: Optional[NamespacesType] = None,
strict: bool = True,
compatibility_mode: bool = False,
default_collation: Optional[str] = None,
default_namespace: Optional[str] = None,
function_namespace: Optional[str] = None,
xsd_version: Optional[str] = None,
schema: Optional[AbstractSchemaProxy] = None,
base_uri: Optional[str] = None,
variable_types: Optional[Dict[str, str]] = None,
document_types: Optional[Dict[str, str]] = None,
collection_types: Optional[Dict[str, str]] = None,
default_collection_type: str = 'node()*') -> None:
super(XPath2Parser, self).__init__(namespaces, strict)
self.compatibility_mode = compatibility_mode
if default_collation is not None:
self.default_collation = default_collation
else:
# Obtain the current collation locale using setlocale() with `None`.
# Consider only configured UTF-8 encodings, otherwise keep Unicode
# Codepoint Collation.
_locale = locale.setlocale(locale.LC_COLLATE, None)
if '.' in _locale:
language_code, encoding = _locale.split('.')
if encoding.lower() == 'utf-8':
self.default_collation = f'{UNICODE_COLLATION_BASE_URI}?lang={language_code}'
self._xsd_version = xsd_version if xsd_version is not None else '1.0'
if default_namespace is not None:
self.default_namespace = self.namespaces[''] = default_namespace
else:
self.default_namespace = self.namespaces.get('', '')
if function_namespace is not None:
self.function_namespace = function_namespace
if schema is None:
pass
elif not isinstance(schema, AbstractSchemaProxy):
msg = "argument 'schema' must be an instance of AbstractSchemaProxy"
raise ElementPathTypeError(msg)
else:
schema.bind_parser(self)
if not variable_types:
self.variable_types = {}
elif all(is_sequence_type(v, self) for v in variable_types.values()):
self.variable_types = variable_types.copy()
else:
raise ElementPathValueError('invalid sequence type for in-scope variable types')
self.base_uri = None if base_uri is None else urlparse(base_uri).geturl()
if document_types:
if any(not is_sequence_type(v, self) for v in document_types.values()):
raise ElementPathValueError('invalid sequence type in document_types argument')
self.document_types = document_types
if collection_types:
if any(not is_sequence_type(v, self) for v in collection_types.values()):
raise ElementPathValueError('invalid sequence type in collection_types argument')
self.collection_types = collection_types
if not is_sequence_type(default_collection_type, self):
raise ElementPathValueError('invalid sequence type for '
'default_collection_type argument')
self.default_collection_type = default_collection_type
def __str__(self) -> str:
args = []
if self.compatibility_mode:
args.append('compatibility_mode=True')
if self.default_collation != UNICODE_CODEPOINT_COLLATION:
args.append(f'default_collation={self.default_collation!r}')
if self.function_namespace != XPATH_FUNCTIONS_NAMESPACE:
args.append(f'function_namespace={self.function_namespace!r}')
if self._xsd_version != '1.0':
args.append(f'xsd_version={self._xsd_version!r}')
if self.schema is not None:
args.append(f'schema={self.schema!r}')
if self.base_uri is not None:
args.append(f'base_uri={self.base_uri!r}')
if self.variable_types:
args.append(f'variable_types={self.variable_types!r}')
if self.document_types:
args.append(f'document_types={self.document_types!r}')
if self.collection_types:
args.append(f'collection_types={self.collection_types!r}')
if self.default_collection_type != 'node()*':
args.append(f'default_collection_type={self.default_collection_type!r}')
if not args:
return super().__str__()
repr_string = super().__str__()[:-1]
if repr_string.endswith('('):
return f"{repr_string}{', '.join(args)})"
return f"{repr_string}, {', '.join(args)})"
def __getstate__(self) -> Dict[str, Any]:
state = self.__dict__.copy()
state.pop('symbol_table', None)
state.pop('tokenizer', None)
return state
@property
def xsd_version(self) -> str:
if self.schema is None:
return self._xsd_version
try:
return self.schema.xsd_version
except (AttributeError, NotImplementedError):
return self._xsd_version
def advance(self, *symbols: str, message: Optional[str] = None) -> XPathToken:
super(XPath2Parser, self).advance(*symbols, message=message)
if self.next_token.symbol == '(:':
# Parses and consumes an XPath 2.0 comment. A comment is delimited
# by symbols '(:' and ':)' and can be nested. The current token is
# saved and restored after parsing the entire comment. Comments
# cannot be inside a prefixed name ':' specification.
self.token.unexpected(':')
token = self.token
comment_level = 1
while comment_level:
self.advance_until('(:', ':)')
if self.next_token.symbol == ':)':
comment_level -= 1
else:
comment_level += 1
self.advance(':)')
self.next_token.unexpected(':')
self.token = token
return self.token
@classmethod
def constructor(cls, symbol: str, bp: int = 90, nargs: NargsType = 1,
sequence_types: Union[Tuple[()], Tuple[str, ...], List[str]] = (),
label: Union[str, Tuple[str, ...]] = 'constructor function') \
-> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""Creates a constructor token class."""
def nud_(self: XPathConstructor) -> XPathConstructor:
try:
self.parser.advance('(')
self[0:] = self.parser.expression(5),
if self.parser.next_token.symbol == ',':
msg = 'Too many arguments: expected at most 1 argument'
raise self.error('XPST0017', msg)
self.parser.advance(')')
self.value = None
except SyntaxError:
raise self.error('XPST0017') from None
if self[0].symbol == '?':
self.to_partial_function()
return self
def evaluate_(self: XPathConstructor, context: Optional[XPathContext] = None) \
-> Union[List[None], AtomicValueType]:
if self.context is not None:
context = self.context
arg = self.data_value(self.get_argument(context))
if arg is None:
return []
elif arg == '?' and self[0].symbol == '?':
raise self.error('XPTY0004', "cannot evaluate a partial function")
try:
if isinstance(arg, UntypedAtomic):
return self.cast(arg.value)
return self.cast(arg)
except ElementPathError:
raise
except (TypeError, ValueError) as err:
if isinstance(context, XPathSchemaContext):
return []
raise self.error('FORG0001', err) from None
if not sequence_types:
assert nargs == 1
sequence_types = ('xs:anyAtomicType?', 'xs:%s?' % symbol)
token_class = cls.register(symbol, nargs=nargs, sequence_types=sequence_types,
label=label, bases=(XPathConstructor,), lbp=bp, rbp=bp,
nud=nud_, evaluate=evaluate_)
def bind(func: Callable[..., Any]) -> Callable[..., Any]:
method_name = func.__name__.partition('_')[0]
if method_name != 'cast':
raise ValueError("The function name must be 'cast' or starts with 'cast_'")
setattr(token_class, method_name, func)
return func
return bind
def schema_constructor(self, atomic_type_name: str, bp: int = 90) \
-> Type[XPathFunction]:
"""Registers a token class for a schema atomic type constructor function."""
if atomic_type_name in (XSD_ANY_ATOMIC_TYPE, XSD_NOTATION):
raise xpath_error('XPST0080')
def nud_(self_: XPathFunction) -> XPathFunction:
self_.parser.advance('(')
self_[0:] = self_.parser.expression(5),
self_.parser.advance(')')
try:
self_.value = self_.evaluate() # Static context evaluation
except MissingContextError:
self_.value = None
return self_
def evaluate_(self_: XPathFunction, context: Optional[XPathContext] = None) \
-> Union[List[None], AtomicValueType]:
arg = self_.get_argument(context)
if arg is None or self_.parser.schema is None:
return []
value = self_.string_value(arg)
try:
return self_.parser.schema.cast_as(value, atomic_type_name)
except (TypeError, ValueError) as err:
if isinstance(context, XPathSchemaContext):
return []
raise self_.error('FORG0001', err)
symbol = get_prefixed_name(atomic_type_name, self.namespaces)
token_class_name = "_%sConstructorFunction" % symbol.replace(':', '_')
kwargs = {
'symbol': symbol,
'nargs': 1,
'label': 'constructor function',
'pattern': r'\b%s(?=\s*\(|\s*\(\:.*\:\)\()' % symbol,
'lbp': bp,
'rbp': bp,
'nud': nud_,
'evaluate': evaluate_,
'__module__': self.__module__,
'__qualname__': token_class_name,
'__return__': None
}
token_class = cast(
Type[XPathFunction], ABCMeta(token_class_name, (XPathFunction,), kwargs)
)
MutableSequence.register(token_class)
if self.symbol_table is self.__class__.symbol_table:
self.symbol_table = dict(self.__class__.symbol_table)
self.symbol_table[symbol] = token_class
self.tokenizer = None
return token_class
def external_function(self,
callback: Callable[..., Any],
name: Optional[str] = None,
prefix: Optional[str] = None,
sequence_types: Tuple[str, ...] = (),
bp: int = 90) -> Type[XPathFunction]:
"""Registers a token class for an external function."""
import inspect
symbol = name or callback.__name__
if not is_ncname(symbol):
raise ElementPathValueError(f'{symbol!r} is not a name')
elif symbol in self.RESERVED_FUNCTION_NAMES:
raise ElementPathValueError(f'{symbol!r} is a reserved function name')
nargs: NargsType
spec = inspect.getfullargspec(callback)
if spec.varargs is not None:
if spec.args:
nargs = len(spec.args), None
else:
nargs = None
elif spec.defaults is None:
nargs = len(spec.args)
else:
nargs = len(spec.args) - len(spec.defaults), len(spec.args)
if prefix:
namespace = self.namespaces[prefix]
qname = QName(namespace, f'{prefix}:{symbol}')
else:
namespace = XPATH_FUNCTIONS_NAMESPACE
qname = QName(XPATH_FUNCTIONS_NAMESPACE, f'fn:{symbol}')
class_name = f'{upper_camel_case(qname.qname)}ExternalFunction'
lookup_name = qname.expanded_name
if self.symbol_table is self.__class__.symbol_table:
self.symbol_table = dict(self.__class__.symbol_table)
if lookup_name in self.symbol_table:
msg = f'function {qname.qname!r} is already registered'
raise ElementPathValueError(msg)
elif symbol not in self.symbol_table or \
not issubclass(self.symbol_table[symbol], ProxyToken):
if symbol in self.symbol_table:
token_cls = self.symbol_table[symbol]
if not issubclass(token_cls, XPathFunction) \
or token_cls.label == 'kind test':
msg = f'{symbol!r} name collides with {token_cls!r}'
raise ElementPathValueError(msg)
if namespace == token_cls.namespace:
msg = f'function {qname.qname!r} is already registered'
raise ElementPathValueError(msg)
# Copy the token class before register the proxy token
self.symbol_table[f'{{{token_cls.namespace}}}{symbol}'] = token_cls
proxy_class_name = f'{upper_camel_case(qname.local_name)}ProxyToken'
kwargs = {
'class_name': proxy_class_name,
'symbol': symbol,
'lbp': bp,
'rbp': bp,
'__module__': self.__module__,
'__qualname__': proxy_class_name,
'__return__': None
}
proxy_class = cast(
Type[ProxyToken], ABCMeta(class_name, (ProxyToken,), kwargs)
)
MutableSequence.register(proxy_class)
self.symbol_table[symbol] = proxy_class
def evaluate_external_function(self_: XPathFunction,
context: Optional[XPathContext] = None) -> Any:
args = []
for k in range(len(self_)):
arg = self_.get_argument(context, index=k)
args.append(arg)
if sequence_types:
for k, (arg, st) in enumerate(zip(args, sequence_types), start=1):
if not match_sequence_type(arg, st, self):
msg_ = f"{ordinal(k)} argument does not match sequence type {st!r}"
raise xpath_error('XPDY0050', msg_)
result = callback(*args)
if not match_sequence_type(result, sequence_types[-1], self):
msg_ = f"Result does not match sequence type {sequence_types[-1]!r}"
raise xpath_error('XPDY0050', msg_)
return result
return callback(*args)
kwargs = {
'class_name': class_name,
'symbol': symbol,
'namespace': namespace,
'label': 'external function',
'nargs': nargs,
'lbp': bp,
'rbp': bp,
'evaluate': evaluate_external_function,
'__module__': self.__module__,
'__qualname__': class_name,
'__return__': None
}
if sequence_types:
# Register function signature(s)
kwargs['sequence_types'] = sequence_types
if self.function_signatures is self.__class__.function_signatures:
self.function_signatures = dict(self.__class__.function_signatures)
if nargs is None:
pass # pragma: no cover
elif isinstance(nargs, int):
assert len(sequence_types) == nargs + 1
self.function_signatures[(qname, nargs)] = 'function({}) as {}'.format(
', '.join(sequence_types[:-1]), sequence_types[-1]
)
elif nargs[1] is None:
assert len(sequence_types) == nargs[0] + 1
self.function_signatures[(qname, nargs[0])] = 'function({}, ...) as {}'.format(
', '.join(sequence_types[:-1]), sequence_types[-1]
)
else:
assert len(sequence_types) == nargs[1] + 1
for arity in range(nargs[0], nargs[1] + 1):
self.function_signatures[(qname, arity)] = 'function({}) as {}'.format(
', '.join(sequence_types[:arity]), sequence_types[-1]
)
token_class = cast(
Type[XPathFunction], ABCMeta(class_name, (XPathFunction,), kwargs)
)
MutableSequence.register(token_class)
self.symbol_table[lookup_name] = token_class
self.tokenizer = None
return token_class
def is_schema_bound(self) -> bool:
return self.schema is not None and 'symbol_table' in self.__dict__
def parse(self, source: str) -> XPathToken:
if self.tokenizer is None:
self.tokenizer = self.create_tokenizer(self.symbol_table)
root_token = super(XPath1Parser, self).parse(source)
if root_token.label in ('sequence type', 'function test'):
raise root_token.error('XPST0003', "not allowed in XPath expression")
try:
root_token.evaluate() # Static context evaluation
except MissingContextError:
pass
if self.schema is not None:
# Tokens tree labeling with XSD types using a dynamic schema context
context = self.schema.get_context()
for _ in root_token.select(context):
pass
return root_token
def check_variables(self, values: MutableMapping[str, Any]) -> None:
if self.variable_types is None:
return
for varname, xsd_type in self.variable_types.items():
if varname not in values:
raise xpath_error('XPST0008', "missing variable {!r}".format(varname))
for varname, value in values.items():
try:
sequence_type = self.variable_types[varname]
except KeyError:
sequence_type = 'item()*' if isinstance(value, list) else 'item()'
if not match_sequence_type(value, sequence_type, self):
message = "Unmatched sequence type for variable {!r}".format(varname)
raise xpath_error('XPDY0050', message)
|
(namespaces: Dict[str, str] = None, strict: bool = True, compatibility_mode: bool = False, default_collation: Optional[str] = None, default_namespace: Optional[str] = None, function_namespace: Optional[str] = None, xsd_version: Optional[str] = None, schema: Optional[elementpath.schema_proxy.AbstractSchemaProxy] = None, base_uri: Optional[str] = None, variable_types: Optional[Dict[str, str]] = None, document_types: Optional[Dict[str, str]] = None, collection_types: Optional[Dict[str, str]] = None, default_collection_type: str = 'node()*') -> None
|
71,979 |
elementpath.xpath2.xpath2_parser
|
__getstate__
| null |
def __getstate__(self) -> Dict[str, Any]:
state = self.__dict__.copy()
state.pop('symbol_table', None)
state.pop('tokenizer', None)
return state
|
(self) -> Dict[str, Any]
|
71,980 |
elementpath.xpath2.xpath2_parser
|
__init__
| null |
def __init__(self, namespaces: Optional[NamespacesType] = None,
strict: bool = True,
compatibility_mode: bool = False,
default_collation: Optional[str] = None,
default_namespace: Optional[str] = None,
function_namespace: Optional[str] = None,
xsd_version: Optional[str] = None,
schema: Optional[AbstractSchemaProxy] = None,
base_uri: Optional[str] = None,
variable_types: Optional[Dict[str, str]] = None,
document_types: Optional[Dict[str, str]] = None,
collection_types: Optional[Dict[str, str]] = None,
default_collection_type: str = 'node()*') -> None:
super(XPath2Parser, self).__init__(namespaces, strict)
self.compatibility_mode = compatibility_mode
if default_collation is not None:
self.default_collation = default_collation
else:
# Obtain the current collation locale using setlocale() with `None`.
# Consider only configured UTF-8 encodings, otherwise keep Unicode
# Codepoint Collation.
_locale = locale.setlocale(locale.LC_COLLATE, None)
if '.' in _locale:
language_code, encoding = _locale.split('.')
if encoding.lower() == 'utf-8':
self.default_collation = f'{UNICODE_COLLATION_BASE_URI}?lang={language_code}'
self._xsd_version = xsd_version if xsd_version is not None else '1.0'
if default_namespace is not None:
self.default_namespace = self.namespaces[''] = default_namespace
else:
self.default_namespace = self.namespaces.get('', '')
if function_namespace is not None:
self.function_namespace = function_namespace
if schema is None:
pass
elif not isinstance(schema, AbstractSchemaProxy):
msg = "argument 'schema' must be an instance of AbstractSchemaProxy"
raise ElementPathTypeError(msg)
else:
schema.bind_parser(self)
if not variable_types:
self.variable_types = {}
elif all(is_sequence_type(v, self) for v in variable_types.values()):
self.variable_types = variable_types.copy()
else:
raise ElementPathValueError('invalid sequence type for in-scope variable types')
self.base_uri = None if base_uri is None else urlparse(base_uri).geturl()
if document_types:
if any(not is_sequence_type(v, self) for v in document_types.values()):
raise ElementPathValueError('invalid sequence type in document_types argument')
self.document_types = document_types
if collection_types:
if any(not is_sequence_type(v, self) for v in collection_types.values()):
raise ElementPathValueError('invalid sequence type in collection_types argument')
self.collection_types = collection_types
if not is_sequence_type(default_collection_type, self):
raise ElementPathValueError('invalid sequence type for '
'default_collection_type argument')
self.default_collection_type = default_collection_type
|
(self, namespaces: Optional[MutableMapping[str, str]] = None, strict: bool = True, compatibility_mode: bool = False, default_collation: Optional[str] = None, default_namespace: Optional[str] = None, function_namespace: Optional[str] = None, xsd_version: Optional[str] = None, schema: Optional[elementpath.schema_proxy.AbstractSchemaProxy] = None, base_uri: Optional[str] = None, variable_types: Optional[Dict[str, str]] = None, document_types: Optional[Dict[str, str]] = None, collection_types: Optional[Dict[str, str]] = None, default_collection_type: str = 'node()*') -> NoneType
|
71,982 |
elementpath.xpath2.xpath2_parser
|
__str__
| null |
def __str__(self) -> str:
args = []
if self.compatibility_mode:
args.append('compatibility_mode=True')
if self.default_collation != UNICODE_CODEPOINT_COLLATION:
args.append(f'default_collation={self.default_collation!r}')
if self.function_namespace != XPATH_FUNCTIONS_NAMESPACE:
args.append(f'function_namespace={self.function_namespace!r}')
if self._xsd_version != '1.0':
args.append(f'xsd_version={self._xsd_version!r}')
if self.schema is not None:
args.append(f'schema={self.schema!r}')
if self.base_uri is not None:
args.append(f'base_uri={self.base_uri!r}')
if self.variable_types:
args.append(f'variable_types={self.variable_types!r}')
if self.document_types:
args.append(f'document_types={self.document_types!r}')
if self.collection_types:
args.append(f'collection_types={self.collection_types!r}')
if self.default_collection_type != 'node()*':
args.append(f'default_collection_type={self.default_collection_type!r}')
if not args:
return super().__str__()
repr_string = super().__str__()[:-1]
if repr_string.endswith('('):
return f"{repr_string}{', '.join(args)})"
return f"{repr_string}, {', '.join(args)})"
|
(self) -> str
|
71,983 |
elementpath.xpath2.xpath2_parser
|
advance
| null |
def advance(self, *symbols: str, message: Optional[str] = None) -> XPathToken:
super(XPath2Parser, self).advance(*symbols, message=message)
if self.next_token.symbol == '(:':
# Parses and consumes an XPath 2.0 comment. A comment is delimited
# by symbols '(:' and ':)' and can be nested. The current token is
# saved and restored after parsing the entire comment. Comments
# cannot be inside a prefixed name ':' specification.
self.token.unexpected(':')
token = self.token
comment_level = 1
while comment_level:
self.advance_until('(:', ':)')
if self.next_token.symbol == ':)':
comment_level -= 1
else:
comment_level += 1
self.advance(':)')
self.next_token.unexpected(':')
self.token = token
return self.token
|
(self, *symbols: str, message: Optional[str] = None) -> elementpath.xpath_tokens.XPathToken
|
71,985 |
elementpath.xpath2.xpath2_parser
|
check_variables
| null |
def check_variables(self, values: MutableMapping[str, Any]) -> None:
if self.variable_types is None:
return
for varname, xsd_type in self.variable_types.items():
if varname not in values:
raise xpath_error('XPST0008', "missing variable {!r}".format(varname))
for varname, value in values.items():
try:
sequence_type = self.variable_types[varname]
except KeyError:
sequence_type = 'item()*' if isinstance(value, list) else 'item()'
if not match_sequence_type(value, sequence_type, self):
message = "Unmatched sequence type for variable {!r}".format(varname)
raise xpath_error('XPDY0050', message)
|
(self, values: MutableMapping[str, Any]) -> NoneType
|
71,988 |
elementpath.xpath2.xpath2_parser
|
external_function
|
Registers a token class for an external function.
|
def external_function(self,
callback: Callable[..., Any],
name: Optional[str] = None,
prefix: Optional[str] = None,
sequence_types: Tuple[str, ...] = (),
bp: int = 90) -> Type[XPathFunction]:
"""Registers a token class for an external function."""
import inspect
symbol = name or callback.__name__
if not is_ncname(symbol):
raise ElementPathValueError(f'{symbol!r} is not a name')
elif symbol in self.RESERVED_FUNCTION_NAMES:
raise ElementPathValueError(f'{symbol!r} is a reserved function name')
nargs: NargsType
spec = inspect.getfullargspec(callback)
if spec.varargs is not None:
if spec.args:
nargs = len(spec.args), None
else:
nargs = None
elif spec.defaults is None:
nargs = len(spec.args)
else:
nargs = len(spec.args) - len(spec.defaults), len(spec.args)
if prefix:
namespace = self.namespaces[prefix]
qname = QName(namespace, f'{prefix}:{symbol}')
else:
namespace = XPATH_FUNCTIONS_NAMESPACE
qname = QName(XPATH_FUNCTIONS_NAMESPACE, f'fn:{symbol}')
class_name = f'{upper_camel_case(qname.qname)}ExternalFunction'
lookup_name = qname.expanded_name
if self.symbol_table is self.__class__.symbol_table:
self.symbol_table = dict(self.__class__.symbol_table)
if lookup_name in self.symbol_table:
msg = f'function {qname.qname!r} is already registered'
raise ElementPathValueError(msg)
elif symbol not in self.symbol_table or \
not issubclass(self.symbol_table[symbol], ProxyToken):
if symbol in self.symbol_table:
token_cls = self.symbol_table[symbol]
if not issubclass(token_cls, XPathFunction) \
or token_cls.label == 'kind test':
msg = f'{symbol!r} name collides with {token_cls!r}'
raise ElementPathValueError(msg)
if namespace == token_cls.namespace:
msg = f'function {qname.qname!r} is already registered'
raise ElementPathValueError(msg)
# Copy the token class before register the proxy token
self.symbol_table[f'{{{token_cls.namespace}}}{symbol}'] = token_cls
proxy_class_name = f'{upper_camel_case(qname.local_name)}ProxyToken'
kwargs = {
'class_name': proxy_class_name,
'symbol': symbol,
'lbp': bp,
'rbp': bp,
'__module__': self.__module__,
'__qualname__': proxy_class_name,
'__return__': None
}
proxy_class = cast(
Type[ProxyToken], ABCMeta(class_name, (ProxyToken,), kwargs)
)
MutableSequence.register(proxy_class)
self.symbol_table[symbol] = proxy_class
def evaluate_external_function(self_: XPathFunction,
context: Optional[XPathContext] = None) -> Any:
args = []
for k in range(len(self_)):
arg = self_.get_argument(context, index=k)
args.append(arg)
if sequence_types:
for k, (arg, st) in enumerate(zip(args, sequence_types), start=1):
if not match_sequence_type(arg, st, self):
msg_ = f"{ordinal(k)} argument does not match sequence type {st!r}"
raise xpath_error('XPDY0050', msg_)
result = callback(*args)
if not match_sequence_type(result, sequence_types[-1], self):
msg_ = f"Result does not match sequence type {sequence_types[-1]!r}"
raise xpath_error('XPDY0050', msg_)
return result
return callback(*args)
kwargs = {
'class_name': class_name,
'symbol': symbol,
'namespace': namespace,
'label': 'external function',
'nargs': nargs,
'lbp': bp,
'rbp': bp,
'evaluate': evaluate_external_function,
'__module__': self.__module__,
'__qualname__': class_name,
'__return__': None
}
if sequence_types:
# Register function signature(s)
kwargs['sequence_types'] = sequence_types
if self.function_signatures is self.__class__.function_signatures:
self.function_signatures = dict(self.__class__.function_signatures)
if nargs is None:
pass # pragma: no cover
elif isinstance(nargs, int):
assert len(sequence_types) == nargs + 1
self.function_signatures[(qname, nargs)] = 'function({}) as {}'.format(
', '.join(sequence_types[:-1]), sequence_types[-1]
)
elif nargs[1] is None:
assert len(sequence_types) == nargs[0] + 1
self.function_signatures[(qname, nargs[0])] = 'function({}, ...) as {}'.format(
', '.join(sequence_types[:-1]), sequence_types[-1]
)
else:
assert len(sequence_types) == nargs[1] + 1
for arity in range(nargs[0], nargs[1] + 1):
self.function_signatures[(qname, arity)] = 'function({}) as {}'.format(
', '.join(sequence_types[:arity]), sequence_types[-1]
)
token_class = cast(
Type[XPathFunction], ABCMeta(class_name, (XPathFunction,), kwargs)
)
MutableSequence.register(token_class)
self.symbol_table[lookup_name] = token_class
self.tokenizer = None
return token_class
|
(self, callback: Callable[..., Any], name: Optional[str] = None, prefix: Optional[str] = None, sequence_types: Tuple[str, ...] = (), bp: int = 90) -> Type[elementpath.xpath_tokens.XPathFunction]
|
71,991 |
elementpath.xpath2.xpath2_parser
|
is_schema_bound
| null |
def is_schema_bound(self) -> bool:
return self.schema is not None and 'symbol_table' in self.__dict__
|
(self) -> bool
|
71,994 |
elementpath.xpath2.xpath2_parser
|
parse
| null |
def parse(self, source: str) -> XPathToken:
if self.tokenizer is None:
self.tokenizer = self.create_tokenizer(self.symbol_table)
root_token = super(XPath1Parser, self).parse(source)
if root_token.label in ('sequence type', 'function test'):
raise root_token.error('XPST0003', "not allowed in XPath expression")
try:
root_token.evaluate() # Static context evaluation
except MissingContextError:
pass
if self.schema is not None:
# Tokens tree labeling with XSD types using a dynamic schema context
context = self.schema.get_context()
for _ in root_token.select(context):
pass
return root_token
|
(self, source: str) -> elementpath.xpath_tokens.XPathToken
|
71,995 |
elementpath.xpath2.xpath2_parser
|
schema_constructor
|
Registers a token class for a schema atomic type constructor function.
|
def schema_constructor(self, atomic_type_name: str, bp: int = 90) \
-> Type[XPathFunction]:
"""Registers a token class for a schema atomic type constructor function."""
if atomic_type_name in (XSD_ANY_ATOMIC_TYPE, XSD_NOTATION):
raise xpath_error('XPST0080')
def nud_(self_: XPathFunction) -> XPathFunction:
self_.parser.advance('(')
self_[0:] = self_.parser.expression(5),
self_.parser.advance(')')
try:
self_.value = self_.evaluate() # Static context evaluation
except MissingContextError:
self_.value = None
return self_
def evaluate_(self_: XPathFunction, context: Optional[XPathContext] = None) \
-> Union[List[None], AtomicValueType]:
arg = self_.get_argument(context)
if arg is None or self_.parser.schema is None:
return []
value = self_.string_value(arg)
try:
return self_.parser.schema.cast_as(value, atomic_type_name)
except (TypeError, ValueError) as err:
if isinstance(context, XPathSchemaContext):
return []
raise self_.error('FORG0001', err)
symbol = get_prefixed_name(atomic_type_name, self.namespaces)
token_class_name = "_%sConstructorFunction" % symbol.replace(':', '_')
kwargs = {
'symbol': symbol,
'nargs': 1,
'label': 'constructor function',
'pattern': r'\b%s(?=\s*\(|\s*\(\:.*\:\)\()' % symbol,
'lbp': bp,
'rbp': bp,
'nud': nud_,
'evaluate': evaluate_,
'__module__': self.__module__,
'__qualname__': token_class_name,
'__return__': None
}
token_class = cast(
Type[XPathFunction], ABCMeta(token_class_name, (XPathFunction,), kwargs)
)
MutableSequence.register(token_class)
if self.symbol_table is self.__class__.symbol_table:
self.symbol_table = dict(self.__class__.symbol_table)
self.symbol_table[symbol] = token_class
self.tokenizer = None
return token_class
|
(self, atomic_type_name: str, bp: int = 90) -> Type[elementpath.xpath_tokens.XPathFunction]
|
71,996 |
elementpath.xpath2.xpath2_parser
|
tracer
|
Trace data collector
|
@staticmethod
def tracer(trace_data: str) -> None:
"""Trace data collector"""
|
(trace_data: str) -> NoneType
|
71,999 |
elementpath.xpath_context
|
XPathContext
|
The XPath dynamic context. The static context is provided by the parser.
Usually the dynamic context instances are created providing only the root element.
Variable values argument is needed if the XPath expression refers to in-scope variables.
The other optional arguments are needed only if a specific position on the context is
required, but have to be used with the knowledge of what is their meaning.
:param root: the root of the XML document, usually an ElementTree instance or an Element. A schema or a schema element can also be provided, or an already built node tree. For default is `None`, in which case no XML root is set, and you have to provide an *item* argument.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs, used when namespace information is not available within document and element nodes. This can be useful when the dynamic context has additional namespaces and root is an Element or an ElementTree instance of the standard library.
:param uri: an optional URI associated with the root element or the document.
:param fragment: if `True` a root element is considered a fragment, otherwise a root element is considered the root of an XML document, and a dummy document is created for selection. In this case the dummy document value is not included in the results.
:param item: the context item. A `None` value means that the context is positioned on the document node.
:param position: the current position of the node within the input sequence.
:param size: the number of items in the input sequence.
:param axis: the active axis. Used to choose when apply the default axis ('child' axis).
:param variables: dictionary of context variables that maps a QName to a value.
:param current_dt: current dateTime of the implementation, including explicit timezone.
:param timezone: implicit timezone to be used when a date, time, or dateTime value does not have a timezone.
:param documents: available documents. This is a mapping of absolute URI strings into document nodes. Used by the function fn:doc.
:param collections: available collections. This is a mapping of absolute URI strings onto sequences of nodes. Used by the XPath 2.0+ function fn:collection.
:param default_collection: this is the sequence of nodes used when fn:collection is called with no arguments.
:param text_resources: available text resources. This is a mapping of absolute URI strings onto text resources. Used by XPath 3.0+ function fn:unparsed-text/fn:unparsed-text-lines.
:param resource_collections: available URI collections. This is a mapping of absolute URI strings to sequence of URIs. Used by the XPath 3.0+ function fn:uri-collection.
:param default_resource_collection: this is the sequence of URIs used when fn:uri-collection is called with no arguments.
:param allow_environment: defines if the access to system environment is allowed, for default is `False`. Used by the XPath 3.0+ functions fn:environment-variable and fn:available-environment-variables.
|
class XPathContext:
"""
The XPath dynamic context. The static context is provided by the parser.
Usually the dynamic context instances are created providing only the root element.
Variable values argument is needed if the XPath expression refers to in-scope variables.
The other optional arguments are needed only if a specific position on the context is
required, but have to be used with the knowledge of what is their meaning.
:param root: the root of the XML document, usually an ElementTree instance or an \
Element. A schema or a schema element can also be provided, or an already built \
node tree. For default is `None`, in which case no XML root is set, and you have \
to provide an *item* argument.
:param namespaces: a dictionary with mapping from namespace prefixes into URIs, \
used when namespace information is not available within document and element nodes. \
This can be useful when the dynamic context has additional namespaces and root \
is an Element or an ElementTree instance of the standard library.
:param uri: an optional URI associated with the root element or the document.
:param fragment: if `True` a root element is considered a fragment, otherwise \
a root element is considered the root of an XML document, and a dummy document \
is created for selection. In this case the dummy document value is not included \
in the results.
:param item: the context item. A `None` value means that the context is positioned on \
the document node.
:param position: the current position of the node within the input sequence.
:param size: the number of items in the input sequence.
:param axis: the active axis. Used to choose when apply the default axis ('child' axis).
:param variables: dictionary of context variables that maps a QName to a value.
:param current_dt: current dateTime of the implementation, including explicit timezone.
:param timezone: implicit timezone to be used when a date, time, or dateTime value does \
not have a timezone.
:param documents: available documents. This is a mapping of absolute URI \
strings into document nodes. Used by the function fn:doc.
:param collections: available collections. This is a mapping of absolute URI \
strings onto sequences of nodes. Used by the XPath 2.0+ function fn:collection.
:param default_collection: this is the sequence of nodes used when fn:collection \
is called with no arguments.
:param text_resources: available text resources. This is a mapping of absolute URI strings \
onto text resources. Used by XPath 3.0+ function fn:unparsed-text/fn:unparsed-text-lines.
:param resource_collections: available URI collections. This is a mapping of absolute \
URI strings to sequence of URIs. Used by the XPath 3.0+ function fn:uri-collection.
:param default_resource_collection: this is the sequence of URIs used when \
fn:uri-collection is called with no arguments.
:param allow_environment: defines if the access to system environment is allowed, \
for default is `False`. Used by the XPath 3.0+ functions fn:environment-variable \
and fn:available-environment-variables.
"""
_etree: Optional[ModuleType] = None
root: Union[DocumentNode, ElementNode, None] = None
document: Optional[DocumentNode] = None
item: Optional[ItemType]
total_nodes: int = 0 # Number of nodes associated to the context
variables: Dict[str, Union[ItemType, List[ItemType]]]
documents: Optional[Dict[str, Union[DocumentNode, ElementNode, None]]] = None
collections = None
default_collection = None
def __init__(self,
root: Optional[RootArgType] = None,
namespaces: Optional[NamespacesType] = None,
uri: Optional[str] = None,
fragment: bool = False,
item: Optional[ItemArgType] = None,
position: int = 1,
size: int = 1,
axis: Optional[str] = None,
variables: Optional[Dict[str, CollectionArgType]] = None,
current_dt: Optional[datetime.datetime] = None,
timezone: Optional[Union[str, Timezone]] = None,
documents: Optional[Dict[str, Optional[RootArgType]]] = None,
collections: Optional[Dict[str, CollectionArgType]] = None,
default_collection: CollectionArgType = None,
text_resources: Optional[Dict[str, str]] = None,
resource_collections: Optional[Dict[str, List[str]]] = None,
default_resource_collection: Optional[str] = None,
allow_environment: bool = False,
default_language: Optional[str] = None,
default_calendar: Optional[str] = None,
default_place: Optional[str] = None) -> None:
if namespaces:
self.namespaces = {k: v for k, v in namespaces.items()}
else:
self.namespaces = {}
if root is not None:
self.root = get_node_tree(root, self.namespaces, uri, fragment)
if item is not None:
self.item = self.get_context_item(item, self.namespaces)
else:
self.item = self.root
elif item is not None:
self.item = self.get_context_item(item, self.namespaces, uri, fragment)
else:
raise ElementPathTypeError("Missing both the root node and the context item!")
if isinstance(self.root, DocumentNode):
self.document = self.root
elif fragment or isinstance(self.root, SchemaElementNode):
pass
elif isinstance(self.root, ElementNode):
# Creates a dummy document
document = cast(DocumentProtocol, self.etree.ElementTree(self.root.elem))
self.document = DocumentNode(document, self.root.uri, position=0)
self.document.children.append(self.root)
self.document.elements = cast(Dict[ElementProtocol, ElementNode], self.root.elements)
# self.root.parent = self.document TODO for v5? It's necessary?
self.position = position
self.size = size
self.axis = axis
if timezone is None or isinstance(timezone, Timezone):
self.timezone = timezone
else:
self.timezone = Timezone.fromstring(timezone)
self.current_dt = current_dt or datetime.datetime.now(tz=self.timezone)
if documents is not None:
self.documents = {
k: get_node_tree(v, self.namespaces, k) if v is not None else v
for k, v in documents.items()
}
self.variables = {}
if variables is not None:
for k, v in variables.items():
if v is None or isinstance(v, (list, tuple)):
self.variables[k] = self.get_collection(v)
else:
self.variables[k] = self.get_context_item(v)
if collections is not None:
self.collections = {k: self.get_collection(v) for k, v in collections.items()}
if default_collection is not None:
self.default_collection = self.get_collection(default_collection)
self.text_resources = text_resources if text_resources is not None else {}
self.resource_collections = resource_collections
self.default_resource_collection = default_resource_collection
self.allow_environment = allow_environment
self.default_language = None if default_language is None else Language(default_language)
self.default_calendar = default_calendar
self.default_place = default_place
def __repr__(self) -> str:
if self.root is not None:
return f'{self.__class__.__name__}(root={self.root.value})'
elif isinstance(self.item, XPathNode):
return f'{self.__class__.__name__}(item={self.item.value})'
else:
return f'{self.__class__.__name__}(item={self.item!r})'
def __copy__(self) -> 'XPathContext':
obj: XPathContext = object.__new__(self.__class__)
obj.__dict__.update(self.__dict__)
obj.axis = None
obj.variables = {k: v for k, v in self.variables.items()}
return obj
@property
def etree(self) -> ModuleType:
if self._etree is None:
if isinstance(self.root, (DocumentNode, ElementNode)):
module_name = self.root.value.__class__.__module__
elif isinstance(self.item, (DocumentNode, ElementNode, CommentNode,
ProcessingInstructionNode)):
module_name = self.item.value.__class__.__module__
else:
module_name = 'xml.etree.ElementTree'
if not isinstance(module_name, str) or not module_name.startswith('lxml.'):
etree_module_name = 'xml.etree.ElementTree'
else:
etree_module_name = 'lxml.etree'
self._etree: ModuleType = importlib.import_module(etree_module_name)
return self._etree
def get_root(self, node: Any) -> Union[None, ElementNode, DocumentNode]:
if isinstance(self.root, (DocumentNode, ElementNode)):
if any(node is x for x in self.root.iter()):
return self.root
if self.documents is not None:
for uri, doc in self.documents.items():
if doc is not None and any(node is x for x in doc.iter()):
return doc
return None
def is_document(self) -> bool:
return isinstance(self.document, DocumentNode)
def is_fragment(self) -> bool:
return self.document is None and self.root is not None
def is_rooted_subtree(self) -> bool:
return self.root is not None and isinstance(self.root.parent, ElementNode)
def is_principal_node_kind(self) -> bool:
if self.axis == 'attribute':
return isinstance(self.item, AttributeNode)
elif self.axis == 'namespace':
return isinstance(self.item, NamespaceNode)
else:
return isinstance(self.item, ElementNode)
def get_context_item(self, item: ItemArgType,
namespaces: Optional[NamespacesType] = None,
uri: Optional[str] = None,
fragment: bool = False) -> ItemType:
"""
Checks the item and returns an item suitable for XPath processing.
For XML trees and elements try a match with an existing node in the
context. If it fails then builds a new node using also the provided
optional arguments.
"""
if isinstance(item, (XPathNode, AnyAtomicType)):
return item
elif is_etree_document(item):
if self.root is not None and item is self.root.value:
return self.root
if self.documents:
for doc in self.documents.values():
if doc is not None and item is doc.value:
return doc
elif is_etree_element(item):
try:
return self.root.elements[item] # type: ignore[index,union-attr]
except (TypeError, KeyError, AttributeError):
pass
if self.documents:
for doc in self.documents.values():
if doc is not None and doc.elements is not None and item in doc.elements:
return doc.elements[item] # type: ignore[index]
if callable(item.tag): # type: ignore[union-attr]
if item.tag.__name__ == 'Comment': # type: ignore[union-attr]
return CommentNode(cast(ElementProtocol, item))
else:
return ProcessingInstructionNode(cast(ElementProtocol, item))
elif not isinstance(item, Token) or not callable(item):
msg = f"Unexpected type {type(item)} for context item"
raise ElementPathTypeError(msg)
else:
return item
return get_node_tree(
root=cast(Union[ElementProtocol, DocumentProtocol], item),
namespaces=namespaces,
uri=uri,
fragment=fragment
)
def get_collection(self, items: Optional[CollectionArgType]) -> Optional[List[ItemType]]:
if items is None:
return None
elif isinstance(items, (list, tuple)):
return [self.get_context_item(x) for x in items]
else:
return [self.get_context_item(items)]
def inner_focus_select(self, token: Union['XPathToken', 'XPathAxis']) -> Iterator[Any]:
"""Apply the token's selector with an inner focus."""
status = self.item, self.size, self.position, self.axis
results = [x for x in token.select(copy(self))]
self.axis = None
if token.label == 'axis' and cast('XPathAxis', token).reverse_axis:
self.size = self.position = len(results)
for self.item in results:
yield self.item
self.position -= 1
else:
self.size = len(results)
for self.position, self.item in enumerate(results, start=1):
yield self.item
self.item, self.size, self.position, self.axis = status
def iter_product(self, selectors: Sequence[Callable[[Any], Any]],
varnames: Optional[Sequence[str]] = None) -> Iterator[Any]:
"""
Iterator for cartesian products of selectors.
:param selectors: a sequence of selector generator functions.
:param varnames: a sequence of variables for storing the generated values.
"""
iterators = [x(self) for x in selectors]
dimension = len(iterators)
prod = [None] * dimension
max_index = dimension - 1
k = 0
while True:
try:
value = next(iterators[k])
except StopIteration:
if not k:
return
iterators[k] = selectors[k](self)
k -= 1
else:
if varnames is not None:
try:
self.variables[varnames[k]] = value
except (TypeError, IndexError):
pass
prod[k] = value
if k == max_index:
yield tuple(prod)
else:
k += 1
##
# Context item iterators for axis
def iter_self(self) -> Iterator[Optional[ItemType]]:
"""Iterator for 'self' axis and '.' shortcut."""
if self.item is not None:
status = self.axis
self.axis = 'self'
yield self.item
self.axis = status
def iter_attributes(self) -> Iterator[AttributeNode]:
"""Iterator for 'attribute' axis and '@' shortcut."""
status: Any
if isinstance(self.item, AttributeNode):
status = self.axis
self.axis = 'attribute'
yield self.item
self.axis = status
return
elif isinstance(self.item, ElementNode):
status = self.item, self.axis
self.axis = 'attribute'
for self.item in self.item.attributes:
yield self.item
self.item, self.axis = status
def iter_children_or_self(self) -> Iterator[Optional[ItemType]]:
"""Iterator for 'child' forward axis and '/' step."""
if self.item is not None:
if self.axis is not None:
yield self.item
elif isinstance(self.item, (ElementNode, DocumentNode)):
_status = self.item, self.axis
self.axis = 'child'
if self.item is self.document and self.root is not self.document:
yield self.root
else:
for self.item in self.item:
yield self.item
self.item, self.axis = _status
def iter_parent(self) -> Iterator[Union[ElementNode, DocumentNode]]:
"""Iterator for 'parent' reverse axis and '..' shortcut."""
if isinstance(self.item, XPathNode):
# A stop rule for non-rooted fragments (e.g. root is a schema elements)
if self.document is not None or self.item is not self.root:
if self.item.parent is not None:
status = self.item, self.axis
self.axis = 'parent'
self.item = self.item.parent
yield self.item
self.item, self.axis = status
def iter_siblings(self, axis: Optional[str] = None) -> Iterator[ChildNodeType]:
"""
Iterator for 'following-sibling' forward axis and 'preceding-sibling' reverse axis.
:param axis: the context axis, default is 'following-sibling'.
"""
if isinstance(self.item, XPathNode):
if self.document is not None or self.item is not self.root:
item = self.item
if item.parent is not None:
status = self.item, self.axis
self.axis = axis or 'following-sibling'
if axis == 'preceding-sibling':
for child in item.parent: # pragma: no cover
if child is item:
break
self.item = child
yield child
else:
follows = False
for child in item.parent:
if follows:
self.item = child
yield child
elif child is item:
follows = True
self.item, self.axis = status
def iter_descendants(self, axis: Optional[str] = None) -> Iterator[Union[None, XPathNode]]:
"""
Iterator for 'descendant' and 'descendant-or-self' forward axes and '//' shortcut.
:param axis: the context axis, for default has no explicit axis.
"""
if isinstance(self.item, (DocumentNode, ElementNode)):
status = self.item, self.axis
self.axis = axis
for self.item in self.item.iter_descendants(with_self=axis != 'descendant'):
yield self.item
self.item, self.axis = status
elif axis != 'descendant' and isinstance(self.item, XPathNode):
self.axis, axis = axis, self.axis
yield self.item
self.axis = axis
def iter_ancestors(self, axis: Optional[str] = None) -> Iterator[XPathNode]:
"""
Iterator for 'ancestor' and 'ancestor-or-self' reverse axes.
:param axis: the context axis, default is 'ancestor'.
"""
if isinstance(self.item, XPathNode):
status = self.item, self.axis
self.axis = axis or 'ancestor'
ancestors: List[XPathNode] = []
if axis == 'ancestor-or-self':
ancestors.append(self.item)
if self.document is not None or self.item is not self.root:
parent = self.item.parent
while parent is not None:
ancestors.append(parent)
if parent is self.root and self.document is None:
break
parent = parent.parent
for self.item in reversed(ancestors):
yield self.item
self.item, self.axis = status
def iter_preceding(self) -> Iterator[Union[DocumentNode, ChildNodeType]]:
"""Iterator for 'preceding' reverse axis."""
ancestors: Set[Union[ElementNode, DocumentNode]]
item: XPathNode
if isinstance(self.item, XPathNode):
if self.document is not None or self.item is not self.root:
item = self.item
if (root := item.parent) is not None:
status = self.item, self.axis
self.axis = 'preceding'
ancestors = {root}
while root.parent is not None:
if root is self.root and self.document is None:
break
root = root.parent
ancestors.add(root)
for self.item in root.iter_descendants():
if self.item is item:
break
if self.item not in ancestors:
yield self.item
self.item, self.axis = status
def iter_followings(self) -> Iterator[ChildNodeType]:
"""Iterator for 'following' forward axis."""
if isinstance(self.item, ElementNode):
status = self.item, self.axis
self.axis = 'following'
descendants = set(self.item.iter_descendants())
position = self.item.position
root = self.item
while isinstance(root.parent, ElementNode) and root is not self.root:
root = root.parent
for item in root.iter_descendants(with_self=False):
if position < item.position and item not in descendants:
self.item = item
yield cast(ChildNodeType, self.item)
self.item, self.axis = status
|
(root: Union[elementpath.xpath_nodes.DocumentNode, elementpath.xpath_nodes.ElementNode, NoneType] = None, namespaces: Optional[MutableMapping[str, str]] = None, uri: Optional[str] = None, fragment: bool = False, item: Optional[Any] = None, position: int = 1, size: int = 1, axis: Optional[str] = None, variables: Dict[str, Union[Any, List[Any]]] = None, current_dt: Optional[datetime.datetime] = None, timezone: Union[str, elementpath.datatypes.datetime.Timezone, NoneType] = None, documents: Optional[Dict[str, Union[elementpath.xpath_nodes.DocumentNode, elementpath.xpath_nodes.ElementNode, NoneType]]] = None, collections: Optional[Dict[str, Union[NoneType, Any, List[Any], Tuple[Any, ...]]]] = None, default_collection: Union[NoneType, Any, List[Any], Tuple[Any, ...]] = None, text_resources: Optional[Dict[str, str]] = None, resource_collections: Optional[Dict[str, List[str]]] = None, default_resource_collection: Optional[str] = None, allow_environment: bool = False, default_language: Optional[str] = None, default_calendar: Optional[str] = None, default_place: Optional[str] = None) -> None
|
72,000 |
elementpath.xpath_context
|
__copy__
| null |
def __copy__(self) -> 'XPathContext':
obj: XPathContext = object.__new__(self.__class__)
obj.__dict__.update(self.__dict__)
obj.axis = None
obj.variables = {k: v for k, v in self.variables.items()}
return obj
|
(self) -> elementpath.xpath_context.XPathContext
|
72,001 |
elementpath.xpath_context
|
__init__
| null |
def __init__(self,
root: Optional[RootArgType] = None,
namespaces: Optional[NamespacesType] = None,
uri: Optional[str] = None,
fragment: bool = False,
item: Optional[ItemArgType] = None,
position: int = 1,
size: int = 1,
axis: Optional[str] = None,
variables: Optional[Dict[str, CollectionArgType]] = None,
current_dt: Optional[datetime.datetime] = None,
timezone: Optional[Union[str, Timezone]] = None,
documents: Optional[Dict[str, Optional[RootArgType]]] = None,
collections: Optional[Dict[str, CollectionArgType]] = None,
default_collection: CollectionArgType = None,
text_resources: Optional[Dict[str, str]] = None,
resource_collections: Optional[Dict[str, List[str]]] = None,
default_resource_collection: Optional[str] = None,
allow_environment: bool = False,
default_language: Optional[str] = None,
default_calendar: Optional[str] = None,
default_place: Optional[str] = None) -> None:
if namespaces:
self.namespaces = {k: v for k, v in namespaces.items()}
else:
self.namespaces = {}
if root is not None:
self.root = get_node_tree(root, self.namespaces, uri, fragment)
if item is not None:
self.item = self.get_context_item(item, self.namespaces)
else:
self.item = self.root
elif item is not None:
self.item = self.get_context_item(item, self.namespaces, uri, fragment)
else:
raise ElementPathTypeError("Missing both the root node and the context item!")
if isinstance(self.root, DocumentNode):
self.document = self.root
elif fragment or isinstance(self.root, SchemaElementNode):
pass
elif isinstance(self.root, ElementNode):
# Creates a dummy document
document = cast(DocumentProtocol, self.etree.ElementTree(self.root.elem))
self.document = DocumentNode(document, self.root.uri, position=0)
self.document.children.append(self.root)
self.document.elements = cast(Dict[ElementProtocol, ElementNode], self.root.elements)
# self.root.parent = self.document TODO for v5? It's necessary?
self.position = position
self.size = size
self.axis = axis
if timezone is None or isinstance(timezone, Timezone):
self.timezone = timezone
else:
self.timezone = Timezone.fromstring(timezone)
self.current_dt = current_dt or datetime.datetime.now(tz=self.timezone)
if documents is not None:
self.documents = {
k: get_node_tree(v, self.namespaces, k) if v is not None else v
for k, v in documents.items()
}
self.variables = {}
if variables is not None:
for k, v in variables.items():
if v is None or isinstance(v, (list, tuple)):
self.variables[k] = self.get_collection(v)
else:
self.variables[k] = self.get_context_item(v)
if collections is not None:
self.collections = {k: self.get_collection(v) for k, v in collections.items()}
if default_collection is not None:
self.default_collection = self.get_collection(default_collection)
self.text_resources = text_resources if text_resources is not None else {}
self.resource_collections = resource_collections
self.default_resource_collection = default_resource_collection
self.allow_environment = allow_environment
self.default_language = None if default_language is None else Language(default_language)
self.default_calendar = default_calendar
self.default_place = default_place
|
(self, root: Union[elementpath.protocols.DocumentProtocol, elementpath.protocols.ElementProtocol, elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol, elementpath.xpath_nodes.DocumentNode, elementpath.xpath_nodes.ElementNode, NoneType] = None, namespaces: Optional[MutableMapping[str, str]] = None, uri: Optional[str] = None, fragment: bool = False, item: Optional[Any] = None, position: int = 1, size: int = 1, axis: Optional[str] = None, variables: Optional[Dict[str, Union[NoneType, Any, List[Any], Tuple[Any, ...]]]] = None, current_dt: Optional[datetime.datetime] = None, timezone: Union[str, elementpath.datatypes.datetime.Timezone, NoneType] = None, documents: Optional[Dict[str, Union[elementpath.protocols.DocumentProtocol, elementpath.protocols.ElementProtocol, elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol, elementpath.xpath_nodes.DocumentNode, elementpath.xpath_nodes.ElementNode, NoneType]]] = None, collections: Optional[Dict[str, Union[NoneType, Any, List[Any], Tuple[Any, ...]]]] = None, default_collection: Union[NoneType, Any, List[Any], Tuple[Any, ...]] = None, text_resources: Optional[Dict[str, str]] = None, resource_collections: Optional[Dict[str, List[str]]] = None, default_resource_collection: Optional[str] = None, allow_environment: bool = False, default_language: Optional[str] = None, default_calendar: Optional[str] = None, default_place: Optional[str] = None) -> NoneType
|
72,002 |
elementpath.xpath_context
|
__repr__
| null |
def __repr__(self) -> str:
if self.root is not None:
return f'{self.__class__.__name__}(root={self.root.value})'
elif isinstance(self.item, XPathNode):
return f'{self.__class__.__name__}(item={self.item.value})'
else:
return f'{self.__class__.__name__}(item={self.item!r})'
|
(self) -> str
|
72,003 |
elementpath.xpath_context
|
get_collection
| null |
def get_collection(self, items: Optional[CollectionArgType]) -> Optional[List[ItemType]]:
if items is None:
return None
elif isinstance(items, (list, tuple)):
return [self.get_context_item(x) for x in items]
else:
return [self.get_context_item(items)]
|
(self, items: Union[NoneType, Any, List[Any], Tuple[Any, ...]]) -> Optional[List[Any]]
|
72,004 |
elementpath.xpath_context
|
get_context_item
|
Checks the item and returns an item suitable for XPath processing.
For XML trees and elements try a match with an existing node in the
context. If it fails then builds a new node using also the provided
optional arguments.
|
def get_context_item(self, item: ItemArgType,
namespaces: Optional[NamespacesType] = None,
uri: Optional[str] = None,
fragment: bool = False) -> ItemType:
"""
Checks the item and returns an item suitable for XPath processing.
For XML trees and elements try a match with an existing node in the
context. If it fails then builds a new node using also the provided
optional arguments.
"""
if isinstance(item, (XPathNode, AnyAtomicType)):
return item
elif is_etree_document(item):
if self.root is not None and item is self.root.value:
return self.root
if self.documents:
for doc in self.documents.values():
if doc is not None and item is doc.value:
return doc
elif is_etree_element(item):
try:
return self.root.elements[item] # type: ignore[index,union-attr]
except (TypeError, KeyError, AttributeError):
pass
if self.documents:
for doc in self.documents.values():
if doc is not None and doc.elements is not None and item in doc.elements:
return doc.elements[item] # type: ignore[index]
if callable(item.tag): # type: ignore[union-attr]
if item.tag.__name__ == 'Comment': # type: ignore[union-attr]
return CommentNode(cast(ElementProtocol, item))
else:
return ProcessingInstructionNode(cast(ElementProtocol, item))
elif not isinstance(item, Token) or not callable(item):
msg = f"Unexpected type {type(item)} for context item"
raise ElementPathTypeError(msg)
else:
return item
return get_node_tree(
root=cast(Union[ElementProtocol, DocumentProtocol], item),
namespaces=namespaces,
uri=uri,
fragment=fragment
)
|
(self, item: Any, namespaces: Optional[MutableMapping[str, str]] = None, uri: Optional[str] = None, fragment: bool = False) -> Any
|
72,005 |
elementpath.xpath_context
|
get_root
| null |
def get_root(self, node: Any) -> Union[None, ElementNode, DocumentNode]:
if isinstance(self.root, (DocumentNode, ElementNode)):
if any(node is x for x in self.root.iter()):
return self.root
if self.documents is not None:
for uri, doc in self.documents.items():
if doc is not None and any(node is x for x in doc.iter()):
return doc
return None
|
(self, node: Any) -> Union[NoneType, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode]
|
72,006 |
elementpath.xpath_context
|
inner_focus_select
|
Apply the token's selector with an inner focus.
|
def inner_focus_select(self, token: Union['XPathToken', 'XPathAxis']) -> Iterator[Any]:
"""Apply the token's selector with an inner focus."""
status = self.item, self.size, self.position, self.axis
results = [x for x in token.select(copy(self))]
self.axis = None
if token.label == 'axis' and cast('XPathAxis', token).reverse_axis:
self.size = self.position = len(results)
for self.item in results:
yield self.item
self.position -= 1
else:
self.size = len(results)
for self.position, self.item in enumerate(results, start=1):
yield self.item
self.item, self.size, self.position, self.axis = status
|
(self, token: Union[ForwardRef('XPathToken'), ForwardRef('XPathAxis')]) -> Iterator[Any]
|
72,007 |
elementpath.xpath_context
|
is_document
| null |
def is_document(self) -> bool:
return isinstance(self.document, DocumentNode)
|
(self) -> bool
|
72,008 |
elementpath.xpath_context
|
is_fragment
| null |
def is_fragment(self) -> bool:
return self.document is None and self.root is not None
|
(self) -> bool
|
72,009 |
elementpath.xpath_context
|
is_principal_node_kind
| null |
def is_principal_node_kind(self) -> bool:
if self.axis == 'attribute':
return isinstance(self.item, AttributeNode)
elif self.axis == 'namespace':
return isinstance(self.item, NamespaceNode)
else:
return isinstance(self.item, ElementNode)
|
(self) -> bool
|
72,010 |
elementpath.xpath_context
|
is_rooted_subtree
| null |
def is_rooted_subtree(self) -> bool:
return self.root is not None and isinstance(self.root.parent, ElementNode)
|
(self) -> bool
|
72,011 |
elementpath.xpath_context
|
iter_ancestors
|
Iterator for 'ancestor' and 'ancestor-or-self' reverse axes.
:param axis: the context axis, default is 'ancestor'.
|
def iter_ancestors(self, axis: Optional[str] = None) -> Iterator[XPathNode]:
"""
Iterator for 'ancestor' and 'ancestor-or-self' reverse axes.
:param axis: the context axis, default is 'ancestor'.
"""
if isinstance(self.item, XPathNode):
status = self.item, self.axis
self.axis = axis or 'ancestor'
ancestors: List[XPathNode] = []
if axis == 'ancestor-or-self':
ancestors.append(self.item)
if self.document is not None or self.item is not self.root:
parent = self.item.parent
while parent is not None:
ancestors.append(parent)
if parent is self.root and self.document is None:
break
parent = parent.parent
for self.item in reversed(ancestors):
yield self.item
self.item, self.axis = status
|
(self, axis: Optional[str] = None) -> Iterator[elementpath.xpath_nodes.XPathNode]
|
72,012 |
elementpath.xpath_context
|
iter_attributes
|
Iterator for 'attribute' axis and '@' shortcut.
|
def iter_attributes(self) -> Iterator[AttributeNode]:
"""Iterator for 'attribute' axis and '@' shortcut."""
status: Any
if isinstance(self.item, AttributeNode):
status = self.axis
self.axis = 'attribute'
yield self.item
self.axis = status
return
elif isinstance(self.item, ElementNode):
status = self.item, self.axis
self.axis = 'attribute'
for self.item in self.item.attributes:
yield self.item
self.item, self.axis = status
|
(self) -> Iterator[elementpath.xpath_nodes.AttributeNode]
|
72,013 |
elementpath.xpath_context
|
iter_children_or_self
|
Iterator for 'child' forward axis and '/' step.
|
def iter_children_or_self(self) -> Iterator[Optional[ItemType]]:
"""Iterator for 'child' forward axis and '/' step."""
if self.item is not None:
if self.axis is not None:
yield self.item
elif isinstance(self.item, (ElementNode, DocumentNode)):
_status = self.item, self.axis
self.axis = 'child'
if self.item is self.document and self.root is not self.document:
yield self.root
else:
for self.item in self.item:
yield self.item
self.item, self.axis = _status
|
(self) -> Iterator[Optional[Any]]
|
72,014 |
elementpath.xpath_context
|
iter_descendants
|
Iterator for 'descendant' and 'descendant-or-self' forward axes and '//' shortcut.
:param axis: the context axis, for default has no explicit axis.
|
def iter_descendants(self, axis: Optional[str] = None) -> Iterator[Union[None, XPathNode]]:
"""
Iterator for 'descendant' and 'descendant-or-self' forward axes and '//' shortcut.
:param axis: the context axis, for default has no explicit axis.
"""
if isinstance(self.item, (DocumentNode, ElementNode)):
status = self.item, self.axis
self.axis = axis
for self.item in self.item.iter_descendants(with_self=axis != 'descendant'):
yield self.item
self.item, self.axis = status
elif axis != 'descendant' and isinstance(self.item, XPathNode):
self.axis, axis = axis, self.axis
yield self.item
self.axis = axis
|
(self, axis: Optional[str] = None) -> Iterator[Optional[elementpath.xpath_nodes.XPathNode]]
|
72,015 |
elementpath.xpath_context
|
iter_followings
|
Iterator for 'following' forward axis.
|
def iter_followings(self) -> Iterator[ChildNodeType]:
"""Iterator for 'following' forward axis."""
if isinstance(self.item, ElementNode):
status = self.item, self.axis
self.axis = 'following'
descendants = set(self.item.iter_descendants())
position = self.item.position
root = self.item
while isinstance(root.parent, ElementNode) and root is not self.root:
root = root.parent
for item in root.iter_descendants(with_self=False):
if position < item.position and item not in descendants:
self.item = item
yield cast(ChildNodeType, self.item)
self.item, self.axis = status
|
(self) -> Iterator[Union[ForwardRef('TextNode'), ForwardRef('ElementNode'), ForwardRef('CommentNode'), ForwardRef('ProcessingInstructionNode')]]
|
72,016 |
elementpath.xpath_context
|
iter_parent
|
Iterator for 'parent' reverse axis and '..' shortcut.
|
def iter_parent(self) -> Iterator[Union[ElementNode, DocumentNode]]:
"""Iterator for 'parent' reverse axis and '..' shortcut."""
if isinstance(self.item, XPathNode):
# A stop rule for non-rooted fragments (e.g. root is a schema elements)
if self.document is not None or self.item is not self.root:
if self.item.parent is not None:
status = self.item, self.axis
self.axis = 'parent'
self.item = self.item.parent
yield self.item
self.item, self.axis = status
|
(self) -> Iterator[Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode]]
|
72,017 |
elementpath.xpath_context
|
iter_preceding
|
Iterator for 'preceding' reverse axis.
|
def iter_preceding(self) -> Iterator[Union[DocumentNode, ChildNodeType]]:
"""Iterator for 'preceding' reverse axis."""
ancestors: Set[Union[ElementNode, DocumentNode]]
item: XPathNode
if isinstance(self.item, XPathNode):
if self.document is not None or self.item is not self.root:
item = self.item
if (root := item.parent) is not None:
status = self.item, self.axis
self.axis = 'preceding'
ancestors = {root}
while root.parent is not None:
if root is self.root and self.document is None:
break
root = root.parent
ancestors.add(root)
for self.item in root.iter_descendants():
if self.item is item:
break
if self.item not in ancestors:
yield self.item
self.item, self.axis = status
|
(self) -> Iterator[Union[elementpath.xpath_nodes.DocumentNode, ForwardRef('TextNode'), ForwardRef('ElementNode'), ForwardRef('CommentNode'), ForwardRef('ProcessingInstructionNode')]]
|
72,018 |
elementpath.xpath_context
|
iter_product
|
Iterator for cartesian products of selectors.
:param selectors: a sequence of selector generator functions.
:param varnames: a sequence of variables for storing the generated values.
|
def iter_product(self, selectors: Sequence[Callable[[Any], Any]],
varnames: Optional[Sequence[str]] = None) -> Iterator[Any]:
"""
Iterator for cartesian products of selectors.
:param selectors: a sequence of selector generator functions.
:param varnames: a sequence of variables for storing the generated values.
"""
iterators = [x(self) for x in selectors]
dimension = len(iterators)
prod = [None] * dimension
max_index = dimension - 1
k = 0
while True:
try:
value = next(iterators[k])
except StopIteration:
if not k:
return
iterators[k] = selectors[k](self)
k -= 1
else:
if varnames is not None:
try:
self.variables[varnames[k]] = value
except (TypeError, IndexError):
pass
prod[k] = value
if k == max_index:
yield tuple(prod)
else:
k += 1
|
(self, selectors: Sequence[Callable[[Any], Any]], varnames: Optional[Sequence[str]] = None) -> Iterator[Any]
|
72,019 |
elementpath.xpath_context
|
iter_self
|
Iterator for 'self' axis and '.' shortcut.
|
def iter_self(self) -> Iterator[Optional[ItemType]]:
"""Iterator for 'self' axis and '.' shortcut."""
if self.item is not None:
status = self.axis
self.axis = 'self'
yield self.item
self.axis = status
|
(self) -> Iterator[Optional[Any]]
|
72,020 |
elementpath.xpath_context
|
iter_siblings
|
Iterator for 'following-sibling' forward axis and 'preceding-sibling' reverse axis.
:param axis: the context axis, default is 'following-sibling'.
|
def iter_siblings(self, axis: Optional[str] = None) -> Iterator[ChildNodeType]:
"""
Iterator for 'following-sibling' forward axis and 'preceding-sibling' reverse axis.
:param axis: the context axis, default is 'following-sibling'.
"""
if isinstance(self.item, XPathNode):
if self.document is not None or self.item is not self.root:
item = self.item
if item.parent is not None:
status = self.item, self.axis
self.axis = axis or 'following-sibling'
if axis == 'preceding-sibling':
for child in item.parent: # pragma: no cover
if child is item:
break
self.item = child
yield child
else:
follows = False
for child in item.parent:
if follows:
self.item = child
yield child
elif child is item:
follows = True
self.item, self.axis = status
|
(self, axis: Optional[str] = None) -> Iterator[Union[ForwardRef('TextNode'), ForwardRef('ElementNode'), ForwardRef('CommentNode'), ForwardRef('ProcessingInstructionNode')]]
|
72,021 |
elementpath.xpath_tokens
|
XPathFunction
|
A token for processing XPath functions.
|
class XPathFunction(XPathToken):
"""
A token for processing XPath functions.
"""
__name__: str
_name: Optional[QName] = None
pattern = r'(?<!\$)\b[^\d\W][\w.\-\xb7\u0300-\u036F\u203F\u2040]*' \
r'(?=\s*(?:\(\:.*\:\))?\s*\((?!\:))'
sequence_types: Union[List[str], Tuple[str, ...]] = ()
"Sequence types of arguments and of the return value of the function."
nargs: NargsType = None
"Number of arguments: a single value or a couple with None that means unbounded."
context: ContextArgType = None
"Dynamic context associated by function reference evaluation or explicitly by a builder."
def __init__(self, parser: XPathParserType, nargs: Optional[int] = None) -> None:
super().__init__(parser)
if isinstance(nargs, int) and nargs != self.nargs:
if nargs < 0:
raise self.error('XPST0017', 'number of arguments must be non negative')
elif self.nargs is None:
self.nargs = nargs
elif isinstance(self.nargs, int):
raise self.error('XPST0017', 'incongruent number of arguments')
elif self.nargs[0] > nargs or self.nargs[1] is not None and self.nargs[1] < nargs:
raise self.error('XPST0017', 'incongruent number of arguments')
else:
self.nargs = nargs
def __repr__(self) -> str:
qname = self.name
if qname is None:
return '<%s object at %#x>' % (self.__class__.__name__, id(self))
elif not isinstance(self.nargs, int):
return '<XPathFunction %s at %#x>' % (qname.qname, id(self))
return '<XPathFunction %s#%r at %#x>' % (qname.qname, self.nargs, id(self))
def __str__(self) -> str:
if self.namespace is None:
return f'{self.symbol!r} {self.label}'
elif self.namespace == XPATH_FUNCTIONS_NAMESPACE:
return f"'fn:{self.symbol}' {self.label}"
else:
for prefix, uri in self.parser.namespaces.items():
if uri == self.namespace:
return f"'{prefix}:{self.symbol}' {self.label}"
else:
return f"'Q{{{self.namespace}}}{self.symbol}' {self.label}"
def __call__(self, *args: XPathFunctionArgType,
context: ContextArgType = None) -> Any:
self.check_arguments_number(len(args))
context = copy(self.context or context)
if self.label == 'partial function':
for value, tk in zip(args, filter(lambda x: x.symbol == '?', self)):
if isinstance(value, XPathToken) and not isinstance(value, XPathFunction):
tk.value = value.evaluate(context)
else:
tk.value = value
else:
self.clear()
for value in args:
if isinstance(value, XPathToken):
self._items.append(value)
elif value is None or isinstance(value, (XPathNode, AnyAtomicType, list)):
self._items.append(ValueToken(self.parser, value=value))
elif not is_etree_document(value) and not is_etree_element(value):
raise self.error('XPTY0004', f"unexpected argument type {type(value)}")
else:
# Accepts and wraps etree elements/documents, useful for external calls.
if context is not None:
value = context.get_context_item(
cast(Union[ElementProtocol, DocumentProtocol], value),
namespaces=context.namespaces,
uri=self.parser.base_uri
)
else:
value = get_node_tree(
cast(Union[ElementProtocol, DocumentProtocol], value),
namespaces=self.parser.namespaces,
uri=self.parser.base_uri
)
self._items.append(ValueToken(self.parser, value=value))
if any(tk.symbol == '?' and not tk for tk in self._items):
self.to_partial_function()
return self
if isinstance(self.label, MultiLabel):
# Disambiguate multi-label tokens
if self.namespace == XSD_NAMESPACE and \
'constructor function' in self.label.values:
self.label = 'constructor function'
else:
for label in self.label.values:
if label.endswith('function'):
self.label = label
break
if self.label == 'partial function':
result = self._partial_evaluate(context)
else:
result = self.evaluate(context)
return self.validated_result(result)
def check_arguments_number(self, nargs: int) -> None:
"""Check the number of arguments against function arity."""
if self.nargs is None or self.nargs == nargs:
pass
elif isinstance(self.nargs, tuple):
if nargs < self.nargs[0]:
raise self.error('XPTY0004', "missing required arguments")
elif self.nargs[1] is not None and nargs > self.nargs[1]:
raise self.error('XPTY0004', "too many arguments")
elif self.nargs > nargs:
raise self.error('XPTY0004', "missing required arguments")
else:
raise self.error('XPTY0004', "too many arguments")
def validated_result(self, result: Any) -> Any:
if isinstance(result, XPathToken) and result.symbol == '?':
return result
elif match_sequence_type(result, self.sequence_types[-1], self.parser):
return result
_result = self.cast_to_primitive_type(result, self.sequence_types[-1])
if not match_sequence_type(_result, self.sequence_types[-1], self.parser):
msg = "{!r} does not match sequence type {}"
raise self.error('XPTY0004', msg.format(result, self.sequence_types[-1]))
return _result
@property
def source(self) -> str:
if self.label in ('sequence type', 'kind test', ''):
return '%s(%s)%s' % (
self.symbol, ', '.join(item.source for item in self), self.occurrence or ''
)
return '%s(%s)' % (self.symbol, ', '.join(item.source for item in self))
@property
def name(self) -> Optional[QName]:
if self._name is not None:
return self._name
elif self.symbol == 'function':
return None
elif self.label == 'partial function':
return None
elif not self.namespace:
self._name = QName(None, self.symbol)
elif self.namespace == XPATH_FUNCTIONS_NAMESPACE:
self._name = QName(XPATH_FUNCTIONS_NAMESPACE, 'fn:%s' % self.symbol)
elif self.namespace == XSD_NAMESPACE:
self._name = QName(XSD_NAMESPACE, 'xs:%s' % self.symbol)
elif self.namespace == XPATH_MATH_FUNCTIONS_NAMESPACE:
self._name = QName(XPATH_MATH_FUNCTIONS_NAMESPACE, 'math:%s' % self.symbol)
else:
for pfx, uri in self.parser.namespaces.items():
if uri == self.namespace:
self._name = QName(uri, f'{pfx}:{self.symbol}')
break
else:
self._name = QName(self.namespace, self.symbol)
return self._name
@property
def arity(self) -> int:
if isinstance(self.nargs, int):
return self.nargs
return len(self._items)
@property
def min_args(self) -> int:
if isinstance(self.nargs, int):
return self.nargs
elif isinstance(self.nargs, (tuple, list)):
return self.nargs[0]
else:
return 0
@property
def max_args(self) -> Optional[int]:
if isinstance(self.nargs, int):
return self.nargs
elif isinstance(self.nargs, (tuple, list)):
return self.nargs[1]
else:
return None
def is_reference(self) -> int:
if not isinstance(self.nargs, int):
return False
return self.nargs and not len(self._items)
def nud(self) -> 'XPathFunction':
self.value = None
if not self.parser.parse_arguments:
return self
code = 'XPST0017' if self.label == 'function' else 'XPST0003'
self.parser.advance('(')
if self.nargs is None:
del self._items[:]
if self.parser.next_token.symbol in (')', '(end)'):
raise self.error(code, 'at least an argument is required')
while True:
self.append(self.parser.expression(5))
if self.parser.next_token.symbol != ',':
break
self.parser.advance()
elif self.nargs == 0:
if self.parser.next_token.symbol != ')':
if self.parser.next_token.symbol != '(end)':
raise self.error(code, '%s has no arguments' % str(self))
raise self.parser.next_token.wrong_syntax()
self.parser.advance()
return self
else:
if isinstance(self.nargs, (tuple, list)):
min_args, max_args = self.nargs
else:
min_args = max_args = self.nargs
k = 0
while k < min_args:
if self.parser.next_token.symbol in (')', '(end)'):
msg = 'Too few arguments: expected at least %s arguments' % min_args
raise self.error('XPST0017', msg if min_args > 1 else msg[:-1])
self._items[k:] = self.parser.expression(5),
k += 1
if k < min_args:
if self.parser.next_token.symbol == ')':
msg = f'{str(self)}: Too few arguments, expected ' \
f'at least {min_args} arguments'
raise self.error(code, msg if min_args > 1 else msg[:-1])
self.parser.advance(',')
while max_args is None or k < max_args:
if self.parser.next_token.symbol == ',':
self.parser.advance(',')
self._items[k:] = self.parser.expression(5),
elif k == 0 and self.parser.next_token.symbol != ')':
self._items[k:] = self.parser.expression(5),
else:
break # pragma: no cover
k += 1
if self.parser.next_token.symbol == ',':
msg = 'Too many arguments: expected at most %s arguments' % max_args
raise self.error(code, msg if max_args != 1 else msg[:-1])
self.parser.advance(')')
if any(tk.symbol == '?' and not tk for tk in self._items):
self.to_partial_function()
return self
def match_function_test(self, function_test: Union[str, List[str]],
as_argument: bool = False) -> bool:
"""
Match if function signature satisfies the provided *function_test*.
For default return type is covariant and arguments are contravariant.
If *as_argument* is `True` the match is inverted.
References:
https://www.w3.org/TR/xpath-31/#id-function-test
https://www.w3.org/TR/xpath-31/#id-sequencetype-subtype
"""
if isinstance(function_test, list):
sequence_types = function_test
else:
sequence_types = split_function_test(function_test)
if not sequence_types or not sequence_types[-1]:
return False
elif sequence_types[0] == '*':
return True
signature = [x for x in self.sequence_types[:self.arity]]
signature.append(self.sequence_types[-1])
if len(sequence_types) != len(signature):
return False
if as_argument:
iterator = zip(sequence_types[:-1], signature[:-1])
else:
iterator = zip(signature[:-1], sequence_types[:-1])
# compare sequence types
for st1, st2 in iterator:
if not is_sequence_type_restriction(st1, st2):
return False
else:
st1, st2 = sequence_types[-1], signature[-1]
return is_sequence_type_restriction(st1, st2)
def to_partial_function(self) -> None:
"""Convert an XPath function to a partial function."""
nargs = len([tk and not tk for tk in self._items if tk.symbol == '?'])
assert nargs, "a partial function requires at least a placeholder token"
if self.label != 'partial function':
def evaluate(context: ContextArgType = None) -> Any:
return self
def select(context: ContextArgType = None) -> Any:
yield self
if self.__class__.evaluate is not XPathToken.evaluate:
setattr(self, '_partial_evaluate', self.evaluate)
if self.__class__.select is not XPathToken.select:
setattr(self, '_partial_select', self.select)
setattr(self, 'evaluate', evaluate)
setattr(self, 'select', select)
self._name = None
self.label = 'partial function'
self.nargs = nargs
def as_function(self) -> Callable[..., Any]:
"""
Wraps the XPath function instance into a standard function.
"""
def wrapper(*args: XPathFunctionArgType, context: ContextArgType = None) -> Any:
return self.__call__(*args, context=context)
qname = self.name
if self.is_reference():
ref_part = f'#{self.nargs}'
else:
ref_part = ''
if qname is None:
name = f'<anonymous-function{ref_part}>'
else:
name = f'<{qname.qname}{ref_part}>'
wrapper.__name__ = name
wrapper.__qualname__ = wrapper.__qualname__[:-7] + name
return wrapper
def _partial_evaluate(self, context: ContextArgType = None) -> Any:
return [x for x in self._partial_select(context)]
def _partial_select(self, context: ContextArgType = None) -> Iterator[Any]:
item = self._partial_evaluate(context)
if item is not None:
if isinstance(item, list):
yield from item
else:
if context is not None:
context.item = item
yield item
|
(parser: Any, nargs: Union[int, Tuple[int, Optional[int]], NoneType] = None) -> None
|
72,022 |
elementpath.xpath_tokens
|
__call__
| null |
def __call__(self, *args: XPathFunctionArgType,
context: ContextArgType = None) -> Any:
self.check_arguments_number(len(args))
context = copy(self.context or context)
if self.label == 'partial function':
for value, tk in zip(args, filter(lambda x: x.symbol == '?', self)):
if isinstance(value, XPathToken) and not isinstance(value, XPathFunction):
tk.value = value.evaluate(context)
else:
tk.value = value
else:
self.clear()
for value in args:
if isinstance(value, XPathToken):
self._items.append(value)
elif value is None or isinstance(value, (XPathNode, AnyAtomicType, list)):
self._items.append(ValueToken(self.parser, value=value))
elif not is_etree_document(value) and not is_etree_element(value):
raise self.error('XPTY0004', f"unexpected argument type {type(value)}")
else:
# Accepts and wraps etree elements/documents, useful for external calls.
if context is not None:
value = context.get_context_item(
cast(Union[ElementProtocol, DocumentProtocol], value),
namespaces=context.namespaces,
uri=self.parser.base_uri
)
else:
value = get_node_tree(
cast(Union[ElementProtocol, DocumentProtocol], value),
namespaces=self.parser.namespaces,
uri=self.parser.base_uri
)
self._items.append(ValueToken(self.parser, value=value))
if any(tk.symbol == '?' and not tk for tk in self._items):
self.to_partial_function()
return self
if isinstance(self.label, MultiLabel):
# Disambiguate multi-label tokens
if self.namespace == XSD_NAMESPACE and \
'constructor function' in self.label.values:
self.label = 'constructor function'
else:
for label in self.label.values:
if label.endswith('function'):
self.label = label
break
if self.label == 'partial function':
result = self._partial_evaluate(context)
else:
result = self.evaluate(context)
return self.validated_result(result)
|
(self, *args: Union[NoneType, elementpath.protocols.ElementProtocol, elementpath.protocols.DocumentProtocol, elementpath.xpath_tokens.XPathToken, elementpath.xpath_nodes.XPathNode, str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType, List[Union[elementpath.xpath_tokens.XPathToken, elementpath.xpath_nodes.XPathNode, str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType]]], context: Optional[elementpath.xpath_context.XPathContext] = None) -> Any
|
72,024 |
elementpath.tdop
|
__delitem__
| null |
def __delitem__(self, i: Union[int, slice]) -> None:
del self._items[i]
|
(self, i: Union[int, slice]) -> NoneType
|
72,025 |
elementpath.tdop
|
__eq__
| null |
def __eq__(self, other: object) -> bool:
if isinstance(other, Token):
return self.symbol == other.symbol and self.value == other.value
return False
|
(self, other: object) -> bool
|
72,026 |
elementpath.tdop
|
__getitem__
| null |
def __getitem__(self, i: Union[int, slice]) \
-> Union[TK, MutableSequence[TK]]:
return self._items[i]
|
(self, i: Union[int, slice]) -> Union[~TK, MutableSequence[~TK]]
|
72,028 |
elementpath.xpath_tokens
|
__init__
| null |
def __init__(self, parser: XPathParserType, nargs: Optional[int] = None) -> None:
super().__init__(parser)
if isinstance(nargs, int) and nargs != self.nargs:
if nargs < 0:
raise self.error('XPST0017', 'number of arguments must be non negative')
elif self.nargs is None:
self.nargs = nargs
elif isinstance(self.nargs, int):
raise self.error('XPST0017', 'incongruent number of arguments')
elif self.nargs[0] > nargs or self.nargs[1] is not None and self.nargs[1] < nargs:
raise self.error('XPST0017', 'incongruent number of arguments')
else:
self.nargs = nargs
|
(self, parser: Any, nargs: Optional[int] = None) -> NoneType
|
72,030 |
elementpath.tdop
|
__len__
| null |
def __len__(self) -> int:
return len(self._items)
|
(self) -> int
|
72,031 |
elementpath.xpath_tokens
|
__repr__
| null |
def __repr__(self) -> str:
qname = self.name
if qname is None:
return '<%s object at %#x>' % (self.__class__.__name__, id(self))
elif not isinstance(self.nargs, int):
return '<XPathFunction %s at %#x>' % (qname.qname, id(self))
return '<XPathFunction %s#%r at %#x>' % (qname.qname, self.nargs, id(self))
|
(self) -> str
|
72,033 |
elementpath.tdop
|
__setitem__
| null |
def __setitem__(self, i: Union[int, slice], o: Any) -> None:
self._items[i] = o
|
(self, i: Union[int, slice], o: Any) -> NoneType
|
72,034 |
elementpath.xpath_tokens
|
__str__
| null |
def __str__(self) -> str:
if self.namespace is None:
return f'{self.symbol!r} {self.label}'
elif self.namespace == XPATH_FUNCTIONS_NAMESPACE:
return f"'fn:{self.symbol}' {self.label}"
else:
for prefix, uri in self.parser.namespaces.items():
if uri == self.namespace:
return f"'{prefix}:{self.symbol}' {self.label}"
else:
return f"'Q{{{self.namespace}}}{self.symbol}' {self.label}"
|
(self) -> str
|
72,035 |
elementpath.xpath_tokens
|
_partial_evaluate
| null |
def _partial_evaluate(self, context: ContextArgType = None) -> Any:
return [x for x in self._partial_select(context)]
|
(self, context: Optional[elementpath.xpath_context.XPathContext] = None) -> Any
|
72,036 |
elementpath.xpath_tokens
|
_partial_select
| null |
def _partial_select(self, context: ContextArgType = None) -> Iterator[Any]:
item = self._partial_evaluate(context)
if item is not None:
if isinstance(item, list):
yield from item
else:
if context is not None:
context.item = item
yield item
|
(self, context: Optional[elementpath.xpath_context.XPathContext] = None) -> Iterator[Any]
|
72,037 |
elementpath.xpath_tokens
|
add_xsd_type
|
Adds an XSD type association from an item. The association is
added using the item's name and type.
|
def add_xsd_type(self, item: Any) -> Optional[XsdTypeProtocol]:
"""
Adds an XSD type association from an item. The association is
added using the item's name and type.
"""
if isinstance(item, XPathNode):
item = item.value
# TODO: replace with protocol check (XsdAttributeProtocol, XsdElementProtocol)
if not hasattr(item, 'type') or not hasattr(item, 'xsd_version'):
return None
name: str = item.name
xsd_type: XsdTypeProtocol = item.type
if self.xsd_types is None:
self.xsd_types = {name: xsd_type}
else:
obj = self.xsd_types.get(name)
if obj is None:
self.xsd_types[name] = xsd_type
elif not isinstance(obj, list):
if obj is not xsd_type:
self.xsd_types[name] = [obj, xsd_type]
elif xsd_type not in obj:
obj.append(xsd_type)
return xsd_type
|
(self, item: Any) -> Optional[elementpath.protocols.XsdTypeProtocol]
|
72,038 |
elementpath.xpath_tokens
|
adjust_datetime
|
XSD datetime adjust function helper.
:param context: the XPath dynamic context.
:param cls: the XSD datetime subclass to use.
:return: an empty list if there is only one argument that is the empty sequence or the adjusted XSD datetime instance.
|
def adjust_datetime(self, context: ContextArgType, cls: Type[AbstractDateTime]) \
-> Union[List[Any], AbstractDateTime, DayTimeDuration]:
"""
XSD datetime adjust function helper.
:param context: the XPath dynamic context.
:param cls: the XSD datetime subclass to use.
:return: an empty list if there is only one argument that is the empty sequence \
or the adjusted XSD datetime instance.
"""
timezone: Optional[Any]
item: Optional[AbstractDateTime]
_item: Union[AbstractDateTime, DayTimeDuration]
if len(self) == 1:
item = self.get_argument(context, cls=cls)
if item is None:
return []
timezone = getattr(context, 'timezone', None)
else:
item = self.get_argument(context, cls=cls)
timezone = self.get_argument(context, 1, cls=DayTimeDuration)
if timezone is not None:
try:
timezone = Timezone.fromduration(timezone)
except ValueError as err:
if isinstance(context, XPathSchemaContext):
timezone = Timezone.fromduration(DayTimeDuration(0))
else:
raise self.error('FODT0003', str(err)) from None
if item is None:
return []
_item = copy(item)
_tzinfo = _item.tzinfo
try:
if _tzinfo is not None and timezone is not None:
if isinstance(_item, DateTime10):
_item += timezone.offset
elif not isinstance(item, Date10):
_item += timezone.offset - _tzinfo.offset
elif timezone.offset < _tzinfo.offset:
_item -= timezone.offset - _tzinfo.offset
_item -= DayTimeDuration.fromstring('P1D')
except OverflowError as err:
if isinstance(context, XPathSchemaContext):
return _item
raise self.error('FODT0001', str(err)) from None
if not isinstance(_item, DayTimeDuration):
_item.tzinfo = timezone
return _item
|
(self, context: Optional[elementpath.xpath_context.XPathContext], cls: Type[elementpath.datatypes.datetime.AbstractDateTime]) -> Union[List[Any], elementpath.datatypes.datetime.AbstractDateTime, elementpath.datatypes.datetime.DayTimeDuration]
|
72,040 |
elementpath.xpath_tokens
|
as_function
|
Wraps the XPath function instance into a standard function.
|
def as_function(self) -> Callable[..., Any]:
"""
Wraps the XPath function instance into a standard function.
"""
def wrapper(*args: XPathFunctionArgType, context: ContextArgType = None) -> Any:
return self.__call__(*args, context=context)
qname = self.name
if self.is_reference():
ref_part = f'#{self.nargs}'
else:
ref_part = ''
if qname is None:
name = f'<anonymous-function{ref_part}>'
else:
name = f'<{qname.qname}{ref_part}>'
wrapper.__name__ = name
wrapper.__qualname__ = wrapper.__qualname__[:-7] + name
return wrapper
|
(self) -> Callable[..., Any]
|
72,041 |
elementpath.tdop
|
as_name
|
Returns a new '(name)' token for resolving ambiguous states.
|
def as_name(self) -> 'Token[TK]':
"""Returns a new '(name)' token for resolving ambiguous states."""
assert self.parser.name_pattern.match(self.symbol) is not None, \
"Token symbol is not compatible with the name pattern!"
token = self.parser.symbol_table['(name)'](self.parser, self.symbol)
token.span = self.span
return token
|
(self) -> elementpath.tdop.Token[~TK]
|
72,042 |
elementpath.xpath_tokens
|
atomization
|
Helper method for value atomization of a sequence.
Ref: https://www.w3.org/TR/xpath31/#id-atomization
:param context: the XPath dynamic context.
|
def atomization(self, context: ContextArgType = None) \
-> Iterator[AtomicValueType]:
"""
Helper method for value atomization of a sequence.
Ref: https://www.w3.org/TR/xpath31/#id-atomization
:param context: the XPath dynamic context.
"""
for item in self.iter_flatten(context):
if isinstance(item, XPathNode):
try:
value = item.typed_value
except (TypeError, ValueError) as err:
raise self.error('XPDY0050', str(err))
else:
if value is None:
msg = f"argument node {item!r} does not have a typed value"
raise self.error('FOTY0012', msg)
elif isinstance(value, list):
yield from value
else:
yield value
elif isinstance(item, XPathFunction) and not isinstance(item, XPathArray):
raise self.error('FOTY0013', f"{item.label!r} has no typed value")
elif isinstance(item, AnyAtomicType):
yield cast(AtomicValueType, item)
else:
msg = f"sequence item {item!r} is not appropriate for the context"
raise self.error('XPTY0004', msg)
|
(self, context: Optional[elementpath.xpath_context.XPathContext] = None) -> Iterator[Union[str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType]]
|
72,043 |
elementpath.xpath_tokens
|
bind_namespace
|
Bind a token with a namespace. The token has to be a name, a name wildcard,
a function or a constructor, otherwise a syntax error is raised. Functions
and constructors must be limited to its namespaces.
|
def bind_namespace(self, namespace: str) -> None:
"""
Bind a token with a namespace. The token has to be a name, a name wildcard,
a function or a constructor, otherwise a syntax error is raised. Functions
and constructors must be limited to its namespaces.
"""
if self.symbol in ('(name)', '*') or isinstance(self, ProxyToken):
pass
elif namespace == self.parser.function_namespace:
if self.label != 'function':
msg = "a name, a wildcard or a function expected"
raise self.wrong_syntax(msg, code='XPST0017')
elif isinstance(self.label, MultiLabel):
self.label = 'function'
elif namespace == XSD_NAMESPACE:
if self.label != 'constructor function':
msg = "a name, a wildcard or a constructor function expected"
raise self.wrong_syntax(msg, code='XPST0017')
elif isinstance(self.label, MultiLabel):
self.label = 'constructor function'
elif namespace == XPATH_MATH_FUNCTIONS_NAMESPACE:
if self.label != 'math function':
msg = "a name, a wildcard or a math function expected"
raise self.wrong_syntax(msg, code='XPST0017')
elif isinstance(self.label, MultiLabel):
self.label = 'math function'
elif not self.label.endswith('function'):
msg = "a name, a wildcard or a function expected"
raise self.wrong_syntax(msg, code='XPST0017')
elif self.namespace and namespace != self.namespace:
msg = "unmatched namespace"
raise self.wrong_syntax(msg, code='XPST0017')
self.namespace = namespace
|
(self, namespace: str) -> NoneType
|
72,044 |
elementpath.xpath_tokens
|
boolean_value
|
The effective boolean value, as computed by fn:boolean().
|
def boolean_value(self, obj: Any) -> bool:
"""
The effective boolean value, as computed by fn:boolean().
"""
if isinstance(obj, list):
if not obj:
return False
elif isinstance(obj[0], XPathNode):
return True
elif len(obj) > 1:
message = "effective boolean value is not defined for a sequence " \
"of two or more items not starting with an XPath node."
raise self.error('FORG0006', message)
else:
obj = obj[0]
if isinstance(obj, (int, str, UntypedAtomic, AnyURI)): # Include bool
return bool(obj)
elif isinstance(obj, (float, Decimal)):
return False if math.isnan(obj) else bool(obj)
elif obj is None:
return False
elif isinstance(obj, XPathNode):
return True
else:
message = "effective boolean value is not defined for {!r}.".format(type(obj))
raise self.error('FORG0006', message)
|
(self, obj: Any) -> bool
|
72,045 |
elementpath.xpath_tokens
|
cast_to_double
|
Cast a value to xs:double.
|
def cast_to_double(self, value: Union[SupportsFloat, str]) -> float:
"""Cast a value to xs:double."""
try:
if self.parser.xsd_version == '1.0':
return cast(float, DoubleProxy10(value))
return cast(float, DoubleProxy(value))
except ValueError as err:
raise self.error('FORG0001', str(err)) # str or UntypedAtomic
|
(self, value: Union[SupportsFloat, str]) -> float
|
72,046 |
elementpath.xpath_tokens
|
cast_to_primitive_type
| null |
def cast_to_primitive_type(self, obj: Any, type_name: str) -> Any:
if obj is None or not type_name.startswith('xs:') or type_name.count(':') != 1:
return obj
type_name = type_name[3:].rstrip('+*?')
token = cast(XPathConstructor, self.parser.symbol_table[type_name](self.parser))
def cast_value(v: Any) -> Any:
try:
if isinstance(v, (UntypedAtomic, AnyURI)):
return token.cast(v)
elif isinstance(v, float) or \
isinstance(v, xsd10_atomic_types[XSD_DECIMAL]):
if type_name in ('double', 'float'):
return token.cast(v)
except (ValueError, TypeError):
return v
else:
return v
if isinstance(obj, list):
return [cast_value(x) for x in obj]
else:
return cast_value(obj)
|
(self, obj: Any, type_name: str) -> Any
|
72,047 |
elementpath.xpath_tokens
|
cast_to_qname
|
Cast a prefixed qname string to a QName object.
|
def cast_to_qname(self, qname: str) -> QName:
"""Cast a prefixed qname string to a QName object."""
try:
if ':' not in qname:
return QName(self.parser.namespaces.get(''), qname.strip())
pfx, _ = qname.strip().split(':')
return QName(self.parser.namespaces[pfx], qname)
except ValueError:
msg = 'invalid value {!r} for an xs:QName'.format(qname.strip())
raise self.error('FORG0001', msg)
except KeyError as err:
raise self.error('FONS0004', 'no namespace found for prefix {}'.format(err))
|
(self, qname: str) -> elementpath.datatypes.qname.QName
|
72,048 |
elementpath.xpath_tokens
|
check_arguments_number
|
Check the number of arguments against function arity.
|
def check_arguments_number(self, nargs: int) -> None:
"""Check the number of arguments against function arity."""
if self.nargs is None or self.nargs == nargs:
pass
elif isinstance(self.nargs, tuple):
if nargs < self.nargs[0]:
raise self.error('XPTY0004', "missing required arguments")
elif self.nargs[1] is not None and nargs > self.nargs[1]:
raise self.error('XPTY0004', "too many arguments")
elif self.nargs > nargs:
raise self.error('XPTY0004', "missing required arguments")
else:
raise self.error('XPTY0004', "too many arguments")
|
(self, nargs: int) -> NoneType
|
72,051 |
elementpath.xpath_tokens
|
data_value
|
The typed value, as computed by fn:data() on each item.
Returns an instance of UntypedAtomic for untyped data.
https://www.w3.org/TR/xpath20/#dt-typed-value
|
def data_value(self, obj: Any) -> Optional[AtomicValueType]:
"""
The typed value, as computed by fn:data() on each item.
Returns an instance of UntypedAtomic for untyped data.
https://www.w3.org/TR/xpath20/#dt-typed-value
"""
if obj is None:
return None
elif isinstance(obj, XPathNode):
try:
return obj.typed_value
except (TypeError, ValueError) as err:
raise self.error('XPDY0050', str(err))
elif isinstance(obj, XPathFunction):
if not isinstance(obj, XPathArray):
raise self.error('FOTY0013', f"{obj.label!r} has no typed value")
values = [self.data_value(x) for x in obj.iter_flatten()]
return values[0] if len(values) == 1 else None
else:
return cast(AtomicValueType, obj)
|
(self, obj: Any) -> Union[str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType, NoneType]
|
72,052 |
elementpath.xpath_tokens
|
error
| null |
def error(self, code: Union[str, QName],
message_or_error: Union[None, str, Exception] = None) -> ElementPathError:
return xpath_error(code, message_or_error, self, self.parser.namespaces)
|
(self, code: Union[str, elementpath.datatypes.qname.QName], message_or_error: Union[NoneType, str, Exception] = None) -> elementpath.exceptions.ElementPathError
|
72,053 |
elementpath.xpath_tokens
|
evaluate
|
Evaluate default method for XPath tokens.
:param context: The XPath dynamic context.
|
def evaluate(self, context: ContextArgType = None) -> Any:
"""
Evaluate default method for XPath tokens.
:param context: The XPath dynamic context.
"""
return [x for x in self.select(context)]
|
(self, context: Optional[elementpath.xpath_context.XPathContext] = None) -> Any
|
72,054 |
elementpath.xpath_tokens
|
expected
| null |
def expected(self, *symbols: str,
message: Optional[str] = None,
code: str = 'XPST0003') -> None:
if symbols and self.symbol not in symbols:
raise self.wrong_syntax(message, code)
|
(self, *symbols: str, message: Optional[str] = None, code: str = 'XPST0003') -> NoneType
|
72,056 |
elementpath.xpath_tokens
|
get_absolute_uri
|
Obtains an absolute URI from the argument and the static context.
:param uri: a string representing a URI.
:param base_uri: an alternative base URI, otherwise the base_uri of the static context is used.
:param as_string: if `True` then returns the URI as a string, otherwise returns the URI as xs:anyURI instance.
:returns: the argument if it's an absolute URI, otherwise returns the URI
obtained by the join o the base_uri of the static context with the
argument. Returns the argument if the base_uri is `None`.
|
def get_absolute_uri(self, uri: str,
base_uri: Optional[str] = None,
as_string: bool = True) -> Union[str, AnyURI]:
"""
Obtains an absolute URI from the argument and the static context.
:param uri: a string representing a URI.
:param base_uri: an alternative base URI, otherwise the base_uri \
of the static context is used.
:param as_string: if `True` then returns the URI as a string, otherwise \
returns the URI as xs:anyURI instance.
:returns: the argument if it's an absolute URI, otherwise returns the URI
obtained by the join o the base_uri of the static context with the
argument. Returns the argument if the base_uri is `None`.
"""
if not base_uri:
base_uri = self.parser.base_uri
uri_parts: urllib.parse.ParseResult = urllib.parse.urlparse(uri)
if uri_parts.scheme or uri_parts.netloc or base_uri is None:
return uri if as_string else AnyURI(uri)
base_uri_parts: urllib.parse.SplitResult = urllib.parse.urlsplit(base_uri)
if base_uri_parts.fragment or not base_uri_parts.scheme and \
not base_uri_parts.netloc and not base_uri_parts.path.startswith('/'):
raise self.error('FORG0002', '{!r} is not suitable as base URI'.format(base_uri))
if uri_parts.path.startswith('/') and base_uri_parts.path not in ('', '/'):
return uri if as_string else AnyURI(uri)
if as_string:
return urllib.parse.urljoin(base_uri, uri)
return AnyURI(urllib.parse.urljoin(base_uri, uri))
|
(self, uri: str, base_uri: Optional[str] = None, as_string: bool = True) -> Union[str, elementpath.datatypes.uri.AnyURI]
|
72,057 |
elementpath.xpath_tokens
|
get_argument
|
Get the argument value of a function of constructor token. A zero length sequence is
converted to a `None` value. If the function has no argument returns the context's
item if the dynamic context is not `None`.
:param context: the dynamic context.
:param index: an index for select the argument to be got, the first for default.
:param required: if set to `True` missing or empty sequence arguments are not allowed.
:param default_to_context: if set to `True` then the item of the dynamic context is returned when the argument is missing.
:param default: the default value returned in case the argument is an empty sequence. If not provided returns `None`.
:param cls: if a type is provided performs a type checking on item.
:param promote: a class or a tuple of classes that are promoted to `cls` class.
|
def get_argument(self, context: ContextArgType,
index: int = 0,
required: bool = False,
default_to_context: bool = False,
default: Optional[AtomicValueType] = None,
cls: Optional[Type[Any]] = None,
promote: Optional[ClassCheckType] = None) -> Any:
"""
Get the argument value of a function of constructor token. A zero length sequence is
converted to a `None` value. If the function has no argument returns the context's
item if the dynamic context is not `None`.
:param context: the dynamic context.
:param index: an index for select the argument to be got, the first for default.
:param required: if set to `True` missing or empty sequence arguments are not allowed.
:param default_to_context: if set to `True` then the item of the dynamic context is \
returned when the argument is missing.
:param default: the default value returned in case the argument is an empty sequence. \
If not provided returns `None`.
:param cls: if a type is provided performs a type checking on item.
:param promote: a class or a tuple of classes that are promoted to `cls` class.
"""
item: Union[None, ElementProtocol, DocumentProtocol,
XPathNode, AnyAtomicType, XPathFunction]
try:
token = self._items[index]
except IndexError:
if default_to_context:
if context is None:
raise self.missing_context() from None
item = context.item if context.item is not None else context.root
elif isinstance(context, XPathSchemaContext):
return default
elif required:
msg = "missing %s argument" % ordinal(index + 1)
raise self.error('XPST0017', msg) from None
else:
return default
else:
if isinstance(token, XPathFunction) and token.is_reference():
return token # It's a function reference
item = None
for k, result in enumerate(token.select(copy(context))):
if k == 0:
item = result
elif self.parser.compatibility_mode:
break
elif isinstance(context, XPathSchemaContext):
# Multiple schema nodes are ignored but do not raise. The target
# of schema context selection is XSD type association and multiple
# node coherency is already checked at schema level.
break
else:
msg = "a sequence of more than one item is not allowed as argument"
raise self.error('XPTY0004', msg)
else:
if item is None:
if not required or isinstance(context, XPathSchemaContext):
return default
ord_arg = ordinal(index + 1)
msg = "A not empty sequence required for {} argument"
raise self.error('XPTY0004', msg.format(ord_arg))
if cls is not None:
return self.validated_value(item, cls, promote, index)
return item
|
(self, context: Optional[elementpath.xpath_context.XPathContext], index: int = 0, required: bool = False, default_to_context: bool = False, default: Union[str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType, NoneType] = None, cls: Optional[Type[Any]] = None, promote: Union[Type[Any], Tuple[Type[Any], ...], NoneType] = None) -> Any
|
72,058 |
elementpath.xpath_tokens
|
get_argument_tokens
|
Builds and returns the argument tokens list, expanding the comma tokens.
|
def get_argument_tokens(self) -> List['XPathToken']:
"""
Builds and returns the argument tokens list, expanding the comma tokens.
"""
tk = self
tokens = []
while True:
if tk.symbol == ',':
tokens.append(tk[1])
tk = tk[0]
else:
tokens.append(tk)
return tokens[::-1]
|
(self) -> List[elementpath.xpath_tokens.XPathToken]
|
72,059 |
elementpath.xpath_tokens
|
get_atomized_operand
|
Get the atomized value for an XPath operator.
:param context: the XPath dynamic context.
:return: the atomized value of a single length sequence or `None` if the sequence is empty.
|
def get_atomized_operand(self, context: ContextArgType = None) \
-> Optional[AtomicValueType]:
"""
Get the atomized value for an XPath operator.
:param context: the XPath dynamic context.
:return: the atomized value of a single length sequence or `None` if the sequence is empty.
"""
selector = iter(self.atomization(context))
try:
value = next(selector)
except StopIteration:
return None
else:
item = getattr(context, 'item', None)
try:
next(selector)
except StopIteration:
if isinstance(value, UntypedAtomic):
value = str(value)
if not isinstance(context, XPathSchemaContext) and \
item is not None and \
self.xsd_types and \
isinstance(value, str):
xsd_type = self.get_xsd_type(item)
if xsd_type is None or xsd_type.name in _XSD_SPECIAL_TYPES:
pass
else:
try:
value = xsd_type.decode(value)
except (TypeError, ValueError):
msg = "Type {!r} is not appropriate for the context"
raise self.error('XPTY0004', msg.format(type(value)))
return value
else:
msg = "atomized operand is a sequence of length greater than one"
raise self.error('XPTY0004', msg)
|
(self, context: Optional[elementpath.xpath_context.XPathContext] = None) -> Union[str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType, NoneType]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.