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,684 |
wtforms_components.fields.passive_hidden
|
PassiveHiddenField
|
HiddenField that does not populate obj values.
|
class PassiveHiddenField(HiddenField):
"""
HiddenField that does not populate obj values.
"""
def populate_obj(self, obj, name):
pass
|
(*args, **kwargs)
|
71,694 |
wtforms_components.fields.passive_hidden
|
populate_obj
| null |
def populate_obj(self, obj, name):
pass
|
(self, obj, name)
|
71,701 |
wtforms_components.widgets
|
ReadOnlyWidgetProxy
| null |
class ReadOnlyWidgetProxy(object):
def __init__(self, widget):
self.widget = widget
def __getattr__(self, name):
return getattr(self.widget, name)
def __call__(self, field, **kwargs):
kwargs.setdefault('readonly', True)
# Some html elements also need disabled attribute to achieve the
# expected UI behaviour.
kwargs.setdefault('disabled', True)
return self.widget(field, **kwargs)
|
(widget)
|
71,702 |
wtforms_components.widgets
|
__call__
| null |
def __call__(self, field, **kwargs):
kwargs.setdefault('readonly', True)
# Some html elements also need disabled attribute to achieve the
# expected UI behaviour.
kwargs.setdefault('disabled', True)
return self.widget(field, **kwargs)
|
(self, field, **kwargs)
|
71,703 |
wtforms_components.widgets
|
__getattr__
| null |
def __getattr__(self, name):
return getattr(self.widget, name)
|
(self, name)
|
71,704 |
wtforms_components.widgets
|
__init__
| null |
def __init__(self, widget):
self.widget = widget
|
(self, widget)
|
71,705 |
wtforms_components.fields.html5
|
SearchField
| null |
class SearchField(SearchField):
widget = SearchInput()
|
(*args, **kwargs)
|
71,722 |
wtforms_components.fields.select
|
SelectField
|
Add support of ``optgroup``'s' to default WTForms' ``SelectField`` class.
So, next choices would be supported as well::
(
('Fruits', (
('apple', 'Apple'),
('peach', 'Peach'),
('pear', 'Pear')
)),
('Vegetables', (
('cucumber', 'Cucumber'),
('potato', 'Potato'),
('tomato', 'Tomato'),
))
)
Also supports lazy choices (callables that return an iterable)
|
class SelectField(_SelectField):
"""
Add support of ``optgroup``'s' to default WTForms' ``SelectField`` class.
So, next choices would be supported as well::
(
('Fruits', (
('apple', 'Apple'),
('peach', 'Peach'),
('pear', 'Pear')
)),
('Vegetables', (
('cucumber', 'Cucumber'),
('potato', 'Potato'),
('tomato', 'Tomato'),
))
)
Also supports lazy choices (callables that return an iterable)
"""
widget = SelectWidget()
def __init__(self, *args, **kwargs):
choices = kwargs.pop('choices', None)
if callable(choices):
super(SelectField, self).__init__(*args, **kwargs)
self.choices = copy(choices)
else:
super(SelectField, self).__init__(*args, choices=choices, **kwargs)
def iter_choices(self):
"""
We should update how choices are iter to make sure that value from
internal list or tuple should be selected.
"""
for value, label in self.concrete_choices:
yield (value, label, (self.coerce, self.data))
@property
def concrete_choices(self):
if callable(self.choices):
return self.choices()
return self.choices
@property
def choice_values(self):
values = []
for value, label in self.concrete_choices:
if isinstance(label, (list, tuple)):
for subvalue, sublabel in label:
values.append(subvalue)
else:
values.append(value)
return values
def pre_validate(self, form):
"""
Don't forget to validate also values from embedded lists.
"""
values = self.choice_values
if (self.data is None and u'' in values) or self.data in values:
return True
raise ValidationError(self.gettext(u'Not a valid choice'))
|
(*args, **kwargs)
|
71,725 |
wtforms_components.fields.select
|
__init__
| null |
def __init__(self, *args, **kwargs):
choices = kwargs.pop('choices', None)
if callable(choices):
super(SelectField, self).__init__(*args, **kwargs)
self.choices = copy(choices)
else:
super(SelectField, self).__init__(*args, choices=choices, **kwargs)
|
(self, *args, **kwargs)
|
71,726 |
wtforms.fields.choices
|
__iter__
| null |
def __iter__(self):
opts = dict(
widget=self.option_widget,
validators=self.validators,
name=self.name,
render_kw=self.render_kw,
_form=None,
_meta=self.meta,
)
for i, choice in enumerate(self.iter_choices()):
if len(choice) == 4:
value, label, checked, render_kw = choice
else:
value, label, checked = choice
render_kw = {}
opt = self._Option(
label=label, id="%s-%d" % (self.id, i), **opts, **render_kw
)
opt.process(None, value)
opt.checked = checked
yield opt
|
(self)
|
71,729 |
wtforms.fields.choices
|
_choices_generator
| null |
def _choices_generator(self, choices):
if not choices:
_choices = []
elif isinstance(choices[0], (list, tuple)):
_choices = choices
else:
_choices = zip(choices, choices)
for value, label, *other_args in _choices:
selected = self.coerce(value) == self.data
render_kw = other_args[0] if len(other_args) else {}
yield (value, label, selected, render_kw)
|
(self, choices)
|
71,732 |
wtforms.fields.choices
|
has_groups
| null |
def has_groups(self):
return isinstance(self.choices, dict)
|
(self)
|
71,733 |
wtforms_components.fields.select
|
iter_choices
|
We should update how choices are iter to make sure that value from
internal list or tuple should be selected.
|
def iter_choices(self):
"""
We should update how choices are iter to make sure that value from
internal list or tuple should be selected.
"""
for value, label in self.concrete_choices:
yield (value, label, (self.coerce, self.data))
|
(self)
|
71,734 |
wtforms.fields.choices
|
iter_groups
| null |
def iter_groups(self):
if isinstance(self.choices, dict):
for label, choices in self.choices.items():
yield (label, self._choices_generator(choices))
|
(self)
|
71,738 |
wtforms_components.fields.select
|
pre_validate
|
Don't forget to validate also values from embedded lists.
|
def pre_validate(self, form):
"""
Don't forget to validate also values from embedded lists.
"""
values = self.choice_values
if (self.data is None and u'' in values) or self.data in values:
return True
raise ValidationError(self.gettext(u'Not a valid choice'))
|
(self, form)
|
71,740 |
wtforms.fields.choices
|
process_data
| null |
def process_data(self, value):
try:
# If value is None, don't coerce to a value
self.data = self.coerce(value) if value is not None else None
except (ValueError, TypeError):
self.data = None
|
(self, value)
|
71,741 |
wtforms.fields.choices
|
process_formdata
| null |
def process_formdata(self, valuelist):
if not valuelist:
return
try:
self.data = self.coerce(valuelist[0])
except ValueError as exc:
raise ValueError(self.gettext("Invalid Choice: could not coerce.")) from exc
|
(self, valuelist)
|
71,743 |
wtforms_components.fields.select_multiple
|
SelectMultipleField
|
No different from a normal select field, except this one can take (and
validate) multiple choices. You'll need to specify the HTML `rows`
attribute to the select field when rendering.
|
class SelectMultipleField(SelectField):
"""
No different from a normal select field, except this one can take (and
validate) multiple choices. You'll need to specify the HTML `rows`
attribute to the select field when rendering.
"""
widget = SelectWidget(multiple=True)
def process_data(self, value):
try:
self.data = list(self.coerce(v) for v in value)
except (ValueError, TypeError):
self.data = None
def process_formdata(self, valuelist):
try:
self.data = list(self.coerce(x) for x in valuelist)
except ValueError:
raise ValueError(
self.gettext(
'Invalid choice(s): one or more data inputs '
'could not be coerced'
)
)
def pre_validate(self, form):
if self.data:
values = self.choice_values
for value in self.data:
if value not in values:
raise ValidationError(
self.gettext(
"'%(value)s' is not a valid"
" choice for this field"
) % dict(value=value)
)
|
(*args, **kwargs)
|
71,759 |
wtforms_components.fields.select_multiple
|
pre_validate
| null |
def pre_validate(self, form):
if self.data:
values = self.choice_values
for value in self.data:
if value not in values:
raise ValidationError(
self.gettext(
"'%(value)s' is not a valid"
" choice for this field"
) % dict(value=value)
)
|
(self, form)
|
71,761 |
wtforms_components.fields.select_multiple
|
process_data
| null |
def process_data(self, value):
try:
self.data = list(self.coerce(v) for v in value)
except (ValueError, TypeError):
self.data = None
|
(self, value)
|
71,762 |
wtforms_components.fields.select_multiple
|
process_formdata
| null |
def process_formdata(self, valuelist):
try:
self.data = list(self.coerce(x) for x in valuelist)
except ValueError:
raise ValueError(
self.gettext(
'Invalid choice(s): one or more data inputs '
'could not be coerced'
)
)
|
(self, valuelist)
|
71,764 |
wtforms_components.widgets
|
SelectWidget
|
Add support of choices with ``optgroup`` to the ``Select`` widget.
|
class SelectWidget(_Select):
"""
Add support of choices with ``optgroup`` to the ``Select`` widget.
"""
@classmethod
def render_optgroup(cls, value, label, mixed):
children = []
for item_value, item_label in label:
item_html = cls.render_option(item_value, item_label, mixed)
children.append(item_html)
html = u'<optgroup label="%s">%s</optgroup>'
data = (html_escape(six.text_type(value)), u'\n'.join(children))
return HTMLString(html % data)
@classmethod
def render_option(cls, value, label, mixed):
"""
Render option as HTML tag, but not forget to wrap options into
``optgroup`` tag if ``label`` var is ``list`` or ``tuple``.
"""
if isinstance(label, (list, tuple)):
return cls.render_optgroup(value, label, mixed)
try:
coerce_func, data = mixed
except TypeError:
selected = mixed
else:
if isinstance(data, list) or isinstance(data, tuple):
selected = coerce_func(value) in data
else:
selected = coerce_func(value) == data
options = {'value': value}
if selected:
options['selected'] = True
html = u'<option %s>%s</option>'
data = (html_params(**options), html_escape(six.text_type(label)))
return HTMLString(html % data)
|
(multiple=False)
|
71,765 |
wtforms.widgets.core
|
__call__
| null |
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
if self.multiple:
kwargs["multiple"] = True
flags = getattr(field, "flags", {})
for k in dir(flags):
if k in self.validation_attrs and k not in kwargs:
kwargs[k] = getattr(flags, k)
html = ["<select %s>" % html_params(name=field.name, **kwargs)]
if field.has_groups():
for group, choices in field.iter_groups():
html.append("<optgroup %s>" % html_params(label=group))
for choice in choices:
if len(choice) == 4:
val, label, selected, render_kw = choice
else:
warnings.warn(
"'iter_groups' is expected to return 4 items tuple since "
"wtforms 3.1, this will be mandatory in wtforms 3.2",
DeprecationWarning,
stacklevel=2,
)
val, label, selected = choice
render_kw = {}
html.append(self.render_option(val, label, selected, **render_kw))
html.append("</optgroup>")
else:
for choice in field.iter_choices():
if len(choice) == 4:
val, label, selected, render_kw = choice
else:
warnings.warn(
"'iter_groups' is expected to return 4 items tuple since "
"wtforms 3.1, this will be mandatory in wtforms 3.2",
DeprecationWarning,
stacklevel=2,
)
val, label, selected = choice
render_kw = {}
html.append(self.render_option(val, label, selected, **render_kw))
html.append("</select>")
return Markup("".join(html))
|
(self, field, **kwargs)
|
71,766 |
wtforms.widgets.core
|
__init__
| null |
def __init__(self, multiple=False):
self.multiple = multiple
|
(self, multiple=False)
|
71,767 |
wtforms_components.fields.split_date_time
|
SplitDateTimeField
| null |
class SplitDateTimeField(FormField):
def __init__(self, label=None, validators=None, separator='-', **kwargs):
FormField.__init__(
self,
datetime_form(kwargs.pop('datetime_form', {})),
label=label,
validators=validators,
separator=separator,
**kwargs
)
def process(self, formdata, data=_unset_value, extra_filters=None):
if data is _unset_value:
try:
data = self.default()
except TypeError:
data = self.default
if data:
obj = Date()
obj.date = data.date()
obj.time = data.time()
else:
obj = None
kwargs = dict()
if extra_filters is not None:
# do not enforce extra_filters=None injection to wtforms<3
kwargs['extra_filters'] = extra_filters
FormField.process(self, formdata, data=obj, **kwargs)
def populate_obj(self, obj, name):
if hasattr(obj, name):
date = self.date.data
hours, minutes = self.time.data.hour, self.time.data.minute
setattr(obj, name, datetime.datetime(
date.year, date.month, date.day, hours, minutes
))
|
(label=None, validators=None, separator='-', **kwargs)
|
71,769 |
wtforms.fields.form
|
__getattr__
| null |
def __getattr__(self, name):
return getattr(self.form, name)
|
(self, name)
|
71,770 |
wtforms.fields.form
|
__getitem__
| null |
def __getitem__(self, name):
return self.form[name]
|
(self, name)
|
71,772 |
wtforms_components.fields.split_date_time
|
__init__
| null |
def __init__(self, label=None, validators=None, separator='-', **kwargs):
FormField.__init__(
self,
datetime_form(kwargs.pop('datetime_form', {})),
label=label,
validators=validators,
separator=separator,
**kwargs
)
|
(self, label=None, validators=None, separator='-', **kwargs)
|
71,773 |
wtforms.fields.form
|
__iter__
| null |
def __iter__(self):
return iter(self.form)
|
(self)
|
71,779 |
wtforms_components.fields.split_date_time
|
populate_obj
| null |
def populate_obj(self, obj, name):
if hasattr(obj, name):
date = self.date.data
hours, minutes = self.time.data.hour, self.time.data.minute
setattr(obj, name, datetime.datetime(
date.year, date.month, date.day, hours, minutes
))
|
(self, obj, name)
|
71,782 |
wtforms_components.fields.split_date_time
|
process
| null |
def process(self, formdata, data=_unset_value, extra_filters=None):
if data is _unset_value:
try:
data = self.default()
except TypeError:
data = self.default
if data:
obj = Date()
obj.date = data.date()
obj.time = data.time()
else:
obj = None
kwargs = dict()
if extra_filters is not None:
# do not enforce extra_filters=None injection to wtforms<3
kwargs['extra_filters'] = extra_filters
FormField.process(self, formdata, data=obj, **kwargs)
|
(self, formdata, data=<unset value>, extra_filters=None)
|
71,784 |
wtforms.fields.core
|
process_formdata
|
Process data received over the wire from a form.
This will be called during form construction with data supplied
through the `formdata` argument.
:param valuelist: A list of strings to process.
|
def process_formdata(self, valuelist):
"""
Process data received over the wire from a form.
This will be called during form construction with data supplied
through the `formdata` argument.
:param valuelist: A list of strings to process.
"""
if valuelist:
self.data = valuelist[0]
|
(self, valuelist)
|
71,785 |
wtforms.fields.form
|
validate
| null |
def validate(self, form, extra_validators=()):
if extra_validators:
raise TypeError(
"FormField does not accept in-line validators, as it"
" gets errors from the enclosed form."
)
return self.form.validate()
|
(self, form, extra_validators=())
|
71,786 |
wtforms_components.fields.html5
|
StringField
| null |
class StringField(_StringField):
widget = TextInput()
|
(*args, **kwargs)
|
71,803 |
wtforms_components.fields.time
|
TimeField
|
A text field which stores a `datetime.time` matching a format.
|
class TimeField(Field):
"""
A text field which stores a `datetime.time` matching a format.
"""
widget = TimeInput()
error_msg = 'Not a valid time.'
def __init__(self, label=None, validators=None, format='%H:%M', **kwargs):
super(TimeField, self).__init__(label, validators, **kwargs)
self.format = format
def _value(self):
if self.raw_data:
return ' '.join(self.raw_data)
elif self.data is not None:
return self.data.strftime(self.format)
else:
return ''
def process_formdata(self, valuelist):
if valuelist:
time_str = ' '.join(valuelist)
try:
self.data = datetime.time(
*time.strptime(time_str, self.format)[3:6]
)
except ValueError:
self.data = None
raise ValueError(self.gettext(self.error_msg))
|
(label=None, validators=None, format='%H:%M', **kwargs)
|
71,806 |
wtforms_components.fields.time
|
__init__
| null |
def __init__(self, label=None, validators=None, format='%H:%M', **kwargs):
super(TimeField, self).__init__(label, validators, **kwargs)
self.format = format
|
(self, label=None, validators=None, format='%H:%M', **kwargs)
|
71,810 |
wtforms_components.fields.time
|
_value
| null |
def _value(self):
if self.raw_data:
return ' '.join(self.raw_data)
elif self.data is not None:
return self.data.strftime(self.format)
else:
return ''
|
(self)
|
71,818 |
wtforms_components.fields.time
|
process_formdata
| null |
def process_formdata(self, valuelist):
if valuelist:
time_str = ' '.join(valuelist)
try:
self.data = datetime.time(
*time.strptime(time_str, self.format)[3:6]
)
except ValueError:
self.data = None
raise ValueError(self.gettext(self.error_msg))
|
(self, valuelist)
|
71,820 |
wtforms_components.validators
|
TimeRange
|
Same as wtforms.validators.NumberRange but validates date.
:param min:
The minimum required value of the time. If not provided, minimum
value will not be checked.
:param max:
The maximum value of the time. If not provided, maximum value
will not be checked.
:param message:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults
are provided depending on the existence of min and max.
|
class TimeRange(BaseDateTimeRange):
"""
Same as wtforms.validators.NumberRange but validates date.
:param min:
The minimum required value of the time. If not provided, minimum
value will not be checked.
:param max:
The maximum value of the time. If not provided, maximum value
will not be checked.
:param message:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults
are provided depending on the existence of min and max.
"""
greater_than_msg = u'Time must be greater than %(min)s.'
less_than_msg = u'Time must be less than %(max)s.'
between_msg = u'Time must be between %(min)s and %(max)s.'
def __init__(self, min=None, max=None, format='%H:%M', message=None):
super(TimeRange, self).__init__(
min=min, max=max, format=format, message=message
)
|
(min=None, max=None, format='%H:%M', message=None)
|
71,822 |
wtforms_components.validators
|
__init__
| null |
def __init__(self, min=None, max=None, format='%H:%M', message=None):
super(TimeRange, self).__init__(
min=min, max=max, format=format, message=message
)
|
(self, min=None, max=None, format='%H:%M', message=None)
|
71,824 |
wtforms_components
|
do_nothing
| null |
def do_nothing(*args, **kwargs):
pass
|
(*args, **kwargs)
|
71,826 |
wtforms_components
|
read_only
| null |
def read_only(field):
field.widget = ReadOnlyWidgetProxy(field.widget)
field.process = do_nothing
field.populate_obj = do_nothing
return field
|
(field)
|
71,829 |
elementpath.schema_proxy
|
AbstractSchemaProxy
|
Abstract base class for defining schema proxies. An implementation can override
initialization type annotations
:param schema: a schema instance compatible with the XsdSchemaProtocol.
:param base_element: the schema element used as base item for static analysis.
|
class AbstractSchemaProxy(metaclass=ABCMeta):
"""
Abstract base class for defining schema proxies. An implementation can override
initialization type annotations
:param schema: a schema instance compatible with the XsdSchemaProtocol.
:param base_element: the schema element used as base item for static analysis.
"""
def __init__(self, schema: XsdSchemaProtocol,
base_element: Optional[XsdElementProtocol] = None) -> None:
if not is_etree_element(schema):
raise ElementPathTypeError(
"argument {!r} is not a compatible schema instance".format(schema)
)
if base_element is not None and not is_etree_element(base_element):
raise ElementPathTypeError(
"argument 'base_element' is not a compatible element instance"
)
self._schema = schema
self._base_element: Optional[XsdElementProtocol] = base_element
def bind_parser(self, parser: XPathParserType) -> None:
"""
Binds a parser instance with schema proxy adding the schema's atomic types constructors.
This method can be redefined in a concrete proxy to optimize schema bindings.
:param parser: a parser instance.
"""
if parser.schema is not self:
parser.schema = self
for xsd_type in self.iter_atomic_types():
if xsd_type.name is not None: # pragma: no cover
parser.schema_constructor(xsd_type.name)
def get_context(self) -> XPathSchemaContext:
"""
Get a context instance for static analysis phase.
:returns: an `XPathSchemaContext` instance.
"""
return XPathSchemaContext(root=self._schema, item=self._base_element)
def find(self, path: str, namespaces: Optional[Dict[str, str]] = None) \
-> Optional[Union[XsdSchemaProtocol, XsdElementProtocol]]:
"""
Find a schema element or attribute using an XPath expression.
:param path: an XPath expression that selects an element or an attribute node.
:param namespaces: an optional mapping from namespace prefix to namespace URI.
:return: The first matching schema component, or ``None`` if there is no match.
"""
return self._schema.find(path, namespaces)
@property
def xsd_version(self) -> str:
"""The XSD version, returns '1.0' or '1.1'."""
return self._schema.xsd_version
def get_type(self, qname: str) -> Optional[XsdTypeProtocol]:
"""
Get the XSD global type from the schema's scope. A concrete implementation must
return an object that supports the protocols `XsdTypeProtocol`, or `None` if
the global type is not found.
:param qname: the fully qualified name of the type to retrieve.
:returns: an object that represents an XSD type or `None`.
"""
xsd_type = self._schema.maps.types.get(qname)
if isinstance(xsd_type, tuple):
return None
return xsd_type
def get_attribute(self, qname: str) -> Optional[XsdAttributeProtocol]:
"""
Get the XSD global attribute from the schema's scope. A concrete implementation must
return an object that supports the protocol `XsdAttributeProtocol`, or `None` if
the global attribute is not found.
:param qname: the fully qualified name of the attribute to retrieve.
:returns: an object that represents an XSD attribute or `None`.
"""
xsd_attribute = self._schema.maps.attributes.get(qname)
if isinstance(xsd_attribute, tuple):
return None
return xsd_attribute
def get_element(self, qname: str) -> Optional[XsdElementProtocol]:
"""
Get the XSD global element from the schema's scope. A concrete implementation must
return an object that supports the protocol `XsdElementProtocol` interface, or
`None` if the global element is not found.
:param qname: the fully qualified name of the element to retrieve.
:returns: an object that represents an XSD element or `None`.
"""
xsd_element = self._schema.maps.elements.get(qname)
if isinstance(xsd_element, tuple):
return None
return xsd_element
def get_substitution_group(self, qname: str) -> Optional[Set[XsdElementProtocol]]:
"""
Get a substitution group. A concrete implementation must returns a list containing
substitution elements or `None` if the substitution group is not found. Moreover each item
of the returned list must be an object that implements the `AbstractXsdElement` interface.
:param qname: the fully qualified name of the substitution group to retrieve.
:returns: a list containing substitution elements or `None`.
"""
return self._schema.maps.substitution_groups.get(qname)
@abstractmethod
def is_instance(self, obj: Any, type_qname: str) -> bool:
"""
Returns `True` if *obj* is an instance of the XSD global type, `False` if not.
:param obj: the instance to be tested.
:param type_qname: the fully qualified name of the type used to test the instance.
"""
@abstractmethod
def cast_as(self, obj: Any, type_qname: str) -> AtomicValueType:
"""
Converts *obj* to the Python type associated with an XSD global type. A concrete
implementation must raises a `ValueError` or `TypeError` in case of a decoding
error or a `KeyError` if the type is not bound to the schema's scope.
:param obj: the instance to be cast.
:param type_qname: the fully qualified name of the type used to convert the instance.
"""
@abstractmethod
def iter_atomic_types(self) -> Iterator[XsdTypeProtocol]:
"""
Returns an iterator for not builtin atomic types defined in the schema's scope. A concrete
implementation must yield objects that implement the protocol `XsdTypeProtocol`.
"""
|
(schema: elementpath.protocols.XsdSchemaProtocol, base_element: Optional[elementpath.protocols.XsdElementProtocol] = None) -> None
|
71,830 |
elementpath.schema_proxy
|
__init__
| null |
def __init__(self, schema: XsdSchemaProtocol,
base_element: Optional[XsdElementProtocol] = None) -> None:
if not is_etree_element(schema):
raise ElementPathTypeError(
"argument {!r} is not a compatible schema instance".format(schema)
)
if base_element is not None and not is_etree_element(base_element):
raise ElementPathTypeError(
"argument 'base_element' is not a compatible element instance"
)
self._schema = schema
self._base_element: Optional[XsdElementProtocol] = base_element
|
(self, schema: elementpath.protocols.XsdSchemaProtocol, base_element: Optional[elementpath.protocols.XsdElementProtocol] = None) -> NoneType
|
71,831 |
elementpath.schema_proxy
|
bind_parser
|
Binds a parser instance with schema proxy adding the schema's atomic types constructors.
This method can be redefined in a concrete proxy to optimize schema bindings.
:param parser: a parser instance.
|
def bind_parser(self, parser: XPathParserType) -> None:
"""
Binds a parser instance with schema proxy adding the schema's atomic types constructors.
This method can be redefined in a concrete proxy to optimize schema bindings.
:param parser: a parser instance.
"""
if parser.schema is not self:
parser.schema = self
for xsd_type in self.iter_atomic_types():
if xsd_type.name is not None: # pragma: no cover
parser.schema_constructor(xsd_type.name)
|
(self, parser: Any) -> NoneType
|
71,832 |
elementpath.schema_proxy
|
cast_as
|
Converts *obj* to the Python type associated with an XSD global type. A concrete
implementation must raises a `ValueError` or `TypeError` in case of a decoding
error or a `KeyError` if the type is not bound to the schema's scope.
:param obj: the instance to be cast.
:param type_qname: the fully qualified name of the type used to convert the instance.
|
@abstractmethod
def cast_as(self, obj: Any, type_qname: str) -> AtomicValueType:
"""
Converts *obj* to the Python type associated with an XSD global type. A concrete
implementation must raises a `ValueError` or `TypeError` in case of a decoding
error or a `KeyError` if the type is not bound to the schema's scope.
:param obj: the instance to be cast.
:param type_qname: the fully qualified name of the type used to convert the instance.
"""
|
(self, obj: Any, type_qname: str) -> Union[str, int, float, decimal.Decimal, bool, elementpath.datatypes.atomic_types.AnyAtomicType]
|
71,833 |
elementpath.schema_proxy
|
find
|
Find a schema element or attribute using an XPath expression.
:param path: an XPath expression that selects an element or an attribute node.
:param namespaces: an optional mapping from namespace prefix to namespace URI.
:return: The first matching schema component, or ``None`` if there is no match.
|
def find(self, path: str, namespaces: Optional[Dict[str, str]] = None) \
-> Optional[Union[XsdSchemaProtocol, XsdElementProtocol]]:
"""
Find a schema element or attribute using an XPath expression.
:param path: an XPath expression that selects an element or an attribute node.
:param namespaces: an optional mapping from namespace prefix to namespace URI.
:return: The first matching schema component, or ``None`` if there is no match.
"""
return self._schema.find(path, namespaces)
|
(self, path: str, namespaces: Optional[Dict[str, str]] = None) -> Union[elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol, NoneType]
|
71,834 |
elementpath.schema_proxy
|
get_attribute
|
Get the XSD global attribute from the schema's scope. A concrete implementation must
return an object that supports the protocol `XsdAttributeProtocol`, or `None` if
the global attribute is not found.
:param qname: the fully qualified name of the attribute to retrieve.
:returns: an object that represents an XSD attribute or `None`.
|
def get_attribute(self, qname: str) -> Optional[XsdAttributeProtocol]:
"""
Get the XSD global attribute from the schema's scope. A concrete implementation must
return an object that supports the protocol `XsdAttributeProtocol`, or `None` if
the global attribute is not found.
:param qname: the fully qualified name of the attribute to retrieve.
:returns: an object that represents an XSD attribute or `None`.
"""
xsd_attribute = self._schema.maps.attributes.get(qname)
if isinstance(xsd_attribute, tuple):
return None
return xsd_attribute
|
(self, qname: str) -> Optional[elementpath.protocols.XsdAttributeProtocol]
|
71,835 |
elementpath.schema_proxy
|
get_context
|
Get a context instance for static analysis phase.
:returns: an `XPathSchemaContext` instance.
|
def get_context(self) -> XPathSchemaContext:
"""
Get a context instance for static analysis phase.
:returns: an `XPathSchemaContext` instance.
"""
return XPathSchemaContext(root=self._schema, item=self._base_element)
|
(self) -> elementpath.xpath_context.XPathSchemaContext
|
71,836 |
elementpath.schema_proxy
|
get_element
|
Get the XSD global element from the schema's scope. A concrete implementation must
return an object that supports the protocol `XsdElementProtocol` interface, or
`None` if the global element is not found.
:param qname: the fully qualified name of the element to retrieve.
:returns: an object that represents an XSD element or `None`.
|
def get_element(self, qname: str) -> Optional[XsdElementProtocol]:
"""
Get the XSD global element from the schema's scope. A concrete implementation must
return an object that supports the protocol `XsdElementProtocol` interface, or
`None` if the global element is not found.
:param qname: the fully qualified name of the element to retrieve.
:returns: an object that represents an XSD element or `None`.
"""
xsd_element = self._schema.maps.elements.get(qname)
if isinstance(xsd_element, tuple):
return None
return xsd_element
|
(self, qname: str) -> Optional[elementpath.protocols.XsdElementProtocol]
|
71,837 |
elementpath.schema_proxy
|
get_substitution_group
|
Get a substitution group. A concrete implementation must returns a list containing
substitution elements or `None` if the substitution group is not found. Moreover each item
of the returned list must be an object that implements the `AbstractXsdElement` interface.
:param qname: the fully qualified name of the substitution group to retrieve.
:returns: a list containing substitution elements or `None`.
|
def get_substitution_group(self, qname: str) -> Optional[Set[XsdElementProtocol]]:
"""
Get a substitution group. A concrete implementation must returns a list containing
substitution elements or `None` if the substitution group is not found. Moreover each item
of the returned list must be an object that implements the `AbstractXsdElement` interface.
:param qname: the fully qualified name of the substitution group to retrieve.
:returns: a list containing substitution elements or `None`.
"""
return self._schema.maps.substitution_groups.get(qname)
|
(self, qname: str) -> Optional[Set[elementpath.protocols.XsdElementProtocol]]
|
71,838 |
elementpath.schema_proxy
|
get_type
|
Get the XSD global type from the schema's scope. A concrete implementation must
return an object that supports the protocols `XsdTypeProtocol`, or `None` if
the global type is not found.
:param qname: the fully qualified name of the type to retrieve.
:returns: an object that represents an XSD type or `None`.
|
def get_type(self, qname: str) -> Optional[XsdTypeProtocol]:
"""
Get the XSD global type from the schema's scope. A concrete implementation must
return an object that supports the protocols `XsdTypeProtocol`, or `None` if
the global type is not found.
:param qname: the fully qualified name of the type to retrieve.
:returns: an object that represents an XSD type or `None`.
"""
xsd_type = self._schema.maps.types.get(qname)
if isinstance(xsd_type, tuple):
return None
return xsd_type
|
(self, qname: str) -> Optional[elementpath.protocols.XsdTypeProtocol]
|
71,839 |
elementpath.schema_proxy
|
is_instance
|
Returns `True` if *obj* is an instance of the XSD global type, `False` if not.
:param obj: the instance to be tested.
:param type_qname: the fully qualified name of the type used to test the instance.
|
@abstractmethod
def is_instance(self, obj: Any, type_qname: str) -> bool:
"""
Returns `True` if *obj* is an instance of the XSD global type, `False` if not.
:param obj: the instance to be tested.
:param type_qname: the fully qualified name of the type used to test the instance.
"""
|
(self, obj: Any, type_qname: str) -> bool
|
71,840 |
elementpath.schema_proxy
|
iter_atomic_types
|
Returns an iterator for not builtin atomic types defined in the schema's scope. A concrete
implementation must yield objects that implement the protocol `XsdTypeProtocol`.
|
@abstractmethod
def iter_atomic_types(self) -> Iterator[XsdTypeProtocol]:
"""
Returns an iterator for not builtin atomic types defined in the schema's scope. A concrete
implementation must yield objects that implement the protocol `XsdTypeProtocol`.
"""
|
(self) -> Iterator[elementpath.protocols.XsdTypeProtocol]
|
71,841 |
elementpath.xpath_nodes
|
AttributeNode
|
A class for processing XPath attribute nodes.
:param name: the attribute name.
:param value: a string value or an XSD attribute when XPath is applied on a schema.
:param parent: the parent element node.
:param position: the position of the node in the document.
:param xsd_type: an optional XSD type associated with the attribute node.
|
class AttributeNode(XPathNode):
"""
A class for processing XPath attribute nodes.
:param name: the attribute name.
:param value: a string value or an XSD attribute when XPath is applied on a schema.
:param parent: the parent element node.
:param position: the position of the node in the document.
:param xsd_type: an optional XSD type associated with the attribute node.
"""
attributes: None
children: None = None
base_uri: None
document_uri: None
namespace_nodes: None
nilled: None
parent: Optional['ElementNode']
kind = 'attribute'
__slots__ = '_name', 'value', 'xsd_type'
def __init__(self,
name: Optional[str], value: Union[str, XsdAttributeProtocol],
parent: Optional['ElementNode'] = None,
position: int = 1,
xsd_type: Optional[XsdTypeProtocol] = None) -> None:
self._name = name
self.value: Union[str, XsdAttributeProtocol] = value
self.parent = parent
self.position = position
self.xsd_type = xsd_type
@property
def is_id(self) -> bool:
return self._name == XML_ID or self.xsd_type is not None and self.xsd_type.is_key()
@property
def is_idrefs(self) -> bool:
if self.xsd_type is None:
return False
root_type = self.xsd_type.root_type
return root_type.name == XSD_IDREF or root_type.name == XSD_IDREFS
@property
def name(self) -> Optional[str]:
return self._name
@property
def type_name(self) -> Optional[str]:
if self.xsd_type is None:
return None
return self.xsd_type.name
@property
def string_value(self) -> str:
if isinstance(self.value, str):
return self.value
return str(get_atomic_value(self.value.type))
@property
def typed_value(self) -> AtomicValueType:
if not isinstance(self.value, str):
return get_atomic_value(self.value.type)
elif self.xsd_type is None or self.xsd_type.name in _XSD_SPECIAL_TYPES:
return UntypedAtomic(self.value)
return cast(AtomicValueType, self.xsd_type.decode(self.value))
def as_item(self) -> Tuple[Optional[str], Union[str, XsdAttributeProtocol]]:
return self._name, self.value
def __repr__(self) -> str:
return '%s(name=%r, value=%r)' % (self.__class__.__name__, self._name, self.value)
@property
def path(self) -> str:
if self.parent is None:
return f'@{self._name}'
return f'{self.parent.path}/@{self._name}'
def is_schema_node(self) -> bool:
return hasattr(self.value, 'name') and hasattr(self.value, 'type')
def match_name(self, name: str, default_namespace: Optional[str] = None) -> bool:
if self._name is None:
return False
elif '*' in name:
return match_wildcard(self._name, name)
else:
return self._name == name
|
(name: Optional[str], value: Any, parent: Optional[elementpath.xpath_nodes.ElementNode] = None, position: int = 1, xsd_type: Optional[elementpath.protocols.XsdTypeProtocol] = None) -> None
|
71,842 |
elementpath.xpath_nodes
|
__init__
| null |
def __init__(self,
name: Optional[str], value: Union[str, XsdAttributeProtocol],
parent: Optional['ElementNode'] = None,
position: int = 1,
xsd_type: Optional[XsdTypeProtocol] = None) -> None:
self._name = name
self.value: Union[str, XsdAttributeProtocol] = value
self.parent = parent
self.position = position
self.xsd_type = xsd_type
|
(self, name: Optional[str], value: Union[str, elementpath.protocols.XsdAttributeProtocol], parent: Optional[elementpath.xpath_nodes.ElementNode] = None, position: int = 1, xsd_type: Optional[elementpath.protocols.XsdTypeProtocol] = None) -> NoneType
|
71,843 |
elementpath.xpath_nodes
|
__repr__
| null |
def __repr__(self) -> str:
return '%s(name=%r, value=%r)' % (self.__class__.__name__, self._name, self.value)
|
(self) -> str
|
71,844 |
elementpath.xpath_nodes
|
as_item
| null |
def as_item(self) -> Tuple[Optional[str], Union[str, XsdAttributeProtocol]]:
return self._name, self.value
|
(self) -> Tuple[Optional[str], Union[str, elementpath.protocols.XsdAttributeProtocol]]
|
71,845 |
elementpath.xpath_nodes
|
is_schema_node
| null |
def is_schema_node(self) -> bool:
return hasattr(self.value, 'name') and hasattr(self.value, 'type')
|
(self) -> bool
|
71,846 |
elementpath.xpath_nodes
|
match_name
| null |
def match_name(self, name: str, default_namespace: Optional[str] = None) -> bool:
if self._name is None:
return False
elif '*' in name:
return match_wildcard(self._name, name)
else:
return self._name == name
|
(self, name: str, default_namespace: Optional[str] = None) -> bool
|
71,847 |
elementpath.xpath_nodes
|
CommentNode
|
A class for processing XPath comment nodes.
:param elem: the wrapped Comment Element.
:param parent: the parent element node.
:param position: the position of the node in the document.
|
class CommentNode(XPathNode):
"""
A class for processing XPath comment nodes.
:param elem: the wrapped Comment 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
name: None
type_name: None
kind = 'comment'
__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 string_value(self) -> str:
return self.elem.text or ''
@property
def typed_value(self) -> str:
return self.elem.text or ''
|
(elem: elementpath.protocols.ElementProtocol, parent: Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode, NoneType] = None, position: int = 1) -> None
|
71,848 |
elementpath.xpath_nodes
|
__init__
| null |
def __init__(self,
elem: ElementProtocol,
parent: Union['ElementNode', 'DocumentNode', None] = None,
position: int = 1) -> None:
self.elem = elem
self.parent = parent
self.position = position
|
(self, elem: elementpath.protocols.ElementProtocol, parent: Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode, NoneType] = None, position: int = 1) -> NoneType
|
71,849 |
elementpath.xpath_nodes
|
__repr__
| null |
def __repr__(self) -> str:
return '%s(elem=%r)' % (self.__class__.__name__, self.elem)
|
(self) -> str
|
71,850 |
elementpath.xpath_nodes
|
is_schema_node
| null |
def is_schema_node(self) -> Optional[bool]:
return None
|
(self) -> Optional[bool]
|
71,851 |
elementpath.xpath_nodes
|
match_name
|
Returns `True` if the argument is matching the name of the node, `False` otherwise.
Raises a ValueError if the argument is used, but it's in a wrong format.
:param name: a fully qualified name, a local name or a wildcard. The accepted wildcard formats are '*', '*:*', '*:local-name' and '{namespace}*'.
:param default_namespace: the default namespace for unprefixed names.
|
def match_name(self, name: str, default_namespace: Optional[str] = None) -> bool:
"""
Returns `True` if the argument is matching the name of the node, `False` otherwise.
Raises a ValueError if the argument is used, but it's in a wrong format.
:param name: a fully qualified name, a local name or a wildcard. The accepted \
wildcard formats are '*', '*:*', '*:local-name' and '{namespace}*'.
:param default_namespace: the default namespace for unprefixed names.
"""
return False
|
(self, name: str, default_namespace: Optional[str] = None) -> bool
|
71,852 |
elementpath.xpath_nodes
|
DocumentNode
|
A class for XPath document nodes.
:param document: the wrapped ElementTree instance.
:param position: the position of the node in the document, usually 1, or 0 for lxml standalone root elements with siblings.
|
class DocumentNode(XPathNode):
"""
A class for XPath document nodes.
:param document: the wrapped ElementTree instance.
:param position: the position of the node in the document, usually 1, \
or 0 for lxml standalone root elements with siblings.
"""
attributes: None = None
children: List[ChildNodeType]
is_id: None
is_idrefs: None
namespace_nodes: None
nilled: None
name: None
parent: None
type_name: None
kind = 'document'
elements: Dict[ElementProtocol, ElementNode]
__slots__ = 'document', 'uri', 'elements', 'children'
def __init__(self, document: DocumentProtocol,
uri: Optional[str] = None,
position: int = 1) -> None:
self.document = document
self.uri = uri
self.parent = None
self.position = position
self.elements = {}
self.children = []
def __repr__(self) -> str:
return '%s(document=%r)' % (self.__class__.__name__, self.document)
@property
def base_uri(self) -> Optional[str]:
return self.uri.strip() if self.uri is not None else None
def getroot(self) -> ElementNode:
for child in self.children:
if isinstance(child, ElementNode):
return child
raise RuntimeError("Missing document root")
def get_element_node(self, elem: ElementProtocol) -> Optional[ElementNode]:
return self.elements.get(elem)
def iter(self) -> Iterator[XPathNode]:
yield self
for e in self.children:
if isinstance(e, ElementNode):
yield from e.iter()
else:
yield e
def iter_document(self) -> Iterator[XPathNode]:
yield self
for e in self.children:
if isinstance(e, ElementNode):
yield from e.iter_document()
else:
yield e
def iter_descendants(self, with_self: bool = True) \
-> Iterator[Union['DocumentNode', ChildNodeType]]:
if with_self:
yield self
for e in self.children:
if isinstance(e, ElementNode):
yield from e.iter_descendants()
else:
yield e
def __getitem__(self, i: Union[int, slice]) -> Union[ChildNodeType, List[ChildNodeType]]:
return self.children[i]
def __len__(self) -> int:
return len(self.children)
def __iter__(self) -> Iterator[ChildNodeType]:
yield from self.children
@property
def value(self) -> DocumentProtocol:
return self.document
@property
def string_value(self) -> str:
if not self.children:
# Fallback for not built documents
root = self.document.getroot()
if root is None:
return ''
return ''.join(etree_iter_strings(root))
return ''.join(child.string_value for child in self.children)
@property
def typed_value(self) -> UntypedAtomic:
return UntypedAtomic(self.string_value)
@property
def document_uri(self) -> Optional[str]:
if self.uri is not None and is_absolute_uri(self.uri):
return self.uri.strip()
else:
return None
def is_extended(self) -> bool:
"""
Returns `True` if the document node cannot be represented with an
ElementTree structure, `False` otherwise.
"""
root = self.document.getroot()
if root is None or not is_etree_element(root):
return True
elif not self.children:
raise RuntimeError("Missing document root")
elif len(self.children) == 1:
return not isinstance(self.children[0], ElementNode)
elif not hasattr(root, 'itersiblings'):
return True # an extended xml.etree.ElementTree structure
elif any(isinstance(x, TextNode) for x in root):
return True
else:
return sum(isinstance(x, ElementNode) for x in root) != 1
@classmethod
def from_element_node(cls, root_node: ElementNode, replace: bool = True) -> 'DocumentNode':
"""
Build a `DocumentNode` from a tree based on an ElementNode.
:param root_node: the root element node.
:param replace: if `True` the root element is replaced by a document node. \
This is usually useful for extended data models (more element children, text nodes).
"""
etree_module_name = root_node.elem.__class__.__module__
etree: ModuleType = import_module(etree_module_name)
assert root_node.elements is not None, "Not a root element node"
assert all(not isinstance(x, SchemaElementNode) for x in root_node.elements)
elements = cast(Dict[ElementProtocol, ElementNode], root_node.elements)
if replace:
document = etree.ElementTree()
if sum(isinstance(x, ElementNode) for x in root_node.children) == 1:
for child in root_node.children:
if isinstance(child, ElementNode):
document = etree.ElementTree(child.elem)
break
document_node = cls(document, root_node.uri, root_node.position)
for child in root_node.children:
document_node.children.append(child)
child.parent = document_node
elements.pop(root_node, None) # type: ignore[call-overload]
document_node.elements = elements
del root_node
return document_node
else:
document = etree.ElementTree(root_node.elem)
document_node = cls(document, root_node.uri, root_node.position - 1)
document_node.children.append(root_node)
root_node.parent = document_node
document_node.elements = elements
return document_node
|
(document: elementpath.protocols.DocumentProtocol, uri: Optional[str] = None, position: int = 1) -> None
|
71,853 |
elementpath.xpath_nodes
|
__getitem__
| null |
def __getitem__(self, i: Union[int, slice]) -> Union[ChildNodeType, List[ChildNodeType]]:
return self.children[i]
|
(self, i: Union[int, slice]) -> Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode, List[Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]]
|
71,854 |
elementpath.xpath_nodes
|
__init__
| null |
def __init__(self, document: DocumentProtocol,
uri: Optional[str] = None,
position: int = 1) -> None:
self.document = document
self.uri = uri
self.parent = None
self.position = position
self.elements = {}
self.children = []
|
(self, document: elementpath.protocols.DocumentProtocol, uri: Optional[str] = None, position: int = 1) -> NoneType
|
71,855 |
elementpath.xpath_nodes
|
__iter__
| null |
def __iter__(self) -> Iterator[ChildNodeType]:
yield from self.children
|
(self) -> Iterator[Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]
|
71,856 |
elementpath.xpath_nodes
|
__len__
| null |
def __len__(self) -> int:
return len(self.children)
|
(self) -> int
|
71,857 |
elementpath.xpath_nodes
|
__repr__
| null |
def __repr__(self) -> str:
return '%s(document=%r)' % (self.__class__.__name__, self.document)
|
(self) -> str
|
71,858 |
elementpath.xpath_nodes
|
get_element_node
| null |
def get_element_node(self, elem: ElementProtocol) -> Optional[ElementNode]:
return self.elements.get(elem)
|
(self, elem: elementpath.protocols.ElementProtocol) -> Optional[elementpath.xpath_nodes.ElementNode]
|
71,859 |
elementpath.xpath_nodes
|
getroot
| null |
def getroot(self) -> ElementNode:
for child in self.children:
if isinstance(child, ElementNode):
return child
raise RuntimeError("Missing document root")
|
(self) -> elementpath.xpath_nodes.ElementNode
|
71,860 |
elementpath.xpath_nodes
|
is_extended
|
Returns `True` if the document node cannot be represented with an
ElementTree structure, `False` otherwise.
|
def is_extended(self) -> bool:
"""
Returns `True` if the document node cannot be represented with an
ElementTree structure, `False` otherwise.
"""
root = self.document.getroot()
if root is None or not is_etree_element(root):
return True
elif not self.children:
raise RuntimeError("Missing document root")
elif len(self.children) == 1:
return not isinstance(self.children[0], ElementNode)
elif not hasattr(root, 'itersiblings'):
return True # an extended xml.etree.ElementTree structure
elif any(isinstance(x, TextNode) for x in root):
return True
else:
return sum(isinstance(x, ElementNode) for x in root) != 1
|
(self) -> bool
|
71,862 |
elementpath.xpath_nodes
|
iter
| null |
def iter(self) -> Iterator[XPathNode]:
yield self
for e in self.children:
if isinstance(e, ElementNode):
yield from e.iter()
else:
yield e
|
(self) -> Iterator[elementpath.xpath_nodes.XPathNode]
|
71,863 |
elementpath.xpath_nodes
|
iter_descendants
| null |
def iter_descendants(self, with_self: bool = True) \
-> Iterator[Union['DocumentNode', ChildNodeType]]:
if with_self:
yield self
for e in self.children:
if isinstance(e, ElementNode):
yield from e.iter_descendants()
else:
yield e
|
(self, with_self: bool = True) -> Iterator[Union[elementpath.xpath_nodes.DocumentNode, elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]
|
71,864 |
elementpath.xpath_nodes
|
iter_document
| null |
def iter_document(self) -> Iterator[XPathNode]:
yield self
for e in self.children:
if isinstance(e, ElementNode):
yield from e.iter_document()
else:
yield e
|
(self) -> Iterator[elementpath.xpath_nodes.XPathNode]
|
71,866 |
elementpath.xpath_nodes
|
ElementNode
|
A class for processing XPath element nodes that uses lazy properties to
diminish the average load for a tree processing.
:param elem: the wrapped Element or XSD schema/element.
:param parent: the parent document node or element node.
:param position: the position of the node in the document.
:param nsmap: an optional mapping from prefix to namespace URI.
:param xsd_type: an optional XSD type associated with the element node.
|
class ElementNode(XPathNode):
"""
A class for processing XPath element nodes that uses lazy properties to
diminish the average load for a tree processing.
:param elem: the wrapped Element or XSD schema/element.
:param parent: the parent document node or element node.
:param position: the position of the node in the document.
:param nsmap: an optional mapping from prefix to namespace URI.
:param xsd_type: an optional XSD type associated with the element node.
"""
children: List[ChildNodeType]
document_uri: None
kind = 'element'
elem: Union[ElementProtocol, SchemaElemType]
nsmap: MutableMapping[Optional[str], str]
elements: Optional[ElementMapType]
_namespace_nodes: Optional[List['NamespaceNode']]
_attributes: Optional[List['AttributeNode']]
uri: Optional[str] = None
__slots__ = 'nsmap', 'elem', 'xsd_type', 'elements', \
'_namespace_nodes', '_attributes', 'children', '__dict__'
def __init__(self,
elem: Union[ElementProtocol, SchemaElemType],
parent: Optional[Union['ElementNode', 'DocumentNode']] = None,
position: int = 1,
nsmap: Optional[MutableMapping[Any, str]] = None,
xsd_type: Optional[XsdTypeProtocol] = None) -> None:
self.elem = elem
self.parent = parent
self.position = position
self.xsd_type = xsd_type
self.elements = None
self._namespace_nodes = None
self._attributes = None
self.children = []
if nsmap is not None:
self.nsmap = nsmap
else:
try:
self.nsmap = cast(Dict[Any, str], getattr(elem, 'nsmap'))
except AttributeError:
self.nsmap = {}
def __repr__(self) -> str:
return '%s(elem=%r)' % (self.__class__.__name__, self.elem)
def __getitem__(self, i: Union[int, slice]) -> Union[ChildNodeType, List[ChildNodeType]]:
return self.children[i]
def __len__(self) -> int:
return len(self.children)
def __iter__(self) -> Iterator[ChildNodeType]:
yield from self.children
@property
def value(self) -> Union[ElementProtocol, SchemaElemType]:
return self.elem
@property
def is_id(self) -> bool:
return False
@property
def is_idrefs(self) -> bool:
return False
@property
def name(self) -> str:
return self.elem.tag
@property
def type_name(self) -> Optional[str]:
if self.xsd_type is None:
return None
return self.xsd_type.name
@property
def base_uri(self) -> Optional[str]:
base_uri = self.elem.get(XML_BASE)
if isinstance(base_uri, str):
base_uri = base_uri.strip()
elif base_uri is not None:
base_uri = ''
elif self.uri is not None:
base_uri = self.uri.strip()
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 nilled(self) -> bool:
return self.elem.get(XSI_NIL) in ('true', '1')
@property
def string_value(self) -> str:
if self.xsd_type is not None and self.xsd_type.is_element_only():
# Element-only text content is normalized
return ''.join(etree_iter_strings(self.elem, normalize=True))
return ''.join(etree_iter_strings(self.elem))
@property
def typed_value(self) -> Optional[AtomicValueType]:
if self.xsd_type is None or \
self.xsd_type.name in _XSD_SPECIAL_TYPES or \
self.xsd_type.has_mixed_content():
return UntypedAtomic(''.join(etree_iter_strings(self.elem)))
elif self.xsd_type.is_element_only() or self.xsd_type.is_empty():
return None
elif self.elem.get(XSI_NIL) and getattr(self.xsd_type.parent, 'nillable', None):
return None
if self.elem.text is not None:
value = self.xsd_type.decode(self.elem.text)
elif self.elem.get(XSI_NIL) in ('1', 'true'):
return ''
else:
value = self.xsd_type.decode('')
return cast(Optional[AtomicValueType], value)
@property
def namespace_nodes(self) -> List['NamespaceNode']:
if self._namespace_nodes is None:
# Lazy generation of namespace nodes of the element
position = self.position + 1
self._namespace_nodes = [NamespaceNode('xml', XML_NAMESPACE, self, position)]
position += 1
if self.nsmap:
for pfx, uri in self.nsmap.items():
if pfx != 'xml':
self._namespace_nodes.append(NamespaceNode(pfx, uri, self, position))
position += 1
return self._namespace_nodes
@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, cast(str, value), self, pos)
for pos, (name, value) in enumerate(self.elem.attrib.items(), position)
]
return self._attributes
@property
def path(self) -> str:
"""Returns an absolute path for the node."""
path = []
item: Any = self
while True:
if isinstance(item, ElementNode):
path.append(item.elem.tag)
item = item.parent
if item is None:
return '/{}'.format('/'.join(reversed(path)))
def is_schema_node(self) -> bool:
return hasattr(self.elem, 'name') and hasattr(self.elem, 'type')
is_schema_element = is_schema_node
def match_name(self, name: str, default_namespace: Optional[str] = None) -> bool:
if '*' in name:
return match_wildcard(self.elem.tag, name)
elif not name:
return not self.elem.tag
elif hasattr(self.elem, 'type'):
return cast(XsdElementProtocol, self.elem).is_matching(name, default_namespace)
elif name[0] == '{' or default_namespace is None:
return self.elem.tag == name
if None in self.nsmap:
default_namespace = self.nsmap[None] # lxml element in-scope namespaces
if default_namespace:
return self.elem.tag == '{%s}%s' % (default_namespace, name)
return self.elem.tag == name
def get_element_node(self, elem: Union[ElementProtocol, SchemaElemType]) \
-> Optional['ElementNode']:
if self.elements is not None:
return self.elements.get(elem)
# Fallback if there is not the map of elements but do not expand lazy elements
for node in self.iter():
if isinstance(node, ElementNode) and elem is node.elem:
return node
else:
return None
def iter(self) -> Iterator[XPathNode]:
# Iterate the tree not including the not built lazy components.
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
while True:
for child in children:
yield 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_document(self) -> Iterator[XPathNode]:
# Iterate the tree but building lazy components.
# Rarely used, don't need optimization.
yield self
yield from self.namespace_nodes
yield from self.attributes
for child in self:
if isinstance(child, ElementNode):
yield from child.iter()
else:
yield child
def iter_descendants(self, with_self: bool = True) -> Iterator[ChildNodeType]:
if with_self:
yield self
iterators: List[Any] = []
children: Iterator[Any] = iter(self.children)
while True:
for child in children:
yield child
if isinstance(child, ElementNode) and child.children:
iterators.append(children)
children = iter(child.children)
break
else:
try:
children = iterators.pop()
except IndexError:
return
|
(elem: Union[elementpath.protocols.ElementProtocol, 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,868 |
elementpath.xpath_nodes
|
__init__
| null |
def __init__(self,
elem: Union[ElementProtocol, SchemaElemType],
parent: Optional[Union['ElementNode', 'DocumentNode']] = None,
position: int = 1,
nsmap: Optional[MutableMapping[Any, str]] = None,
xsd_type: Optional[XsdTypeProtocol] = None) -> None:
self.elem = elem
self.parent = parent
self.position = position
self.xsd_type = xsd_type
self.elements = None
self._namespace_nodes = None
self._attributes = None
self.children = []
if nsmap is not None:
self.nsmap = nsmap
else:
try:
self.nsmap = cast(Dict[Any, str], getattr(elem, 'nsmap'))
except AttributeError:
self.nsmap = {}
|
(self, elem: Union[elementpath.protocols.ElementProtocol, elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol], parent: Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.DocumentNode, NoneType] = None, position: int = 1, nsmap: Optional[MutableMapping[Any, str]] = None, xsd_type: Optional[elementpath.protocols.XsdTypeProtocol] = None) -> NoneType
|
71,872 |
elementpath.xpath_nodes
|
get_element_node
| null |
def get_element_node(self, elem: Union[ElementProtocol, SchemaElemType]) \
-> Optional['ElementNode']:
if self.elements is not None:
return self.elements.get(elem)
# Fallback if there is not the map of elements but do not expand lazy elements
for node in self.iter():
if isinstance(node, ElementNode) and elem is node.elem:
return node
else:
return None
|
(self, elem: Union[elementpath.protocols.ElementProtocol, elementpath.protocols.XsdSchemaProtocol, elementpath.protocols.XsdElementProtocol]) -> Optional[elementpath.xpath_nodes.ElementNode]
|
71,873 |
elementpath.xpath_nodes
|
is_schema_node
| null |
def is_schema_node(self) -> bool:
return hasattr(self.elem, 'name') and hasattr(self.elem, 'type')
|
(self) -> bool
|
71,875 |
elementpath.xpath_nodes
|
iter
| null |
def iter(self) -> Iterator[XPathNode]:
# Iterate the tree not including the not built lazy components.
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
while True:
for child in children:
yield 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,876 |
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)
while True:
for child in children:
yield child
if isinstance(child, ElementNode) and 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,877 |
elementpath.xpath_nodes
|
iter_document
| null |
def iter_document(self) -> Iterator[XPathNode]:
# Iterate the tree but building lazy components.
# Rarely used, don't need optimization.
yield self
yield from self.namespace_nodes
yield from self.attributes
for child in self:
if isinstance(child, ElementNode):
yield from child.iter()
else:
yield child
|
(self) -> Iterator[elementpath.xpath_nodes.XPathNode]
|
71,878 |
elementpath.xpath_nodes
|
match_name
| null |
def match_name(self, name: str, default_namespace: Optional[str] = None) -> bool:
if '*' in name:
return match_wildcard(self.elem.tag, name)
elif not name:
return not self.elem.tag
elif hasattr(self.elem, 'type'):
return cast(XsdElementProtocol, self.elem).is_matching(name, default_namespace)
elif name[0] == '{' or default_namespace is None:
return self.elem.tag == name
if None in self.nsmap:
default_namespace = self.nsmap[None] # lxml element in-scope namespaces
if default_namespace:
return self.elem.tag == '{%s}%s' % (default_namespace, name)
return self.elem.tag == name
|
(self, name: str, default_namespace: Optional[str] = None) -> bool
|
71,879 |
elementpath.exceptions
|
ElementPathError
|
Base exception class for elementpath package.
:param message: the message related to the error.
:param code: an optional error code.
:param token: an optional token instance related with the error.
|
class ElementPathError(Exception):
"""
Base exception class for elementpath package.
:param message: the message related to the error.
:param code: an optional error code.
:param token: an optional token instance related with the error.
"""
def __init__(self, message: str,
code: Optional[str] = None,
token: Optional['Token[Any]'] = None) -> None:
super(ElementPathError, self).__init__(message)
self.message = message
self.code = code
self.token = token
def __str__(self) -> str:
if self.token is None or not isinstance(self.token.value, (str, bytes)):
if not self.code:
return self.message
return '[{}] {}'.format(self.code, self.message)
elif not self.code:
return '{1} at line {2}, column {3}: {0}'.format(
self.message, self.token, *self.token.position
)
return '{2} at line {3}, column {4}: [{1}] {0}'.format(
self.message, self.code, self.token, *self.token.position
)
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,880 |
elementpath.exceptions
|
__init__
| null |
def __init__(self, message: str,
code: Optional[str] = None,
token: Optional['Token[Any]'] = None) -> None:
super(ElementPathError, self).__init__(message)
self.message = message
self.code = code
self.token = token
|
(self, message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,881 |
elementpath.exceptions
|
__str__
| null |
def __str__(self) -> str:
if self.token is None or not isinstance(self.token.value, (str, bytes)):
if not self.code:
return self.message
return '[{}] {}'.format(self.code, self.message)
elif not self.code:
return '{1} at line {2}, column {3}: {0}'.format(
self.message, self.token, *self.token.position
)
return '{2} at line {3}, column {4}: [{1}] {0}'.format(
self.message, self.code, self.token, *self.token.position
)
|
(self) -> str
|
71,882 |
elementpath.exceptions
|
ElementPathKeyError
| null |
class ElementPathKeyError(ElementPathError, KeyError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,885 |
elementpath.exceptions
|
ElementPathLocaleError
| null |
class ElementPathLocaleError(ElementPathError, locale.Error):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,888 |
elementpath.exceptions
|
ElementPathNameError
| null |
class ElementPathNameError(ElementPathError, NameError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,891 |
elementpath.exceptions
|
ElementPathOverflowError
| null |
class ElementPathOverflowError(ElementPathError, OverflowError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,894 |
elementpath.exceptions
|
ElementPathRuntimeError
| null |
class ElementPathRuntimeError(ElementPathError, RuntimeError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,897 |
elementpath.exceptions
|
ElementPathSyntaxError
| null |
class ElementPathSyntaxError(ElementPathError, SyntaxError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,900 |
elementpath.exceptions
|
ElementPathTypeError
| null |
class ElementPathTypeError(ElementPathError, TypeError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,903 |
elementpath.exceptions
|
ElementPathValueError
| null |
class ElementPathValueError(ElementPathError, ValueError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,906 |
elementpath.exceptions
|
ElementPathZeroDivisionError
| null |
class ElementPathZeroDivisionError(ElementPathError, ZeroDivisionError):
pass
|
(message: str, code: Optional[str] = None, token: Optional[ForwardRef('Token[Any]')] = None) -> None
|
71,909 |
elementpath.xpath_nodes
|
LazyElementNode
|
A fully lazy element node, slower but better if the node does not
to be used in a document context. The node extends descendants but
does not record positions and a map of elements.
|
class LazyElementNode(ElementNode):
"""
A fully lazy element node, slower but better if the node does not
to be used in a document context. The node extends descendants but
does not record positions and a map of elements.
"""
__slots__ = ()
def __iter__(self) -> Iterator[ChildNodeType]:
if not self.children:
if self.elem.text is not None:
self.children.append(TextNode(self.elem.text, self))
if len(self.elem):
for elem in self.elem:
if not callable(elem.tag):
nsmap = cast(Dict[Any, str], getattr(elem, 'nsmap', self.nsmap))
self.children.append(LazyElementNode(elem, self, nsmap=nsmap))
elif elem.tag.__name__ == 'Comment': # type: ignore[attr-defined]
self.children.append(CommentNode(elem, self))
else:
self.children.append(ProcessingInstructionNode(elem, self))
if elem.tail is not None:
self.children.append(TextNode(elem.tail, self))
yield from self.children
def iter_descendants(self, with_self: bool = True) -> Iterator[ChildNodeType]:
if with_self:
yield self
for child in self:
if isinstance(child, ElementNode):
yield from child.iter_descendants()
else:
yield child
|
(elem: Union[elementpath.protocols.ElementProtocol, 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,912 |
elementpath.xpath_nodes
|
__iter__
| null |
def __iter__(self) -> Iterator[ChildNodeType]:
if not self.children:
if self.elem.text is not None:
self.children.append(TextNode(self.elem.text, self))
if len(self.elem):
for elem in self.elem:
if not callable(elem.tag):
nsmap = cast(Dict[Any, str], getattr(elem, 'nsmap', self.nsmap))
self.children.append(LazyElementNode(elem, self, nsmap=nsmap))
elif elem.tag.__name__ == 'Comment': # type: ignore[attr-defined]
self.children.append(CommentNode(elem, self))
else:
self.children.append(ProcessingInstructionNode(elem, self))
if elem.tail is not None:
self.children.append(TextNode(elem.tail, self))
yield from self.children
|
(self) -> Iterator[Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]
|
71,919 |
elementpath.xpath_nodes
|
iter_descendants
| null |
def iter_descendants(self, with_self: bool = True) -> Iterator[ChildNodeType]:
if with_self:
yield self
for child in self:
if isinstance(child, ElementNode):
yield from child.iter_descendants()
else:
yield child
|
(self, with_self: bool = True) -> Iterator[Union[elementpath.xpath_nodes.TextNode, elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.CommentNode, elementpath.xpath_nodes.ProcessingInstructionNode]]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.