id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
172,678 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
class FilterArgumentError(TemplateRuntimeError):
"""This error is raised if a filter was called with inappropriate
arguments
"""
The provided code snippet includes necessary dependencies for implementing the `do_round` function. Write a Python function `def do_round( value: float, precision: int = 0, method: 'te.Literal["common", "ceil", "floor"]' = "common", ) -> float` to solve the following problem:
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43
Here is the function:
def do_round(
value: float,
precision: int = 0,
method: 'te.Literal["common", "ceil", "floor"]' = "common",
) -> float:
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
If you don't specify a method ``'common'`` is used.
.. sourcecode:: jinja
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If
you need a real integer, pipe it through `int`:
.. sourcecode:: jinja
{{ 42.55|round|int }}
-> 43
"""
if method not in {"common", "ceil", "floor"}:
raise FilterArgumentError("method must be common, ceil or floor")
if method == "common":
return round(value, precision)
func = getattr(math, method)
return t.cast(float, func(value * (10**precision)) / (10**precision)) | Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 |
172,679 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def ignore_case(value: V) -> V:
"""For use as a postprocessor for :func:`make_attrgetter`. Converts strings
to lowercase and returns other types as-is."""
if isinstance(value, str):
return t.cast(V, value.lower())
return value
def make_attrgetter(
environment: "Environment",
attribute: t.Optional[t.Union[str, int]],
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
default: t.Optional[t.Any] = None,
) -> t.Callable[[t.Any], t.Any]:
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
parts = _prepare_attribute_parts(attribute)
def attrgetter(item: t.Any) -> t.Any:
for part in parts:
item = environment.getitem(item, part)
if default is not None and isinstance(item, Undefined):
item = default
if postprocess is not None:
item = postprocess(item)
return item
return attrgetter
class _GroupTuple(t.NamedTuple):
grouper: t.Any
list: t.List
# Use the regular tuple repr to hide this subclass if users print
# out the value during debugging.
def __repr__(self) -> str:
return tuple.__repr__(self)
def __str__(self) -> str:
return tuple.__str__(self)
def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ...
def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ...
The provided code snippet includes necessary dependencies for implementing the `sync_do_groupby` function. Write a Python function `def sync_do_groupby( environment: "Environment", value: "t.Iterable[V]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, ) -> "t.List[_GroupTuple]"` to solve the following problem:
Group a sequence of objects by an attribute using Python's :func:`itertools.groupby`. The attribute can use dot notation for nested access, like ``"address.city"``. Unlike Python's ``groupby``, the values are sorted first so only one group is returned for each unique value. For example, a list of ``User`` objects with a ``city`` attribute can be rendered in groups. In this example, ``grouper`` refers to the ``city`` value of the group. .. sourcecode:: html+jinja <ul>{% for city, items in users|groupby("city") %} <li>{{ city }} <ul>{% for user in items %} <li>{{ user.name }} {% endfor %}</ul> </li> {% endfor %}</ul> ``groupby`` yields namedtuples of ``(grouper, list)``, which can be used instead of the tuple unpacking above. ``grouper`` is the value of the attribute, and ``list`` is the items with that value. .. sourcecode:: html+jinja <ul>{% for group in users|groupby("city") %} <li>{{ group.grouper }}: {{ group.list|join(", ") }} {% endfor %}</ul> You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja <ul>{% for city, items in users|groupby("city", default="NY") %} <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li> {% endfor %}</ul> Like the :func:`~jinja-filters.sort` filter, sorting and grouping is case-insensitive by default. The ``key`` for each group will have the case of the first item in that group of values. For example, if a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group will have two values. This can be disabled by passing ``case_sensitive=True``. .. versionchanged:: 3.1 Added the ``case_sensitive`` parameter. Sorting and grouping is case-insensitive by default, matching other filters that do comparisons. .. versionchanged:: 3.0 Added the ``default`` parameter. .. versionchanged:: 2.6 The attribute supports dot notation for nested access.
Here is the function:
def sync_do_groupby(
environment: "Environment",
value: "t.Iterable[V]",
attribute: t.Union[str, int],
default: t.Optional[t.Any] = None,
case_sensitive: bool = False,
) -> "t.List[_GroupTuple]":
"""Group a sequence of objects by an attribute using Python's
:func:`itertools.groupby`. The attribute can use dot notation for
nested access, like ``"address.city"``. Unlike Python's ``groupby``,
the values are sorted first so only one group is returned for each
unique value.
For example, a list of ``User`` objects with a ``city`` attribute
can be rendered in groups. In this example, ``grouper`` refers to
the ``city`` value of the group.
.. sourcecode:: html+jinja
<ul>{% for city, items in users|groupby("city") %}
<li>{{ city }}
<ul>{% for user in items %}
<li>{{ user.name }}
{% endfor %}</ul>
</li>
{% endfor %}</ul>
``groupby`` yields namedtuples of ``(grouper, list)``, which
can be used instead of the tuple unpacking above. ``grouper`` is the
value of the attribute, and ``list`` is the items with that value.
.. sourcecode:: html+jinja
<ul>{% for group in users|groupby("city") %}
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
{% endfor %}</ul>
You can specify a ``default`` value to use if an object in the list
does not have the given attribute.
.. sourcecode:: jinja
<ul>{% for city, items in users|groupby("city", default="NY") %}
<li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
{% endfor %}</ul>
Like the :func:`~jinja-filters.sort` filter, sorting and grouping is
case-insensitive by default. The ``key`` for each group will have
the case of the first item in that group of values. For example, if
a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group
will have two values. This can be disabled by passing
``case_sensitive=True``.
.. versionchanged:: 3.1
Added the ``case_sensitive`` parameter. Sorting and grouping is
case-insensitive by default, matching other filters that do
comparisons.
.. versionchanged:: 3.0
Added the ``default`` parameter.
.. versionchanged:: 2.6
The attribute supports dot notation for nested access.
"""
expr = make_attrgetter(
environment,
attribute,
postprocess=ignore_case if not case_sensitive else None,
default=default,
)
out = [
_GroupTuple(key, list(values))
for key, values in groupby(sorted(value, key=expr), expr)
]
if not case_sensitive:
# Return the real key from the first value instead of the lowercase key.
output_expr = make_attrgetter(environment, attribute, default=default)
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
return out | Group a sequence of objects by an attribute using Python's :func:`itertools.groupby`. The attribute can use dot notation for nested access, like ``"address.city"``. Unlike Python's ``groupby``, the values are sorted first so only one group is returned for each unique value. For example, a list of ``User`` objects with a ``city`` attribute can be rendered in groups. In this example, ``grouper`` refers to the ``city`` value of the group. .. sourcecode:: html+jinja <ul>{% for city, items in users|groupby("city") %} <li>{{ city }} <ul>{% for user in items %} <li>{{ user.name }} {% endfor %}</ul> </li> {% endfor %}</ul> ``groupby`` yields namedtuples of ``(grouper, list)``, which can be used instead of the tuple unpacking above. ``grouper`` is the value of the attribute, and ``list`` is the items with that value. .. sourcecode:: html+jinja <ul>{% for group in users|groupby("city") %} <li>{{ group.grouper }}: {{ group.list|join(", ") }} {% endfor %}</ul> You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja <ul>{% for city, items in users|groupby("city", default="NY") %} <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li> {% endfor %}</ul> Like the :func:`~jinja-filters.sort` filter, sorting and grouping is case-insensitive by default. The ``key`` for each group will have the case of the first item in that group of values. For example, if a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group will have two values. This can be disabled by passing ``case_sensitive=True``. .. versionchanged:: 3.1 Added the ``case_sensitive`` parameter. Sorting and grouping is case-insensitive by default, matching other filters that do comparisons. .. versionchanged:: 3.0 Added the ``default`` parameter. .. versionchanged:: 2.6 The attribute supports dot notation for nested access. |
172,680 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def ignore_case(value: V) -> V:
"""For use as a postprocessor for :func:`make_attrgetter`. Converts strings
to lowercase and returns other types as-is."""
if isinstance(value, str):
return t.cast(V, value.lower())
return value
def make_attrgetter(
environment: "Environment",
attribute: t.Optional[t.Union[str, int]],
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
default: t.Optional[t.Any] = None,
) -> t.Callable[[t.Any], t.Any]:
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
parts = _prepare_attribute_parts(attribute)
def attrgetter(item: t.Any) -> t.Any:
for part in parts:
item = environment.getitem(item, part)
if default is not None and isinstance(item, Undefined):
item = default
if postprocess is not None:
item = postprocess(item)
return item
return attrgetter
class _GroupTuple(t.NamedTuple):
grouper: t.Any
list: t.List
# Use the regular tuple repr to hide this subclass if users print
# out the value during debugging.
def __repr__(self) -> str:
return tuple.__repr__(self)
def __str__(self) -> str:
return tuple.__str__(self)
def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ...
def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ...
async def auto_to_list(
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> t.List["V"]:
return [x async for x in auto_aiter(value)]
async def do_groupby(
environment: "Environment",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
attribute: t.Union[str, int],
default: t.Optional[t.Any] = None,
case_sensitive: bool = False,
) -> "t.List[_GroupTuple]":
expr = make_attrgetter(
environment,
attribute,
postprocess=ignore_case if not case_sensitive else None,
default=default,
)
out = [
_GroupTuple(key, await auto_to_list(values))
for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
]
if not case_sensitive:
# Return the real key from the first value instead of the lowercase key.
output_expr = make_attrgetter(environment, attribute, default=default)
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
return out | null |
172,681 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
V = t.TypeVar("V")
def make_attrgetter(
environment: "Environment",
attribute: t.Optional[t.Union[str, int]],
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
default: t.Optional[t.Any] = None,
) -> t.Callable[[t.Any], t.Any]:
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
parts = _prepare_attribute_parts(attribute)
def attrgetter(item: t.Any) -> t.Any:
for part in parts:
item = environment.getitem(item, part)
if default is not None and isinstance(item, Undefined):
item = default
if postprocess is not None:
item = postprocess(item)
return item
return attrgetter
The provided code snippet includes necessary dependencies for implementing the `sync_do_sum` function. Write a Python function `def sync_do_sum( environment: "Environment", iterable: "t.Iterable[V]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore ) -> V` to solve the following problem:
Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The ``attribute`` parameter was added to allow summing up over attributes. Also the ``start`` parameter was moved on to the right.
Here is the function:
def sync_do_sum(
environment: "Environment",
iterable: "t.Iterable[V]",
attribute: t.Optional[t.Union[str, int]] = None,
start: V = 0, # type: ignore
) -> V:
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The ``attribute`` parameter was added to allow summing up over
attributes. Also the ``start`` parameter was moved on to the right.
"""
if attribute is not None:
iterable = map(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start) # type: ignore[no-any-return, call-overload] | Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The ``attribute`` parameter was added to allow summing up over attributes. Also the ``start`` parameter was moved on to the right. |
172,682 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
V = t.TypeVar("V")
def make_attrgetter(
environment: "Environment",
attribute: t.Optional[t.Union[str, int]],
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
default: t.Optional[t.Any] = None,
) -> t.Callable[[t.Any], t.Any]:
async def auto_aiter(
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> "t.AsyncIterator[V]":
async def do_sum(
environment: "Environment",
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
attribute: t.Optional[t.Union[str, int]] = None,
start: V = 0, # type: ignore
) -> V:
rv = start
if attribute is not None:
func = make_attrgetter(environment, attribute)
else:
def func(x: V) -> V:
return x
async for item in auto_aiter(iterable):
rv += func(item)
return rv | null |
172,683 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
The provided code snippet includes necessary dependencies for implementing the `sync_do_list` function. Write a Python function `def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]"` to solve the following problem:
Convert the value into a list. If it was a string the returned list will be a list of characters.
Here is the function:
def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":
"""Convert the value into a list. If it was a string the returned list
will be a list of characters.
"""
return list(value) | Convert the value into a list. If it was a string the returned list will be a list of characters. |
172,684 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
async def auto_to_list(
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> t.List["V"]:
return [x async for x in auto_aiter(value)]
async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":
return await auto_to_list(value) | null |
172,685 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
The provided code snippet includes necessary dependencies for implementing the `do_mark_safe` function. Write a Python function `def do_mark_safe(value: str) -> Markup` to solve the following problem:
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Here is the function:
def do_mark_safe(value: str) -> Markup:
"""Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
"""
return Markup(value) | Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. |
172,686 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
The provided code snippet includes necessary dependencies for implementing the `do_mark_unsafe` function. Write a Python function `def do_mark_unsafe(value: str) -> str` to solve the following problem:
Mark a value as unsafe. This is the reverse operation for :func:`safe`.
Here is the function:
def do_mark_unsafe(value: str) -> str:
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
return str(value) | Mark a value as unsafe. This is the reverse operation for :func:`safe`. |
172,687 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
def do_reverse(value: str) -> str:
... | null |
172,688 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":
... | null |
172,689 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
V = t.TypeVar("V")
class FilterArgumentError(TemplateRuntimeError):
"""This error is raised if a filter was called with inappropriate
arguments
"""
The provided code snippet includes necessary dependencies for implementing the `do_reverse` function. Write a Python function `def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]` to solve the following problem:
Reverse the object or return an iterator that iterates over it the other way round.
Here is the function:
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
"""Reverse the object or return an iterator that iterates over it the other
way round.
"""
if isinstance(value, str):
return value[::-1]
try:
return reversed(value) # type: ignore
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError as e:
raise FilterArgumentError("argument must be iterable") from e | Reverse the object or return an iterator that iterates over it the other way round. |
172,690 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
class Undefined:
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
"""
__slots__ = (
"_undefined_hint",
"_undefined_obj",
"_undefined_name",
"_undefined_exception",
)
def __init__(
self,
hint: t.Optional[str] = None,
obj: t.Any = missing,
name: t.Optional[str] = None,
exc: t.Type[TemplateRuntimeError] = UndefinedError,
) -> None:
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
def _undefined_message(self) -> str:
"""Build a message about the undefined value based on how it was
accessed.
"""
if self._undefined_hint:
return self._undefined_hint
if self._undefined_obj is missing:
return f"{self._undefined_name!r} is undefined"
if not isinstance(self._undefined_name, str):
return (
f"{object_type_repr(self._undefined_obj)} has no"
f" element {self._undefined_name!r}"
)
return (
f"{object_type_repr(self._undefined_obj)!r} has no"
f" attribute {self._undefined_name!r}"
)
def _fail_with_undefined_error(
self, *args: t.Any, **kwargs: t.Any
) -> "te.NoReturn":
"""Raise an :exc:`UndefinedError` when operations are performed
on the undefined value.
"""
raise self._undefined_exception(self._undefined_message)
def __getattr__(self, name: str) -> t.Any:
if name[:2] == "__":
raise AttributeError(name)
return self._fail_with_undefined_error()
__add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error
__mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error
__truediv__ = __rtruediv__ = _fail_with_undefined_error
__floordiv__ = __rfloordiv__ = _fail_with_undefined_error
__mod__ = __rmod__ = _fail_with_undefined_error
__pos__ = __neg__ = _fail_with_undefined_error
__call__ = __getitem__ = _fail_with_undefined_error
__lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
__int__ = __float__ = __complex__ = _fail_with_undefined_error
__pow__ = __rpow__ = _fail_with_undefined_error
def __eq__(self, other: t.Any) -> bool:
return type(self) is type(other)
def __ne__(self, other: t.Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return id(type(self))
def __str__(self) -> str:
return ""
def __len__(self) -> int:
return 0
def __iter__(self) -> t.Iterator[t.Any]:
yield from ()
async def __aiter__(self) -> t.AsyncIterator[t.Any]:
for _ in ():
yield
def __bool__(self) -> bool:
return False
def __repr__(self) -> str:
return "Undefined"
del (
Undefined.__slots__,
ChainableUndefined.__slots__,
DebugUndefined.__slots__,
StrictUndefined.__slots__,
)
The provided code snippet includes necessary dependencies for implementing the `do_attr` function. Write a Python function `def do_attr( environment: "Environment", obj: t.Any, name: str ) -> t.Union[Undefined, t.Any]` to solve the following problem:
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
Here is the function:
def do_attr(
environment: "Environment", obj: t.Any, name: str
) -> t.Union[Undefined, t.Any]:
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo.bar`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
if environment.sandboxed:
environment = t.cast("SandboxedEnvironment", environment)
if not environment.is_safe_attribute(obj, name, value):
return environment.unsafe_undefined(obj, name)
return value
return environment.undefined(obj=obj, name=name) | Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. |
172,691 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def sync_do_map(
context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any
) -> t.Iterable:
... | null |
172,692 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def sync_do_map(
context: "Context",
value: t.Iterable,
*,
attribute: str = ...,
default: t.Optional[t.Any] = None,
) -> t.Iterable:
... | null |
172,693 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def prepare_map(
context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
) -> t.Callable[[t.Any], t.Any]:
if not args and "attribute" in kwargs:
attribute = kwargs.pop("attribute")
default = kwargs.pop("default", None)
if kwargs:
raise FilterArgumentError(
f"Unexpected keyword argument {next(iter(kwargs))!r}"
)
func = make_attrgetter(context.environment, attribute, default=default)
else:
try:
name = args[0]
args = args[1:]
except LookupError:
raise FilterArgumentError("map requires a filter argument") from None
def func(item: t.Any) -> t.Any:
return context.environment.call_filter(
name, item, args, kwargs, context=context
)
return func
The provided code snippet includes necessary dependencies for implementing the `sync_do_map` function. Write a Python function `def sync_do_map( context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any ) -> t.Iterable` to solve the following problem:
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja {{ users|map(attribute="username", default="Anonymous")|join(", ") }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} Similar to a generator comprehension such as: .. code-block:: python (u.username for u in users) (getattr(u, "username", "Anonymous") for u in users) (do_lower(x) for x in titles) .. versionchanged:: 2.11.0 Added the ``default`` parameter. .. versionadded:: 2.7
Here is the function:
def sync_do_map(
context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any
) -> t.Iterable:
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
You can specify a ``default`` value to use if an object in the list
does not have the given attribute.
.. sourcecode:: jinja
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
Similar to a generator comprehension such as:
.. code-block:: python
(u.username for u in users)
(getattr(u, "username", "Anonymous") for u in users)
(do_lower(x) for x in titles)
.. versionchanged:: 2.11.0
Added the ``default`` parameter.
.. versionadded:: 2.7
"""
if value:
func = prepare_map(context, args, kwargs)
for item in value:
yield func(item) | Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames: .. sourcecode:: jinja Users on this page: {{ users|map(attribute='username')|join(', ') }} You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja {{ users|map(attribute="username", default="Anonymous")|join(", ") }} Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence: .. sourcecode:: jinja Users on this page: {{ titles|map('lower')|join(', ') }} Similar to a generator comprehension such as: .. code-block:: python (u.username for u in users) (getattr(u, "username", "Anonymous") for u in users) (do_lower(x) for x in titles) .. versionchanged:: 2.11.0 Added the ``default`` parameter. .. versionadded:: 2.7 |
172,694 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
name: str,
*args: t.Any,
**kwargs: t.Any,
) -> t.Iterable:
... | null |
172,695 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*,
attribute: str = ...,
default: t.Optional[t.Any] = None,
) -> t.Iterable:
... | null |
172,696 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def prepare_map(
context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]
) -> t.Callable[[t.Any], t.Any]:
if not args and "attribute" in kwargs:
attribute = kwargs.pop("attribute")
default = kwargs.pop("default", None)
if kwargs:
raise FilterArgumentError(
f"Unexpected keyword argument {next(iter(kwargs))!r}"
)
func = make_attrgetter(context.environment, attribute, default=default)
else:
try:
name = args[0]
args = args[1:]
except LookupError:
raise FilterArgumentError("map requires a filter argument") from None
def func(item: t.Any) -> t.Any:
return context.environment.call_filter(
name, item, args, kwargs, context=context
)
return func
async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
# Avoid a costly call to isawaitable
if type(value) in _common_primitives:
return t.cast("V", value)
if inspect.isawaitable(value):
return await t.cast("t.Awaitable[V]", value)
return t.cast("V", value)
async def auto_aiter(
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> "t.AsyncIterator[V]":
if hasattr(iterable, "__aiter__"):
async for item in t.cast("t.AsyncIterable[V]", iterable):
yield item
else:
for item in t.cast("t.Iterable[V]", iterable):
yield item
async def do_map(
context: "Context",
value: t.Union[t.AsyncIterable, t.Iterable],
*args: t.Any,
**kwargs: t.Any,
) -> t.AsyncIterable:
if value:
func = prepare_map(context, args, kwargs)
async for item in auto_aiter(value):
yield await auto_await(func(item)) | null |
172,697 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def select_or_reject(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.Iterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
for item in value:
if func(item):
yield item
The provided code snippet includes necessary dependencies for implementing the `sync_do_select` function. Write a Python function `def sync_do_select( context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any ) -> "t.Iterator[V]"` to solve the following problem:
Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding. If no test is specified, each object will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ numbers|select("odd") }} {{ numbers|select("odd") }} {{ numbers|select("divisibleby", 3) }} {{ numbers|select("lessthan", 42) }} {{ strings|select("equalto", "mystring") }} Similar to a generator comprehension such as: .. code-block:: python (n for n in numbers if test_odd(n)) (n for n in numbers if test_divisibleby(n, 3)) .. versionadded:: 2.7
Here is the function:
def sync_do_select(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to each object,
and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
Similar to a generator comprehension such as:
.. code-block:: python
(n for n in numbers if test_odd(n))
(n for n in numbers if test_divisibleby(n, 3))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: x, False) | Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding. If no test is specified, each object will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ numbers|select("odd") }} {{ numbers|select("odd") }} {{ numbers|select("divisibleby", 3) }} {{ numbers|select("lessthan", 42) }} {{ strings|select("equalto", "mystring") }} Similar to a generator comprehension such as: .. code-block:: python (n for n in numbers if test_odd(n)) (n for n in numbers if test_divisibleby(n, 3)) .. versionadded:: 2.7 |
172,698 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
async def async_select_or_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.AsyncIterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
async for item in auto_aiter(value):
if func(item):
yield item
async def do_select(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False) | null |
172,699 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def select_or_reject(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.Iterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
for item in value:
if func(item):
yield item
The provided code snippet includes necessary dependencies for implementing the `sync_do_reject` function. Write a Python function `def sync_do_reject( context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any ) -> "t.Iterator[V]"` to solve the following problem:
Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding. If no test is specified, each object will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ numbers|reject("odd") }} Similar to a generator comprehension such as: .. code-block:: python (n for n in numbers if not test_odd(n)) .. versionadded:: 2.7
Here is the function:
def sync_do_reject(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to each object,
and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
Similar to a generator comprehension such as:
.. code-block:: python
(n for n in numbers if not test_odd(n))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: not x, False) | Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding. If no test is specified, each object will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ numbers|reject("odd") }} Similar to a generator comprehension such as: .. code-block:: python (n for n in numbers if not test_odd(n)) .. versionadded:: 2.7 |
172,700 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
async def async_select_or_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.AsyncIterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
async for item in auto_aiter(value):
if func(item):
yield item
async def do_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False) | null |
172,701 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def select_or_reject(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.Iterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
for item in value:
if func(item):
yield item
The provided code snippet includes necessary dependencies for implementing the `sync_do_selectattr` function. Write a Python function `def sync_do_selectattr( context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any ) -> "t.Iterator[V]"` to solve the following problem:
Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding. If no test is specified, the attribute's value will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ users|selectattr("is_active") }} {{ users|selectattr("email", "none") }} Similar to a generator comprehension such as: .. code-block:: python (u for user in users if user.is_active) (u for user in users if test_none(user.email)) .. versionadded:: 2.7
Here is the function:
def sync_do_selectattr(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and only selecting the objects with the
test succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
Similar to a generator comprehension such as:
.. code-block:: python
(u for user in users if user.is_active)
(u for user in users if test_none(user.email))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: x, True) | Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding. If no test is specified, the attribute's value will be evaluated as a boolean. Example usage: .. sourcecode:: jinja {{ users|selectattr("is_active") }} {{ users|selectattr("email", "none") }} Similar to a generator comprehension such as: .. code-block:: python (u for user in users if user.is_active) (u for user in users if test_none(user.email)) .. versionadded:: 2.7 |
172,702 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
async def async_select_or_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.AsyncIterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
async for item in auto_aiter(value):
if func(item):
yield item
async def do_selectattr(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True) | null |
172,703 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
def select_or_reject(
context: "Context",
value: "t.Iterable[V]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.Iterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
for item in value:
if func(item):
yield item
The provided code snippet includes necessary dependencies for implementing the `sync_do_rejectattr` function. Write a Python function `def sync_do_rejectattr( context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any ) -> "t.Iterator[V]"` to solve the following problem:
Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding. If no test is specified, the attribute's value will be evaluated as a boolean. .. sourcecode:: jinja {{ users|rejectattr("is_active") }} {{ users|rejectattr("email", "none") }} Similar to a generator comprehension such as: .. code-block:: python (u for user in users if not user.is_active) (u for user in users if not test_none(user.email)) .. versionadded:: 2.7
Here is the function:
def sync_do_rejectattr(
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
) -> "t.Iterator[V]":
"""Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
Similar to a generator comprehension such as:
.. code-block:: python
(u for user in users if not user.is_active)
(u for user in users if not test_none(user.email))
.. versionadded:: 2.7
"""
return select_or_reject(context, value, args, kwargs, lambda x: not x, True) | Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding. If no test is specified, the attribute's value will be evaluated as a boolean. .. sourcecode:: jinja {{ users|rejectattr("is_active") }} {{ users|rejectattr("email", "none") }} Similar to a generator comprehension such as: .. code-block:: python (u for user in users if not user.is_active) (u for user in users if not test_none(user.email)) .. versionadded:: 2.7 |
172,704 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
async def async_select_or_reject(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
args: t.Tuple,
kwargs: t.Dict[str, t.Any],
modfunc: t.Callable[[t.Any], t.Any],
lookup_attr: bool,
) -> "t.AsyncIterator[V]":
if value:
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
async for item in auto_aiter(value):
if func(item):
yield item
async def do_rejectattr(
context: "Context",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
*args: t.Any,
**kwargs: t.Any,
) -> "t.AsyncIterator[V]":
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True) | null |
172,705 | import math
import random
import re
import typing
import typing as t
from collections import abc
from itertools import chain
from itertools import groupby
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import async_variant
from .async_utils import auto_aiter
from .async_utils import auto_await
from .async_utils import auto_to_list
from .exceptions import FilterArgumentError
from .runtime import Undefined
from .utils import htmlsafe_json_dumps
from .utils import pass_context
from .utils import pass_environment
from .utils import pass_eval_context
from .utils import pformat
from .utils import url_quote
from .utils import urlize
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
from .nodes import EvalContext
from .runtime import Context
from .sandbox import SandboxedEnvironment # noqa: F401
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
def htmlsafe_json_dumps(
obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
) -> markupsafe.Markup:
"""Serialize an object to a string of JSON with :func:`json.dumps`,
then replace HTML-unsafe characters with Unicode escapes and mark
the result safe with :class:`~markupsafe.Markup`.
This is available in templates as the ``|tojson`` filter.
The following characters are escaped: ``<``, ``>``, ``&``, ``'``.
The returned string is safe to render in HTML documents and
``<script>`` tags. The exception is in HTML attributes that are
double quoted; either use single quotes or the ``|forceescape``
filter.
:param obj: The object to serialize to JSON.
:param dumps: The ``dumps`` function to use. Defaults to
``env.policies["json.dumps_function"]``, which defaults to
:func:`json.dumps`.
:param kwargs: Extra arguments to pass to ``dumps``. Merged onto
``env.policies["json.dumps_kwargs"]``.
.. versionchanged:: 3.0
The ``dumper`` parameter is renamed to ``dumps``.
.. versionadded:: 2.9
"""
if dumps is None:
dumps = json.dumps
return markupsafe.Markup(
dumps(obj, **kwargs)
.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("&", "\\u0026")
.replace("'", "\\u0027")
)
The provided code snippet includes necessary dependencies for implementing the `do_tojson` function. Write a Python function `def do_tojson( eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None ) -> Markup` to solve the following problem:
Serialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents. The returned string is safe to render in HTML documents and ``<script>`` tags. The exception is in HTML attributes that are double quoted; either use single quotes or the ``|forceescape`` filter. :param value: The object to serialize to JSON. :param indent: The ``indent`` parameter passed to ``dumps``, for pretty-printing the value. .. versionadded:: 2.9
Here is the function:
def do_tojson(
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
) -> Markup:
"""Serialize an object to a string of JSON, and mark it safe to
render in HTML. This filter is only for use in HTML documents.
The returned string is safe to render in HTML documents and
``<script>`` tags. The exception is in HTML attributes that are
double quoted; either use single quotes or the ``|forceescape``
filter.
:param value: The object to serialize to JSON.
:param indent: The ``indent`` parameter passed to ``dumps``, for
pretty-printing the value.
.. versionadded:: 2.9
"""
policies = eval_ctx.environment.policies
dumps = policies["json.dumps_function"]
kwargs = policies["json.dumps_kwargs"]
if indent is not None:
kwargs = kwargs.copy()
kwargs["indent"] = indent
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs) | Serialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents. The returned string is safe to render in HTML documents and ``<script>`` tags. The exception is in HTML attributes that are double quoted; either use single quotes or the ``|forceescape`` filter. :param value: The object to serialize to JSON. :param indent: The ``indent`` parameter passed to ``dumps``, for pretty-printing the value. .. versionadded:: 2.9 |
172,706 | import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .async_utils import auto_await
from .exceptions import TemplateNotFound
from .exceptions import TemplateRuntimeError
from .exceptions import UndefinedError
from .nodes import EvalContext
from .utils import _PassArg
from .utils import concat
from .utils import internalcode
from .utils import missing
from .utils import Namespace
from .utils import object_type_repr
from .utils import pass_eval_context
V = t.TypeVar("V")
The provided code snippet includes necessary dependencies for implementing the `identity` function. Write a Python function `def identity(x: V) -> V` to solve the following problem:
Returns its argument. Useful for certain things in the environment.
Here is the function:
def identity(x: V) -> V:
"""Returns its argument. Useful for certain things in the
environment.
"""
return x | Returns its argument. Useful for certain things in the environment. |
172,707 | import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .async_utils import auto_await
from .exceptions import TemplateNotFound
from .exceptions import TemplateRuntimeError
from .exceptions import UndefinedError
from .nodes import EvalContext
from .utils import _PassArg
from .utils import concat
from .utils import internalcode
from .utils import missing
from .utils import Namespace
from .utils import object_type_repr
from .utils import pass_eval_context
if t.TYPE_CHECKING:
import logging
import typing_extensions as te
from .environment import Environment
class chain(Iterator[_T], Generic[_T]):
def __init__(self, *iterables: Iterable[_T]) -> None: ...
def __next__(self) -> _T: ...
def __iter__(self) -> Iterator[_T]: ...
def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ...
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
concat = "".join
The provided code snippet includes necessary dependencies for implementing the `markup_join` function. Write a Python function `def markup_join(seq: t.Iterable[t.Any]) -> str` to solve the following problem:
Concatenation that escapes if necessary and converts to string.
Here is the function:
def markup_join(seq: t.Iterable[t.Any]) -> str:
"""Concatenation that escapes if necessary and converts to string."""
buf = []
iterator = map(soft_str, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, "__html__"):
return Markup("").join(chain(buf, iterator))
return concat(buf) | Concatenation that escapes if necessary and converts to string. |
172,708 | import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .async_utils import auto_await
from .exceptions import TemplateNotFound
from .exceptions import TemplateRuntimeError
from .exceptions import UndefinedError
from .nodes import EvalContext
from .utils import _PassArg
from .utils import concat
from .utils import internalcode
from .utils import missing
from .utils import Namespace
from .utils import object_type_repr
from .utils import pass_eval_context
if t.TYPE_CHECKING:
import logging
import typing_extensions as te
from .environment import Environment
concat = "".join
The provided code snippet includes necessary dependencies for implementing the `str_join` function. Write a Python function `def str_join(seq: t.Iterable[t.Any]) -> str` to solve the following problem:
Simple args to string conversion and concatenation.
Here is the function:
def str_join(seq: t.Iterable[t.Any]) -> str:
"""Simple args to string conversion and concatenation."""
return concat(map(str, seq)) | Simple args to string conversion and concatenation. |
172,709 | import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .async_utils import auto_await
from .exceptions import TemplateNotFound
from .exceptions import TemplateRuntimeError
from .exceptions import UndefinedError
from .nodes import EvalContext
from .utils import _PassArg
from .utils import concat
from .utils import internalcode
from .utils import missing
from .utils import Namespace
from .utils import object_type_repr
from .utils import pass_eval_context
if t.TYPE_CHECKING:
import logging
import typing_extensions as te
from .environment import Environment
missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()
The provided code snippet includes necessary dependencies for implementing the `new_context` function. Write a Python function `def new_context( environment: "Environment", template_name: t.Optional[str], blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]], vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> "Context"` to solve the following problem:
Internal helper for context creation.
Here is the function:
def new_context(
environment: "Environment",
template_name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
vars: t.Optional[t.Dict[str, t.Any]] = None,
shared: bool = False,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
locals: t.Optional[t.Mapping[str, t.Any]] = None,
) -> "Context":
"""Internal helper for context creation."""
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or (), **vars)
if locals:
# if the parent is shared a copy should be created because
# we don't want to modify the dict passed
if shared:
parent = dict(parent)
for key, value in locals.items():
if value is not missing:
parent[key] = value
return environment.context_class(
environment, parent, template_name, blocks, globals=globals
) | Internal helper for context creation. |
172,710 | import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .async_utils import auto_await
from .exceptions import TemplateNotFound
from .exceptions import TemplateRuntimeError
from .exceptions import UndefinedError
from .nodes import EvalContext
from .utils import _PassArg
from .utils import concat
from .utils import internalcode
from .utils import missing
from .utils import Namespace
from .utils import object_type_repr
from .utils import pass_eval_context
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
if t.TYPE_CHECKING:
import logging
import typing_extensions as te
from .environment import Environment
def _dict_method_all(dict_method: F) -> F:
@functools.wraps(dict_method)
def f_all(self: "Context") -> t.Any:
return dict_method(self.get_all())
return t.cast(F, f_all) | null |
172,711 | import functools
import sys
import typing as t
from collections import abc
from itertools import chain
from markupsafe import escape
from markupsafe import Markup
from markupsafe import soft_str
from .async_utils import auto_aiter
from .async_utils import auto_await
from .exceptions import TemplateNotFound
from .exceptions import TemplateRuntimeError
from .exceptions import UndefinedError
from .nodes import EvalContext
from .utils import _PassArg
from .utils import concat
from .utils import internalcode
from .utils import missing
from .utils import Namespace
from .utils import object_type_repr
from .utils import pass_eval_context
if t.TYPE_CHECKING:
import logging
import typing_extensions as te
from .environment import Environment
class Undefined:
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
"""
__slots__ = (
"_undefined_hint",
"_undefined_obj",
"_undefined_name",
"_undefined_exception",
)
def __init__(
self,
hint: t.Optional[str] = None,
obj: t.Any = missing,
name: t.Optional[str] = None,
exc: t.Type[TemplateRuntimeError] = UndefinedError,
) -> None:
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
def _undefined_message(self) -> str:
"""Build a message about the undefined value based on how it was
accessed.
"""
if self._undefined_hint:
return self._undefined_hint
if self._undefined_obj is missing:
return f"{self._undefined_name!r} is undefined"
if not isinstance(self._undefined_name, str):
return (
f"{object_type_repr(self._undefined_obj)} has no"
f" element {self._undefined_name!r}"
)
return (
f"{object_type_repr(self._undefined_obj)!r} has no"
f" attribute {self._undefined_name!r}"
)
def _fail_with_undefined_error(
self, *args: t.Any, **kwargs: t.Any
) -> "te.NoReturn":
"""Raise an :exc:`UndefinedError` when operations are performed
on the undefined value.
"""
raise self._undefined_exception(self._undefined_message)
def __getattr__(self, name: str) -> t.Any:
if name[:2] == "__":
raise AttributeError(name)
return self._fail_with_undefined_error()
__add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error
__mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error
__truediv__ = __rtruediv__ = _fail_with_undefined_error
__floordiv__ = __rfloordiv__ = _fail_with_undefined_error
__mod__ = __rmod__ = _fail_with_undefined_error
__pos__ = __neg__ = _fail_with_undefined_error
__call__ = __getitem__ = _fail_with_undefined_error
__lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
__int__ = __float__ = __complex__ = _fail_with_undefined_error
__pow__ = __rpow__ = _fail_with_undefined_error
def __eq__(self, other: t.Any) -> bool:
return type(self) is type(other)
def __ne__(self, other: t.Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return id(type(self))
def __str__(self) -> str:
return ""
def __len__(self) -> int:
return 0
def __iter__(self) -> t.Iterator[t.Any]:
yield from ()
async def __aiter__(self) -> t.AsyncIterator[t.Any]:
for _ in ():
yield
def __bool__(self) -> bool:
return False
def __repr__(self) -> str:
return "Undefined"
del (
Undefined.__slots__,
ChainableUndefined.__slots__,
DebugUndefined.__slots__,
StrictUndefined.__slots__,
)
The provided code snippet includes necessary dependencies for implementing the `make_logging_undefined` function. Write a Python function `def make_logging_undefined( logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined ) -> t.Type[Undefined]` to solve the following problem:
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`.
Here is the function:
def make_logging_undefined(
logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined
) -> t.Type[Undefined]:
"""Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
Example::
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=logger,
base=Undefined
)
.. versionadded:: 2.8
:param logger: the logger to use. If not provided, a default logger
is created.
:param base: the base class to add logging functionality to. This
defaults to :class:`Undefined`.
"""
if logger is None:
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler(sys.stderr))
def _log_message(undef: Undefined) -> None:
logger.warning( # type: ignore
"Template variable warning: %s", undef._undefined_message
)
class LoggingUndefined(base): # type: ignore
__slots__ = ()
def _fail_with_undefined_error( # type: ignore
self, *args: t.Any, **kwargs: t.Any
) -> "te.NoReturn":
try:
super()._fail_with_undefined_error(*args, **kwargs)
except self._undefined_exception as e:
logger.error("Template variable error: %s", e) # type: ignore
raise e
def __str__(self) -> str:
_log_message(self)
return super().__str__() # type: ignore
def __iter__(self) -> t.Iterator[t.Any]:
_log_message(self)
return super().__iter__() # type: ignore
def __bool__(self) -> bool:
_log_message(self)
return super().__bool__() # type: ignore
return LoggingUndefined | Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. |
172,712 | import operator
import types
import typing as t
from _string import formatter_field_name_split
from collections import abc
from collections import deque
from string import Formatter
from markupsafe import EscapeFormatter
from markupsafe import Markup
from .environment import Environment
from .exceptions import SecurityError
from .runtime import Context
from .runtime import Undefined
def inspect_format_method(callable: t.Callable) -> t.Optional[str]:
if not isinstance(
callable, (types.MethodType, types.BuiltinMethodType)
) or callable.__name__ not in ("format", "format_map"):
return None
obj = callable.__self__
if isinstance(obj, str):
return obj
return None | null |
172,713 | import operator
import types
import typing as t
from _string import formatter_field_name_split
from collections import abc
from collections import deque
from string import Formatter
from markupsafe import EscapeFormatter
from markupsafe import Markup
from .environment import Environment
from .exceptions import SecurityError
from .runtime import Context
from .runtime import Undefined
MAX_RANGE = 100000
The provided code snippet includes necessary dependencies for implementing the `safe_range` function. Write a Python function `def safe_range(*args: int) -> range` to solve the following problem:
A range that can't generate ranges with a length of more than MAX_RANGE items.
Here is the function:
def safe_range(*args: int) -> range:
"""A range that can't generate ranges with a length of more than
MAX_RANGE items.
"""
rng = range(*args)
if len(rng) > MAX_RANGE:
raise OverflowError(
"Range too big. The sandbox blocks ranges larger than"
f" MAX_RANGE ({MAX_RANGE})."
)
return rng | A range that can't generate ranges with a length of more than MAX_RANGE items. |
172,714 | import operator
import types
import typing as t
from _string import formatter_field_name_split
from collections import abc
from collections import deque
from string import Formatter
from markupsafe import EscapeFormatter
from markupsafe import Markup
from .environment import Environment
from .exceptions import SecurityError
from .runtime import Context
from .runtime import Undefined
UNSAFE_FUNCTION_ATTRIBUTES: t.Set[str] = set()
UNSAFE_METHOD_ATTRIBUTES: t.Set[str] = set()
UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}
UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}
UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}
The provided code snippet includes necessary dependencies for implementing the `is_internal_attribute` function. Write a Python function `def is_internal_attribute(obj: t.Any, attr: str) -> bool` to solve the following problem:
Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False
Here is the function:
def is_internal_attribute(obj: t.Any, attr: str) -> bool:
"""Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
>>> from jinja2.sandbox import is_internal_attribute
>>> is_internal_attribute(str, "mro")
True
>>> is_internal_attribute(str, "upper")
False
"""
if isinstance(obj, types.FunctionType):
if attr in UNSAFE_FUNCTION_ATTRIBUTES:
return True
elif isinstance(obj, types.MethodType):
if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:
return True
elif isinstance(obj, type):
if attr == "mro":
return True
elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
return True
elif isinstance(obj, types.GeneratorType):
if attr in UNSAFE_GENERATOR_ATTRIBUTES:
return True
elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):
if attr in UNSAFE_COROUTINE_ATTRIBUTES:
return True
elif hasattr(types, "AsyncGeneratorType") and isinstance(
obj, types.AsyncGeneratorType
):
if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
return True
return attr.startswith("__") | Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False |
172,715 | import operator
import types
import typing as t
from _string import formatter_field_name_split
from collections import abc
from collections import deque
from string import Formatter
from markupsafe import EscapeFormatter
from markupsafe import Markup
from .environment import Environment
from .exceptions import SecurityError
from .runtime import Context
from .runtime import Undefined
_mutable_spec: t.Tuple[t.Tuple[t.Type, t.FrozenSet[str]], ...] = (
(
abc.MutableSet,
frozenset(
[
"add",
"clear",
"difference_update",
"discard",
"pop",
"remove",
"symmetric_difference_update",
"update",
]
),
),
(
abc.MutableMapping,
frozenset(["clear", "pop", "popitem", "setdefault", "update"]),
),
(
abc.MutableSequence,
frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),
),
(
deque,
frozenset(
[
"append",
"appendleft",
"clear",
"extend",
"extendleft",
"pop",
"popleft",
"remove",
"rotate",
]
),
),
)
def unsafe(f: F) -> F:
"""Marks a function or method as unsafe.
.. code-block: python
def delete(self):
pass
"""
f.unsafe_callable = True # type: ignore
return f
The provided code snippet includes necessary dependencies for implementing the `modifies_known_mutable` function. Write a Python function `def modifies_known_mutable(obj: t.Any, attr: str) -> bool` to solve the following problem:
This function checks if an attribute on a builtin mutable object (list, dict, set or deque) or the corresponding ABCs would modify it if called. >>> modifies_known_mutable({}, "clear") True >>> modifies_known_mutable({}, "keys") False >>> modifies_known_mutable([], "append") True >>> modifies_known_mutable([], "index") False If called with an unsupported object, ``False`` is returned. >>> modifies_known_mutable("foo", "upper") False
Here is the function:
def modifies_known_mutable(obj: t.Any, attr: str) -> bool:
"""This function checks if an attribute on a builtin mutable object
(list, dict, set or deque) or the corresponding ABCs would modify it
if called.
>>> modifies_known_mutable({}, "clear")
True
>>> modifies_known_mutable({}, "keys")
False
>>> modifies_known_mutable([], "append")
True
>>> modifies_known_mutable([], "index")
False
If called with an unsupported object, ``False`` is returned.
>>> modifies_known_mutable("foo", "upper")
False
"""
for typespec, unsafe in _mutable_spec:
if isinstance(obj, typespec):
return attr in unsafe
return False | This function checks if an attribute on a builtin mutable object (list, dict, set or deque) or the corresponding ABCs would modify it if called. >>> modifies_known_mutable({}, "clear") True >>> modifies_known_mutable({}, "keys") False >>> modifies_known_mutable([], "append") True >>> modifies_known_mutable([], "index") False If called with an unsupported object, ``False`` is returned. >>> modifies_known_mutable("foo", "upper") False |
172,716 | import typing as t
from . import nodes
from .visitor import NodeTransformer
if t.TYPE_CHECKING:
from .environment import Environment
class Optimizer(NodeTransformer):
def __init__(self, environment: "t.Optional[Environment]") -> None:
self.environment = environment
def generic_visit(
self, node: nodes.Node, *args: t.Any, **kwargs: t.Any
) -> nodes.Node:
node = super().generic_visit(node, *args, **kwargs)
# Do constant folding. Some other nodes besides Expr have
# as_const, but folding them causes errors later on.
if isinstance(node, nodes.Expr):
try:
return nodes.Const.from_untrusted(
node.as_const(args[0] if args else None),
lineno=node.lineno,
environment=self.environment,
)
except nodes.Impossible:
pass
return node
The provided code snippet includes necessary dependencies for implementing the `optimize` function. Write a Python function `def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node` to solve the following problem:
The context hint can be used to perform an static optimization based on the context given.
Here is the function:
def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node:
"""The context hint can be used to perform an static optimization
based on the context given."""
optimizer = Optimizer(environment)
return t.cast(nodes.Node, optimizer.visit(node)) | The context hint can be used to perform an static optimization based on the context given. |
172,717 | import sys
import typing as t
from types import CodeType
from types import TracebackType
from .exceptions import TemplateSyntaxError
from .utils import internal_code
from .utils import missing
if t.TYPE_CHECKING:
from .runtime import Context
def fake_traceback( # type: ignore
exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int
) -> TracebackType:
"""Produce a new traceback object that looks like it came from the
template source instead of the compiled code. The filename, line
number, and location name will point to the template, and the local
variables will be the current template context.
:param exc_value: The original exception to be re-raised to create
the new traceback.
:param tb: The original traceback to get the local variables and
code info from.
:param filename: The template filename.
:param lineno: The line number in the template source.
"""
if tb is not None:
# Replace the real locals with the context that would be
# available at that point in the template.
locals = get_template_locals(tb.tb_frame.f_locals)
locals.pop("__jinja_exception__", None)
else:
locals = {}
globals = {
"__name__": filename,
"__file__": filename,
"__jinja_exception__": exc_value,
}
# Raise an exception at the correct line number.
code: CodeType = compile(
"\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec"
)
# Build a new code object that points to the template file and
# replaces the location with a block name.
location = "template"
if tb is not None:
function = tb.tb_frame.f_code.co_name
if function == "root":
location = "top-level template code"
elif function.startswith("block_"):
location = f"block {function[6:]!r}"
if sys.version_info >= (3, 8):
code = code.replace(co_name=location)
else:
code = CodeType(
code.co_argcount,
code.co_kwonlyargcount,
code.co_nlocals,
code.co_stacksize,
code.co_flags,
code.co_code,
code.co_consts,
code.co_names,
code.co_varnames,
code.co_filename,
location,
code.co_firstlineno,
code.co_lnotab,
code.co_freevars,
code.co_cellvars,
)
# Execute the new code, which is guaranteed to raise, and return
# the new traceback without this frame.
try:
exec(code, globals, locals)
except BaseException:
return sys.exc_info()[2].tb_next # type: ignore
class TracebackType:
if sys.version_info >= (3, 7):
def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ...
tb_next: Optional[TracebackType]
else:
def tb_next(self) -> Optional[TracebackType]: ...
# the rest are read-only even in 3.7
def tb_frame(self) -> FrameType: ...
def tb_lasti(self) -> int: ...
def tb_lineno(self) -> int: ...
class TemplateSyntaxError(TemplateError):
"""Raised to tell the user that there is a problem with the template."""
def __init__(
self,
message: str,
lineno: int,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> None:
super().__init__(message)
self.lineno = lineno
self.name = name
self.filename = filename
self.source: t.Optional[str] = None
# this is set to True if the debug.translate_syntax_error
# function translated the syntax error into a new traceback
self.translated = False
def __str__(self) -> str:
# for translated errors we only return the message
if self.translated:
return t.cast(str, self.message)
# otherwise attach some stuff
location = f"line {self.lineno}"
name = self.filename or self.name
if name:
location = f'File "{name}", {location}'
lines = [t.cast(str, self.message), " " + location]
# if the source is set, add the line to the output
if self.source is not None:
try:
line = self.source.splitlines()[self.lineno - 1]
except IndexError:
pass
else:
lines.append(" " + line.strip())
return "\n".join(lines)
def __reduce__(self): # type: ignore
# https://bugs.python.org/issue1692335 Exceptions that take
# multiple required arguments have problems with pickling.
# Without this, raises TypeError: __init__() missing 1 required
# positional argument: 'lineno'
return self.__class__, (self.message, self.lineno, self.name, self.filename)
internal_code: t.MutableSet[CodeType] = set()
The provided code snippet includes necessary dependencies for implementing the `rewrite_traceback_stack` function. Write a Python function `def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException` to solve the following problem:
Rewrite the current exception to replace any tracebacks from within compiled template code with tracebacks that look like they came from the template source. This must be called within an ``except`` block. :param source: For ``TemplateSyntaxError``, the original source if known. :return: The original exception with the rewritten traceback.
Here is the function:
def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:
"""Rewrite the current exception to replace any tracebacks from
within compiled template code with tracebacks that look like they
came from the template source.
This must be called within an ``except`` block.
:param source: For ``TemplateSyntaxError``, the original source if
known.
:return: The original exception with the rewritten traceback.
"""
_, exc_value, tb = sys.exc_info()
exc_value = t.cast(BaseException, exc_value)
tb = t.cast(TracebackType, tb)
if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:
exc_value.translated = True
exc_value.source = source
# Remove the old traceback, otherwise the frames from the
# compiler still show up.
exc_value.with_traceback(None)
# Outside of runtime, so the frame isn't executing template
# code, but it still needs to point at the template.
tb = fake_traceback(
exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
)
else:
# Skip the frame for the render function.
tb = tb.tb_next
stack = []
# Build the stack of traceback object, replacing any in template
# code with the source file and line information.
while tb is not None:
# Skip frames decorated with @internalcode. These are internal
# calls that aren't useful in template debugging output.
if tb.tb_frame.f_code in internal_code:
tb = tb.tb_next
continue
template = tb.tb_frame.f_globals.get("__jinja_template__")
if template is not None:
lineno = template.get_corresponding_lineno(tb.tb_lineno)
fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)
stack.append(fake_tb)
else:
stack.append(tb)
tb = tb.tb_next
tb_next = None
# Assign tb_next in reverse to avoid circular references.
for tb in reversed(stack):
tb.tb_next = tb_next
tb_next = tb
return exc_value.with_traceback(tb_next) | Rewrite the current exception to replace any tracebacks from within compiled template code with tracebacks that look like they came from the template source. This must be called within an ``except`` block. :param source: For ``TemplateSyntaxError``, the original source if known. :return: The original exception with the rewritten traceback. |
172,718 | import typing as t
from ast import literal_eval
from ast import parse
from itertools import chain
from itertools import islice
from types import GeneratorType
from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
from .compiler import has_safe_repr
from .environment import Environment
from .environment import Template
def literal_eval(node_or_string: Union[str, AST]) -> Any: ...
def parse(source: Union[str, unicode], filename: Union[str, unicode] = ..., mode: Union[str, unicode] = ...) -> Module: ...
class chain(Iterator[_T], Generic[_T]):
def __init__(self, *iterables: Iterable[_T]) -> None: ...
def __next__(self) -> _T: ...
def __iter__(self) -> Iterator[_T]: ...
def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ...
def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ...
def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], step: Optional[int] = ...) -> Iterator[_T]: ...
class GeneratorType:
gi_code: CodeType
gi_frame: FrameType
gi_running: bool
gi_yieldfrom: Optional[GeneratorType]
def __iter__(self) -> GeneratorType: ...
def __next__(self) -> Any: ...
def close(self) -> None: ...
def send(self, __arg: Any) -> Any: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> Any: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ...
The provided code snippet includes necessary dependencies for implementing the `native_concat` function. Write a Python function `def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]` to solve the following problem:
Return a native Python type from the list of compiled nodes. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the string is returned. :param values: Iterable of outputs to concatenate.
Here is the function:
def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:
"""Return a native Python type from the list of compiled nodes. If
the result is a single node, its value is returned. Otherwise, the
nodes are concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise,
the string is returned.
:param values: Iterable of outputs to concatenate.
"""
head = list(islice(values, 2))
if not head:
return None
if len(head) == 1:
raw = head[0]
if not isinstance(raw, str):
return raw
else:
if isinstance(values, GeneratorType):
values = chain(head, values)
raw = "".join([str(v) for v in values])
try:
return literal_eval(
# In Python 3.10+ ast.literal_eval removes leading spaces/tabs
# from the given string. For backwards compatibility we need to
# parse the string ourselves without removing leading spaces/tabs.
parse(raw, mode="eval")
)
except (ValueError, SyntaxError, MemoryError):
return raw | Return a native Python type from the list of compiled nodes. If the result is a single node, its value is returned. Otherwise, the nodes are concatenated as strings. If the result can be parsed with :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the string is returned. :param values: Iterable of outputs to concatenate. |
172,719 | import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime import concat
from .runtime import Context
from .runtime import Undefined
from .utils import import_string
from .utils import pass_context
if t.TYPE_CHECKING:
import typing_extensions as te
from .lexer import Token
from .lexer import TokenStream
from .parser import Parser
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
class Context:
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`pass_context` get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
def __init__(
self,
environment: "Environment",
parent: t.Dict[str, t.Any],
name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
):
self.parent = parent
self.vars: t.Dict[str, t.Any] = {}
self.environment: "Environment" = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars: t.Set[str] = set()
self.name = name
self.globals_keys = set() if globals is None else set(globals)
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]:
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
)
return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any:
"""Look up a variable by name, or return a default if the key is
not found.
:param key: The variable name to look up.
:param default: The value to return if the key is not found.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
"""Look up a variable by name, or return an :class:`Undefined`
object if the key is not found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up.
"""
rv = self.resolve_or_missing(key)
if rv is missing:
return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any:
"""Look up a variable by name, or return a ``missing`` sentinel
if the key is not found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]:
"""Get a new dict with the exported variables."""
return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]:
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars)
def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]:
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`.
"""
if __debug__:
__traceback_hide__ = True # noqa
# Allow callable classes to take a context
if (
hasattr(__obj, "__call__") # noqa: B004
and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context:
# the active context should have access to variables set in
# loops and blocks without mutating the context itself
if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"])
if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args
elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args
elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
kwargs.pop("_block_vars", None)
kwargs.pop("_loop_vars", None)
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined(
"value was undefined because a callable raised a"
" StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
"""
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
return context
keys = _dict_method_all(dict.keys)
values = _dict_method_all(dict.values)
items = _dict_method_all(dict.items)
def __contains__(self, name: str) -> bool:
return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any:
"""Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key is not found.
"""
item = self.resolve_or_missing(key)
if item is missing:
raise KeyError(key)
return item
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
class Undefined:
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
jinja2.exceptions.UndefinedError: 'foo' is undefined
"""
__slots__ = (
"_undefined_hint",
"_undefined_obj",
"_undefined_name",
"_undefined_exception",
)
def __init__(
self,
hint: t.Optional[str] = None,
obj: t.Any = missing,
name: t.Optional[str] = None,
exc: t.Type[TemplateRuntimeError] = UndefinedError,
) -> None:
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
def _undefined_message(self) -> str:
"""Build a message about the undefined value based on how it was
accessed.
"""
if self._undefined_hint:
return self._undefined_hint
if self._undefined_obj is missing:
return f"{self._undefined_name!r} is undefined"
if not isinstance(self._undefined_name, str):
return (
f"{object_type_repr(self._undefined_obj)} has no"
f" element {self._undefined_name!r}"
)
return (
f"{object_type_repr(self._undefined_obj)!r} has no"
f" attribute {self._undefined_name!r}"
)
def _fail_with_undefined_error(
self, *args: t.Any, **kwargs: t.Any
) -> "te.NoReturn":
"""Raise an :exc:`UndefinedError` when operations are performed
on the undefined value.
"""
raise self._undefined_exception(self._undefined_message)
def __getattr__(self, name: str) -> t.Any:
if name[:2] == "__":
raise AttributeError(name)
return self._fail_with_undefined_error()
__add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error
__mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error
__truediv__ = __rtruediv__ = _fail_with_undefined_error
__floordiv__ = __rfloordiv__ = _fail_with_undefined_error
__mod__ = __rmod__ = _fail_with_undefined_error
__pos__ = __neg__ = _fail_with_undefined_error
__call__ = __getitem__ = _fail_with_undefined_error
__lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
__int__ = __float__ = __complex__ = _fail_with_undefined_error
__pow__ = __rpow__ = _fail_with_undefined_error
def __eq__(self, other: t.Any) -> bool:
return type(self) is type(other)
def __ne__(self, other: t.Any) -> bool:
return not self.__eq__(other)
def __hash__(self) -> int:
return id(type(self))
def __str__(self) -> str:
return ""
def __len__(self) -> int:
return 0
def __iter__(self) -> t.Iterator[t.Any]:
yield from ()
async def __aiter__(self) -> t.AsyncIterator[t.Any]:
for _ in ():
yield
def __bool__(self) -> bool:
return False
def __repr__(self) -> str:
return "Undefined"
del (
Undefined.__slots__,
ChainableUndefined.__slots__,
DebugUndefined.__slots__,
StrictUndefined.__slots__,
)
def _gettext_alias(
__context: Context, *args: t.Any, **kwargs: t.Any
) -> t.Union[t.Any, Undefined]:
return __context.call(__context.resolve("gettext"), *args, **kwargs) | null |
172,720 | import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime import concat
from .runtime import Context
from .runtime import Undefined
from .utils import import_string
from .utils import pass_context
if t.TYPE_CHECKING:
import typing_extensions as te
from .lexer import Token
from .lexer import TokenStream
from .parser import Parser
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
class Context:
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`pass_context` get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
def __init__(
self,
environment: "Environment",
parent: t.Dict[str, t.Any],
name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
):
self.parent = parent
self.vars: t.Dict[str, t.Any] = {}
self.environment: "Environment" = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars: t.Set[str] = set()
self.name = name
self.globals_keys = set() if globals is None else set(globals)
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]:
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
)
return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any:
"""Look up a variable by name, or return a default if the key is
not found.
:param key: The variable name to look up.
:param default: The value to return if the key is not found.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
"""Look up a variable by name, or return an :class:`Undefined`
object if the key is not found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up.
"""
rv = self.resolve_or_missing(key)
if rv is missing:
return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any:
"""Look up a variable by name, or return a ``missing`` sentinel
if the key is not found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]:
"""Get a new dict with the exported variables."""
return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]:
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars)
def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]:
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`.
"""
if __debug__:
__traceback_hide__ = True # noqa
# Allow callable classes to take a context
if (
hasattr(__obj, "__call__") # noqa: B004
and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context:
# the active context should have access to variables set in
# loops and blocks without mutating the context itself
if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"])
if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args
elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args
elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
kwargs.pop("_block_vars", None)
kwargs.pop("_loop_vars", None)
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined(
"value was undefined because a callable raised a"
" StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
"""
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
return context
keys = _dict_method_all(dict.keys)
values = _dict_method_all(dict.values)
items = _dict_method_all(dict.items)
def __contains__(self, name: str) -> bool:
return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any:
"""Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key is not found.
"""
item = self.resolve_or_missing(key)
if item is missing:
raise KeyError(key)
return item
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
def pass_context(f: F) -> F:
"""Pass the :class:`~jinja2.runtime.Context` as the first argument
to the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
If only ``Context.eval_context`` is needed, use
:func:`pass_eval_context`. If only ``Context.environment`` is
needed, use :func:`pass_environment`.
.. versionadded:: 3.0.0
Replaces ``contextfunction`` and ``contextfilter``.
"""
f.jinja_pass_arg = _PassArg.context # type: ignore
return f
def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:
@pass_context
def gettext(__context: Context, __string: str, **variables: t.Any) -> str:
rv = __context.call(func, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, even if there are no
# variables. This makes translation strings more consistent
# and predictable. This requires escaping
return rv % variables # type: ignore
return gettext | null |
172,721 | import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime import concat
from .runtime import Context
from .runtime import Undefined
from .utils import import_string
from .utils import pass_context
if t.TYPE_CHECKING:
import typing_extensions as te
from .lexer import Token
from .lexer import TokenStream
from .parser import Parser
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
class Context:
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`pass_context` get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
def __init__(
self,
environment: "Environment",
parent: t.Dict[str, t.Any],
name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
):
self.parent = parent
self.vars: t.Dict[str, t.Any] = {}
self.environment: "Environment" = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars: t.Set[str] = set()
self.name = name
self.globals_keys = set() if globals is None else set(globals)
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]:
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
)
return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any:
"""Look up a variable by name, or return a default if the key is
not found.
:param key: The variable name to look up.
:param default: The value to return if the key is not found.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
"""Look up a variable by name, or return an :class:`Undefined`
object if the key is not found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up.
"""
rv = self.resolve_or_missing(key)
if rv is missing:
return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any:
"""Look up a variable by name, or return a ``missing`` sentinel
if the key is not found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]:
"""Get a new dict with the exported variables."""
return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]:
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars)
def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]:
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`.
"""
if __debug__:
__traceback_hide__ = True # noqa
# Allow callable classes to take a context
if (
hasattr(__obj, "__call__") # noqa: B004
and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context:
# the active context should have access to variables set in
# loops and blocks without mutating the context itself
if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"])
if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args
elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args
elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
kwargs.pop("_block_vars", None)
kwargs.pop("_loop_vars", None)
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined(
"value was undefined because a callable raised a"
" StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
"""
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
return context
keys = _dict_method_all(dict.keys)
values = _dict_method_all(dict.values)
items = _dict_method_all(dict.items)
def __contains__(self, name: str) -> bool:
return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any:
"""Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key is not found.
"""
item = self.resolve_or_missing(key)
if item is missing:
raise KeyError(key)
return item
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
def pass_context(f: F) -> F:
"""Pass the :class:`~jinja2.runtime.Context` as the first argument
to the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
If only ``Context.eval_context`` is needed, use
:func:`pass_eval_context`. If only ``Context.environment`` is
needed, use :func:`pass_environment`.
.. versionadded:: 3.0.0
Replaces ``contextfunction`` and ``contextfilter``.
"""
f.jinja_pass_arg = _PassArg.context # type: ignore
return f
def _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:
@pass_context
def ngettext(
__context: Context,
__singular: str,
__plural: str,
__num: int,
**variables: t.Any,
) -> str:
variables.setdefault("num", __num)
rv = __context.call(func, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return ngettext | null |
172,722 | import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime import concat
from .runtime import Context
from .runtime import Undefined
from .utils import import_string
from .utils import pass_context
if t.TYPE_CHECKING:
import typing_extensions as te
from .lexer import Token
from .lexer import TokenStream
from .parser import Parser
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
class Context:
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`pass_context` get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
def __init__(
self,
environment: "Environment",
parent: t.Dict[str, t.Any],
name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
):
self.parent = parent
self.vars: t.Dict[str, t.Any] = {}
self.environment: "Environment" = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars: t.Set[str] = set()
self.name = name
self.globals_keys = set() if globals is None else set(globals)
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]:
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
)
return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any:
"""Look up a variable by name, or return a default if the key is
not found.
:param key: The variable name to look up.
:param default: The value to return if the key is not found.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
"""Look up a variable by name, or return an :class:`Undefined`
object if the key is not found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up.
"""
rv = self.resolve_or_missing(key)
if rv is missing:
return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any:
"""Look up a variable by name, or return a ``missing`` sentinel
if the key is not found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]:
"""Get a new dict with the exported variables."""
return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]:
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars)
def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]:
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`.
"""
if __debug__:
__traceback_hide__ = True # noqa
# Allow callable classes to take a context
if (
hasattr(__obj, "__call__") # noqa: B004
and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context:
# the active context should have access to variables set in
# loops and blocks without mutating the context itself
if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"])
if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args
elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args
elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
kwargs.pop("_block_vars", None)
kwargs.pop("_loop_vars", None)
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined(
"value was undefined because a callable raised a"
" StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
"""
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
return context
keys = _dict_method_all(dict.keys)
values = _dict_method_all(dict.values)
items = _dict_method_all(dict.items)
def __contains__(self, name: str) -> bool:
return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any:
"""Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key is not found.
"""
item = self.resolve_or_missing(key)
if item is missing:
raise KeyError(key)
return item
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
def pass_context(f: F) -> F:
"""Pass the :class:`~jinja2.runtime.Context` as the first argument
to the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
If only ``Context.eval_context`` is needed, use
:func:`pass_eval_context`. If only ``Context.environment`` is
needed, use :func:`pass_environment`.
.. versionadded:: 3.0.0
Replaces ``contextfunction`` and ``contextfilter``.
"""
f.jinja_pass_arg = _PassArg.context # type: ignore
return f
def _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:
@pass_context
def pgettext(
__context: Context, __string_ctx: str, __string: str, **variables: t.Any
) -> str:
variables.setdefault("context", __string_ctx)
rv = __context.call(func, __string_ctx, __string)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return pgettext | null |
172,723 | import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime import concat
from .runtime import Context
from .runtime import Undefined
from .utils import import_string
from .utils import pass_context
if t.TYPE_CHECKING:
import typing_extensions as te
from .lexer import Token
from .lexer import TokenStream
from .parser import Parser
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
class Markup(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: "te.SupportsIndex") -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
# a tuple of arguments, each wrapped
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
elif hasattr(type(arg), "__getitem__") and not isinstance(arg, str):
# a mapping of arguments, wrapped
arg = _MarkupEscapeHelper(arg, self.escape)
else:
# a single argument, wrapped with the helper and a tuple
arg = (_MarkupEscapeHelper(arg, self.escape),)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
# Use two regexes to avoid ambiguous matches.
value = _strip_comments_re.sub("", self)
value = _strip_tags_re.sub("", value)
value = " ".join(value.split())
return Markup(value).unescape()
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
class Context:
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`pass_context` get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
def __init__(
self,
environment: "Environment",
parent: t.Dict[str, t.Any],
name: t.Optional[str],
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
):
self.parent = parent
self.vars: t.Dict[str, t.Any] = {}
self.environment: "Environment" = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars: t.Set[str] = set()
self.name = name
self.globals_keys = set() if globals is None else set(globals)
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = {k: [v] for k, v in blocks.items()}
def super(
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
) -> t.Union["BlockReference", "Undefined"]:
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined(
f"there is no parent block called {name!r}.", name="super"
)
return BlockReference(name, self, blocks, index)
def get(self, key: str, default: t.Any = None) -> t.Any:
"""Look up a variable by name, or return a default if the key is
not found.
:param key: The variable name to look up.
:param default: The value to return if the key is not found.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
"""Look up a variable by name, or return an :class:`Undefined`
object if the key is not found.
If you need to add custom behavior, override
:meth:`resolve_or_missing`, not this method. The various lookup
functions use that method, not this one.
:param key: The variable name to look up.
"""
rv = self.resolve_or_missing(key)
if rv is missing:
return self.environment.undefined(name=key)
return rv
def resolve_or_missing(self, key: str) -> t.Any:
"""Look up a variable by name, or return a ``missing`` sentinel
if the key is not found.
Override this method to add custom lookup behavior.
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
method. Don't call this method directly.
:param key: The variable name to look up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return missing
def get_exported(self) -> t.Dict[str, t.Any]:
"""Get a new dict with the exported variables."""
return {k: self.vars[k] for k in self.exported_vars}
def get_all(self) -> t.Dict[str, t.Any]:
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
return self.vars
return dict(self.parent, **self.vars)
def call(
__self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902
) -> t.Union[t.Any, "Undefined"]:
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable has :func:`pass_context` or
:func:`pass_environment`.
"""
if __debug__:
__traceback_hide__ = True # noqa
# Allow callable classes to take a context
if (
hasattr(__obj, "__call__") # noqa: B004
and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
):
__obj = __obj.__call__ # type: ignore
pass_arg = _PassArg.from_obj(__obj)
if pass_arg is _PassArg.context:
# the active context should have access to variables set in
# loops and blocks without mutating the context itself
if kwargs.get("_loop_vars"):
__self = __self.derived(kwargs["_loop_vars"])
if kwargs.get("_block_vars"):
__self = __self.derived(kwargs["_block_vars"])
args = (__self,) + args
elif pass_arg is _PassArg.eval_context:
args = (__self.eval_ctx,) + args
elif pass_arg is _PassArg.environment:
args = (__self.environment,) + args
kwargs.pop("_block_vars", None)
kwargs.pop("_loop_vars", None)
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined(
"value was undefined because a callable raised a"
" StopIteration exception"
)
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
"""Internal helper function to create a derived context. This is
used in situations where the system needs a new context in the same
template that is independent.
"""
context = new_context(
self.environment, self.name, {}, self.get_all(), True, None, locals
)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
return context
keys = _dict_method_all(dict.keys)
values = _dict_method_all(dict.values)
items = _dict_method_all(dict.items)
def __contains__(self, name: str) -> bool:
return name in self.vars or name in self.parent
def __getitem__(self, key: str) -> t.Any:
"""Look up a variable by name with ``[]`` syntax, or raise a
``KeyError`` if the key is not found.
"""
item = self.resolve_or_missing(key)
if item is missing:
raise KeyError(key)
return item
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
def pass_context(f: F) -> F:
"""Pass the :class:`~jinja2.runtime.Context` as the first argument
to the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
If only ``Context.eval_context`` is needed, use
:func:`pass_eval_context`. If only ``Context.environment`` is
needed, use :func:`pass_environment`.
.. versionadded:: 3.0.0
Replaces ``contextfunction`` and ``contextfilter``.
"""
f.jinja_pass_arg = _PassArg.context # type: ignore
return f
def _make_new_npgettext(
func: t.Callable[[str, str, str, int], str]
) -> t.Callable[..., str]:
@pass_context
def npgettext(
__context: Context,
__string_ctx: str,
__singular: str,
__plural: str,
__num: int,
**variables: t.Any,
) -> str:
variables.setdefault("context", __string_ctx)
variables.setdefault("num", __num)
rv = __context.call(func, __string_ctx, __singular, __plural, __num)
if __context.eval_ctx.autoescape:
rv = Markup(rv)
# Always treat as a format string, see gettext comment above.
return rv % variables # type: ignore
return npgettext | null |
172,724 | import pprint
import re
import typing as t
from markupsafe import Markup
from . import defaults
from . import nodes
from .environment import Environment
from .exceptions import TemplateAssertionError
from .exceptions import TemplateSyntaxError
from .runtime import concat
from .runtime import Context
from .runtime import Undefined
from .utils import import_string
from .utils import pass_context
if t.TYPE_CHECKING:
import typing_extensions as te
from .lexer import Token
from .lexer import TokenStream
from .parser import Parser
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
class Extension:
"""Extensions can be used to add extra functionality to the Jinja template
system at the parser level. Custom extensions are bound to an environment
but may not store environment specific data on `self`. The reason for
this is that an extension can be bound to another environment (for
overlays) by creating a copy and reassigning the `environment` attribute.
As extensions are created by the environment they cannot accept any
arguments for configuration. One may want to work around that by using
a factory function, but that is not possible as extensions are identified
by their import name. The correct way to configure the extension is
storing the configuration values on the environment. Because this way the
environment ends up acting as central configuration storage the
attributes may clash which is why extensions have to ensure that the names
they choose for configuration are not too generic. ``prefix`` for example
is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
name as includes the name of the extension (fragment cache).
"""
identifier: t.ClassVar[str]
def __init_subclass__(cls) -> None:
cls.identifier = f"{cls.__module__}.{cls.__name__}"
#: if this extension parses this is the list of tags it's listening to.
tags: t.Set[str] = set()
#: the priority of that extension. This is especially useful for
#: extensions that preprocess values. A lower value means higher
#: priority.
#:
#: .. versionadded:: 2.4
priority = 100
def __init__(self, environment: Environment) -> None:
self.environment = environment
def bind(self, environment: Environment) -> "Extension":
"""Create a copy of this extension bound to another environment."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.environment = environment
return rv
def preprocess(
self, source: str, name: t.Optional[str], filename: t.Optional[str] = None
) -> str:
"""This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source.
"""
return source
def filter_stream(
self, stream: "TokenStream"
) -> t.Union["TokenStream", t.Iterable["Token"]]:
"""It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
to filter tokens returned. This method has to return an iterable of
:class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a
:class:`~jinja2.lexer.TokenStream`.
"""
return stream
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
"""If any of the :attr:`tags` matched this method is called with the
parser as first argument. The token the parser stream is pointing at
is the name token that matched. This method has to return one or a
list of multiple nodes.
"""
raise NotImplementedError()
def attr(
self, name: str, lineno: t.Optional[int] = None
) -> nodes.ExtensionAttribute:
"""Return an attribute node for the current extension. This is useful
to pass constants on extensions to generated template code.
::
self.attr('_my_attribute', lineno=lineno)
"""
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
def call_method(
self,
name: str,
args: t.Optional[t.List[nodes.Expr]] = None,
kwargs: t.Optional[t.List[nodes.Keyword]] = None,
dyn_args: t.Optional[nodes.Expr] = None,
dyn_kwargs: t.Optional[nodes.Expr] = None,
lineno: t.Optional[int] = None,
) -> nodes.Call:
"""Call a method of the extension. This is a shortcut for
:meth:`attr` + :class:`jinja2.nodes.Call`.
"""
if args is None:
args = []
if kwargs is None:
kwargs = []
return nodes.Call(
self.attr(name, lineno=lineno),
args,
kwargs,
dyn_args,
dyn_kwargs,
lineno=lineno,
)
class InternationalizationExtension(Extension):
"""This extension adds gettext support to Jinja."""
tags = {"trans"}
# TODO: the i18n extension is currently reevaluating values in a few
# situations. Take this example:
# {% trans count=something() %}{{ count }} foo{% pluralize
# %}{{ count }} fooss{% endtrans %}
# something is called twice here. One time for the gettext value and
# the other time for the n-parameter of the ngettext function.
def __init__(self, environment: Environment) -> None:
super().__init__(environment)
environment.globals["_"] = _gettext_alias
environment.extend(
install_gettext_translations=self._install,
install_null_translations=self._install_null,
install_gettext_callables=self._install_callables,
uninstall_gettext_translations=self._uninstall,
extract_translations=self._extract,
newstyle_gettext=False,
)
def _install(
self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None
) -> None:
# ugettext and ungettext are preferred in case the I18N library
# is providing compatibility with older Python versions.
gettext = getattr(translations, "ugettext", None)
if gettext is None:
gettext = translations.gettext
ngettext = getattr(translations, "ungettext", None)
if ngettext is None:
ngettext = translations.ngettext
pgettext = getattr(translations, "pgettext", None)
npgettext = getattr(translations, "npgettext", None)
self._install_callables(
gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext
)
def _install_null(self, newstyle: t.Optional[bool] = None) -> None:
import gettext
translations = gettext.NullTranslations()
if hasattr(translations, "pgettext"):
# Python < 3.8
pgettext = translations.pgettext # type: ignore
else:
def pgettext(c: str, s: str) -> str:
return s
if hasattr(translations, "npgettext"):
npgettext = translations.npgettext # type: ignore
else:
def npgettext(c: str, s: str, p: str, n: int) -> str:
return s if n == 1 else p
self._install_callables(
gettext=translations.gettext,
ngettext=translations.ngettext,
newstyle=newstyle,
pgettext=pgettext,
npgettext=npgettext,
)
def _install_callables(
self,
gettext: t.Callable[[str], str],
ngettext: t.Callable[[str, str, int], str],
newstyle: t.Optional[bool] = None,
pgettext: t.Optional[t.Callable[[str, str], str]] = None,
npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,
) -> None:
if newstyle is not None:
self.environment.newstyle_gettext = newstyle # type: ignore
if self.environment.newstyle_gettext: # type: ignore
gettext = _make_new_gettext(gettext)
ngettext = _make_new_ngettext(ngettext)
if pgettext is not None:
pgettext = _make_new_pgettext(pgettext)
if npgettext is not None:
npgettext = _make_new_npgettext(npgettext)
self.environment.globals.update(
gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext
)
def _uninstall(self, translations: "_SupportedTranslations") -> None:
for key in ("gettext", "ngettext", "pgettext", "npgettext"):
self.environment.globals.pop(key, None)
def _extract(
self,
source: t.Union[str, nodes.Template],
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
) -> t.Iterator[
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
]:
if isinstance(source, str):
source = self.environment.parse(source)
return extract_from_ast(source, gettext_functions)
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
"""Parse a translatable tag."""
lineno = next(parser.stream).lineno
context = None
context_token = parser.stream.next_if("string")
if context_token is not None:
context = context_token.value
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
plural_expr: t.Optional[nodes.Expr] = None
plural_expr_assignment: t.Optional[nodes.Assign] = None
num_called_num = False
variables: t.Dict[str, nodes.Expr] = {}
trimmed = None
while parser.stream.current.type != "block_end":
if variables:
parser.stream.expect("comma")
# skip colon for python compatibility
if parser.stream.skip_if("colon"):
break
token = parser.stream.expect("name")
if token.value in variables:
parser.fail(
f"translatable variable {token.value!r} defined twice.",
token.lineno,
exc=TemplateAssertionError,
)
# expressions
if parser.stream.current.type == "assign":
next(parser.stream)
variables[token.value] = var = parser.parse_expression()
elif trimmed is None and token.value in ("trimmed", "notrimmed"):
trimmed = token.value == "trimmed"
continue
else:
variables[token.value] = var = nodes.Name(token.value, "load")
if plural_expr is None:
if isinstance(var, nodes.Call):
plural_expr = nodes.Name("_trans", "load")
variables[token.value] = plural_expr
plural_expr_assignment = nodes.Assign(
nodes.Name("_trans", "store"), var
)
else:
plural_expr = var
num_called_num = token.value == "num"
parser.stream.expect("block_end")
plural = None
have_plural = False
referenced = set()
# now parse until endtrans or pluralize
singular_names, singular = self._parse_block(parser, True)
if singular_names:
referenced.update(singular_names)
if plural_expr is None:
plural_expr = nodes.Name(singular_names[0], "load")
num_called_num = singular_names[0] == "num"
# if we have a pluralize block, we parse that too
if parser.stream.current.test("name:pluralize"):
have_plural = True
next(parser.stream)
if parser.stream.current.type != "block_end":
token = parser.stream.expect("name")
if token.value not in variables:
parser.fail(
f"unknown variable {token.value!r} for pluralization",
token.lineno,
exc=TemplateAssertionError,
)
plural_expr = variables[token.value]
num_called_num = token.value == "num"
parser.stream.expect("block_end")
plural_names, plural = self._parse_block(parser, False)
next(parser.stream)
referenced.update(plural_names)
else:
next(parser.stream)
# register free names as simple name expressions
for name in referenced:
if name not in variables:
variables[name] = nodes.Name(name, "load")
if not have_plural:
plural_expr = None
elif plural_expr is None:
parser.fail("pluralize without variables", lineno)
if trimmed is None:
trimmed = self.environment.policies["ext.i18n.trimmed"]
if trimmed:
singular = self._trim_whitespace(singular)
if plural:
plural = self._trim_whitespace(plural)
node = self._make_node(
singular,
plural,
context,
variables,
plural_expr,
bool(referenced),
num_called_num and have_plural,
)
node.set_lineno(lineno)
if plural_expr_assignment is not None:
return [plural_expr_assignment, node]
else:
return node
def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:
return _ws_re.sub(" ", string.strip())
def _parse_block(
self, parser: "Parser", allow_pluralize: bool
) -> t.Tuple[t.List[str], str]:
"""Parse until the next block tag with a given name."""
referenced = []
buf = []
while True:
if parser.stream.current.type == "data":
buf.append(parser.stream.current.value.replace("%", "%%"))
next(parser.stream)
elif parser.stream.current.type == "variable_begin":
next(parser.stream)
name = parser.stream.expect("name").value
referenced.append(name)
buf.append(f"%({name})s")
parser.stream.expect("variable_end")
elif parser.stream.current.type == "block_begin":
next(parser.stream)
if parser.stream.current.test("name:endtrans"):
break
elif parser.stream.current.test("name:pluralize"):
if allow_pluralize:
break
parser.fail(
"a translatable section can have only one pluralize section"
)
parser.fail(
"control structures in translatable sections are not allowed"
)
elif parser.stream.eos:
parser.fail("unclosed translation block")
else:
raise RuntimeError("internal parser error")
return referenced, concat(buf)
def _make_node(
self,
singular: str,
plural: t.Optional[str],
context: t.Optional[str],
variables: t.Dict[str, nodes.Expr],
plural_expr: t.Optional[nodes.Expr],
vars_referenced: bool,
num_called_num: bool,
) -> nodes.Output:
"""Generates a useful node from the data provided."""
newstyle = self.environment.newstyle_gettext # type: ignore
node: nodes.Expr
# no variables referenced? no need to escape for old style
# gettext invocations only if there are vars.
if not vars_referenced and not newstyle:
singular = singular.replace("%%", "%")
if plural:
plural = plural.replace("%%", "%")
func_name = "gettext"
func_args: t.List[nodes.Expr] = [nodes.Const(singular)]
if context is not None:
func_args.insert(0, nodes.Const(context))
func_name = f"p{func_name}"
if plural_expr is not None:
func_name = f"n{func_name}"
func_args.extend((nodes.Const(plural), plural_expr))
node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)
# in case newstyle gettext is used, the method is powerful
# enough to handle the variable expansion and autoescape
# handling itself
if newstyle:
for key, value in variables.items():
# the function adds that later anyways in case num was
# called num, so just skip it.
if num_called_num and key == "num":
continue
node.kwargs.append(nodes.Keyword(key, value))
# otherwise do that here
else:
# mark the return value as safe if we are in an
# environment with autoescaping turned on
node = nodes.MarkSafeIfAutoescape(node)
if variables:
node = nodes.Mod(
node,
nodes.Dict(
[
nodes.Pair(nodes.Const(key), value)
for key, value in variables.items()
]
),
)
return nodes.Output([node])
def extract_from_ast(
ast: nodes.Template,
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
babel_style: bool = True,
) -> t.Iterator[
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
]:
"""Extract localizable strings from the given template node. Per
default this function returns matches in babel style that means non string
parameters as well as keyword arguments are returned as `None`. This
allows Babel to figure out what you really meant if you are using
gettext functions that allow keyword arguments for placeholder expansion.
If you don't want that behavior set the `babel_style` parameter to `False`
which causes only strings to be returned and parameters are always stored
in tuples. As a consequence invalid gettext calls (calls without a single
string parameter or string parameters after non-string parameters) are
skipped.
This example explains the behavior:
>>> from jinja2 import Environment
>>> env = Environment()
>>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
>>> list(extract_from_ast(node))
[(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
>>> list(extract_from_ast(node, babel_style=False))
[(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
For every string found this function yields a ``(lineno, function,
message)`` tuple, where:
* ``lineno`` is the number of the line on which the string was found,
* ``function`` is the name of the ``gettext`` function used (if the
string was extracted from embedded Python code), and
* ``message`` is the string, or a tuple of strings for functions
with multiple string arguments.
This extraction function operates on the AST and is because of that unable
to extract any comments. For comment support you have to use the babel
extraction interface or extract comments yourself.
"""
out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]
for node in ast.find_all(nodes.Call):
if (
not isinstance(node.node, nodes.Name)
or node.node.name not in gettext_functions
):
continue
strings: t.List[t.Optional[str]] = []
for arg in node.args:
if isinstance(arg, nodes.Const) and isinstance(arg.value, str):
strings.append(arg.value)
else:
strings.append(None)
for _ in node.kwargs:
strings.append(None)
if node.dyn_args is not None:
strings.append(None)
if node.dyn_kwargs is not None:
strings.append(None)
if not babel_style:
out = tuple(x for x in strings if x is not None)
if not out:
continue
else:
if len(strings) == 1:
out = strings[0]
else:
out = tuple(strings)
yield node.lineno, node.node.name, out
class _CommentFinder:
"""Helper class to find comments in a token stream. Can only
find comments for gettext calls forwards. Once the comment
from line 4 is found, a comment for line 1 will not return a
usable value.
"""
def __init__(
self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]
) -> None:
self.tokens = tokens
self.comment_tags = comment_tags
self.offset = 0
self.last_lineno = 0
def find_backwards(self, offset: int) -> t.List[str]:
try:
for _, token_type, token_value in reversed(
self.tokens[self.offset : offset]
):
if token_type in ("comment", "linecomment"):
try:
prefix, comment = token_value.split(None, 1)
except ValueError:
continue
if prefix in self.comment_tags:
return [comment.rstrip()]
return []
finally:
self.offset = offset
def find_comments(self, lineno: int) -> t.List[str]:
if not self.comment_tags or self.last_lineno > lineno:
return []
for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):
if token_lineno > lineno:
return self.find_backwards(self.offset + idx)
return self.find_backwards(len(self.tokens))
class Environment:
r"""The core component of Jinja is the `Environment`. It contains
important shared variables like configuration, filters, tests,
globals and others. Instances of this class may be modified if
they are not shared and if no template was loaded so far.
Modifications on environments after the first template was loaded
will lead to surprising effects and undefined behavior.
Here are the possible initialization parameters:
`block_start_string`
The string marking the beginning of a block. Defaults to ``'{%'``.
`block_end_string`
The string marking the end of a block. Defaults to ``'%}'``.
`variable_start_string`
The string marking the beginning of a print statement.
Defaults to ``'{{'``.
`variable_end_string`
The string marking the end of a print statement. Defaults to
``'}}'``.
`comment_start_string`
The string marking the beginning of a comment. Defaults to ``'{#'``.
`comment_end_string`
The string marking the end of a comment. Defaults to ``'#}'``.
`line_statement_prefix`
If given and a string, this will be used as prefix for line based
statements. See also :ref:`line-statements`.
`line_comment_prefix`
If given and a string, this will be used as prefix for line based
comments. See also :ref:`line-statements`.
.. versionadded:: 2.2
`trim_blocks`
If this is set to ``True`` the first newline after a block is
removed (block, not variable tag!). Defaults to `False`.
`lstrip_blocks`
If this is set to ``True`` leading spaces and tabs are stripped
from the start of a line to a block. Defaults to `False`.
`newline_sequence`
The sequence that starts a newline. Must be one of ``'\r'``,
``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
useful default for Linux and OS X systems as well as web
applications.
`keep_trailing_newline`
Preserve the trailing newline when rendering templates.
The default is ``False``, which causes a single newline,
if present, to be stripped from the end of the template.
.. versionadded:: 2.7
`extensions`
List of Jinja extensions to use. This can either be import paths
as strings or extension classes. For more information have a
look at :ref:`the extensions documentation <jinja-extensions>`.
`optimized`
should the optimizer be enabled? Default is ``True``.
`undefined`
:class:`Undefined` or a subclass of it that is used to represent
undefined values in the template.
`finalize`
A callable that can be used to process the result of a variable
expression before it is output. For example one can convert
``None`` implicitly into an empty string here.
`autoescape`
If set to ``True`` the XML/HTML autoescaping feature is enabled by
default. For more details about autoescaping see
:class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
be a callable that is passed the template name and has to
return ``True`` or ``False`` depending on autoescape should be
enabled by default.
.. versionchanged:: 2.4
`autoescape` can now be a function
`loader`
The template loader for this environment.
`cache_size`
The size of the cache. Per default this is ``400`` which means
that if more than 400 templates are loaded the loader will clean
out the least recently used template. If the cache size is set to
``0`` templates are recompiled all the time, if the cache size is
``-1`` the cache will not be cleaned.
.. versionchanged:: 2.8
The cache size was increased to 400 from a low 50.
`auto_reload`
Some loaders load templates from locations where the template
sources may change (ie: file system or database). If
``auto_reload`` is set to ``True`` (default) every time a template is
requested the loader checks if the source changed and if yes, it
will reload the template. For higher performance it's possible to
disable that.
`bytecode_cache`
If set to a bytecode cache object, this object will provide a
cache for the internal Jinja bytecode so that templates don't
have to be parsed if they were not changed.
See :ref:`bytecode-cache` for more information.
`enable_async`
If set to true this enables async template execution which
allows using async functions and generators.
"""
#: if this environment is sandboxed. Modifying this variable won't make
#: the environment sandboxed though. For a real sandboxed environment
#: have a look at jinja2.sandbox. This flag alone controls the code
#: generation by the compiler.
sandboxed = False
#: True if the environment is just an overlay
overlayed = False
#: the environment this environment is linked to if it is an overlay
linked_to: t.Optional["Environment"] = None
#: shared environments have this set to `True`. A shared environment
#: must not be modified
shared = False
#: the class that is used for code generation. See
#: :class:`~jinja2.compiler.CodeGenerator` for more information.
code_generator_class: t.Type["CodeGenerator"] = CodeGenerator
concat = "".join
#: the context class that is used for templates. See
#: :class:`~jinja2.runtime.Context` for more information.
context_class: t.Type[Context] = Context
template_class: t.Type["Template"]
def __init__(
self,
block_start_string: str = BLOCK_START_STRING,
block_end_string: str = BLOCK_END_STRING,
variable_start_string: str = VARIABLE_START_STRING,
variable_end_string: str = VARIABLE_END_STRING,
comment_start_string: str = COMMENT_START_STRING,
comment_end_string: str = COMMENT_END_STRING,
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
trim_blocks: bool = TRIM_BLOCKS,
lstrip_blocks: bool = LSTRIP_BLOCKS,
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
optimized: bool = True,
undefined: t.Type[Undefined] = Undefined,
finalize: t.Optional[t.Callable[..., t.Any]] = None,
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
loader: t.Optional["BaseLoader"] = None,
cache_size: int = 400,
auto_reload: bool = True,
bytecode_cache: t.Optional["BytecodeCache"] = None,
enable_async: bool = False,
):
# !!Important notice!!
# The constructor accepts quite a few arguments that should be
# passed by keyword rather than position. However it's important to
# not change the order of arguments because it's used at least
# internally in those cases:
# - spontaneous environments (i18n extension and Template)
# - unittests
# If parameter changes are required only add parameters at the end
# and don't change the arguments (or the defaults!) of the arguments
# existing already.
# lexer / parser information
self.block_start_string = block_start_string
self.block_end_string = block_end_string
self.variable_start_string = variable_start_string
self.variable_end_string = variable_end_string
self.comment_start_string = comment_start_string
self.comment_end_string = comment_end_string
self.line_statement_prefix = line_statement_prefix
self.line_comment_prefix = line_comment_prefix
self.trim_blocks = trim_blocks
self.lstrip_blocks = lstrip_blocks
self.newline_sequence = newline_sequence
self.keep_trailing_newline = keep_trailing_newline
# runtime information
self.undefined: t.Type[Undefined] = undefined
self.optimized = optimized
self.finalize = finalize
self.autoescape = autoescape
# defaults
self.filters = DEFAULT_FILTERS.copy()
self.tests = DEFAULT_TESTS.copy()
self.globals = DEFAULT_NAMESPACE.copy()
# set the loader provided
self.loader = loader
self.cache = create_cache(cache_size)
self.bytecode_cache = bytecode_cache
self.auto_reload = auto_reload
# configurable policies
self.policies = DEFAULT_POLICIES.copy()
# load extensions
self.extensions = load_extensions(self, extensions)
self.is_async = enable_async
_environment_config_check(self)
def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
"""Adds an extension after the environment was created.
.. versionadded:: 2.5
"""
self.extensions.update(load_extensions(self, [extension]))
def extend(self, **attributes: t.Any) -> None:
"""Add the items to the instance of the environment if they do not exist
yet. This is used by :ref:`extensions <writing-extensions>` to register
callbacks and configuration values without breaking inheritance.
"""
for key, value in attributes.items():
if not hasattr(self, key):
setattr(self, key, value)
def overlay(
self,
block_start_string: str = missing,
block_end_string: str = missing,
variable_start_string: str = missing,
variable_end_string: str = missing,
comment_start_string: str = missing,
comment_end_string: str = missing,
line_statement_prefix: t.Optional[str] = missing,
line_comment_prefix: t.Optional[str] = missing,
trim_blocks: bool = missing,
lstrip_blocks: bool = missing,
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,
keep_trailing_newline: bool = missing,
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
optimized: bool = missing,
undefined: t.Type[Undefined] = missing,
finalize: t.Optional[t.Callable[..., t.Any]] = missing,
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
loader: t.Optional["BaseLoader"] = missing,
cache_size: int = missing,
auto_reload: bool = missing,
bytecode_cache: t.Optional["BytecodeCache"] = missing,
enable_async: bool = False,
) -> "Environment":
"""Create a new overlay environment that shares all the data with the
current environment except for cache and the overridden attributes.
Extensions cannot be removed for an overlayed environment. An overlayed
environment automatically gets all the extensions of the environment it
is linked to plus optional extra extensions.
Creating overlays should happen after the initial environment was set
up completely. Not all attributes are truly linked, some are just
copied over so modifications on the original environment may not shine
through.
.. versionchanged:: 3.1.2
Added the ``newline_sequence``,, ``keep_trailing_newline``,
and ``enable_async`` parameters to match ``__init__``.
"""
args = dict(locals())
del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.overlayed = True
rv.linked_to = self
for key, value in args.items():
if value is not missing:
setattr(rv, key, value)
if cache_size is not missing:
rv.cache = create_cache(cache_size)
else:
rv.cache = copy_cache(self.cache)
rv.extensions = {}
for key, value in self.extensions.items():
rv.extensions[key] = value.bind(rv)
if extensions is not missing:
rv.extensions.update(load_extensions(rv, extensions))
if enable_async is not missing:
rv.is_async = enable_async
return _environment_config_check(rv)
def lexer(self) -> Lexer:
"""The lexer for this environment."""
return get_lexer(self)
def iter_extensions(self) -> t.Iterator["Extension"]:
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
def getitem(
self, obj: t.Any, argument: t.Union[str, t.Any]
) -> t.Union[t.Any, Undefined]:
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (AttributeError, TypeError, LookupError):
if isinstance(argument, str):
try:
attr = str(argument)
except Exception:
pass
else:
try:
return getattr(obj, attr)
except AttributeError:
pass
return self.undefined(obj=obj, name=argument)
def getattr(self, obj: t.Any, attribute: str) -> t.Any:
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a string.
"""
try:
return getattr(obj, attribute)
except AttributeError:
pass
try:
return obj[attribute]
except (TypeError, LookupError, AttributeError):
return self.undefined(obj=obj, name=attribute)
def _filter_test_common(
self,
name: t.Union[str, Undefined],
value: t.Any,
args: t.Optional[t.Sequence[t.Any]],
kwargs: t.Optional[t.Mapping[str, t.Any]],
context: t.Optional[Context],
eval_ctx: t.Optional[EvalContext],
is_filter: bool,
) -> t.Any:
if is_filter:
env_map = self.filters
type_name = "filter"
else:
env_map = self.tests
type_name = "test"
func = env_map.get(name) # type: ignore
if func is None:
msg = f"No {type_name} named {name!r}."
if isinstance(name, Undefined):
try:
name._fail_with_undefined_error()
except Exception as e:
msg = f"{msg} ({e}; did you forget to quote the callable name?)"
raise TemplateRuntimeError(msg)
args = [value, *(args if args is not None else ())]
kwargs = kwargs if kwargs is not None else {}
pass_arg = _PassArg.from_obj(func)
if pass_arg is _PassArg.context:
if context is None:
raise TemplateRuntimeError(
f"Attempted to invoke a context {type_name} without context."
)
args.insert(0, context)
elif pass_arg is _PassArg.eval_context:
if eval_ctx is None:
if context is not None:
eval_ctx = context.eval_ctx
else:
eval_ctx = EvalContext(self)
args.insert(0, eval_ctx)
elif pass_arg is _PassArg.environment:
args.insert(0, self)
return func(*args, **kwargs)
def call_filter(
self,
name: str,
value: t.Any,
args: t.Optional[t.Sequence[t.Any]] = None,
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
context: t.Optional[Context] = None,
eval_ctx: t.Optional[EvalContext] = None,
) -> t.Any:
"""Invoke a filter on a value the same way the compiler does.
This might return a coroutine if the filter is running from an
environment in async mode and the filter supports async
execution. It's your responsibility to await this if needed.
.. versionadded:: 2.7
"""
return self._filter_test_common(
name, value, args, kwargs, context, eval_ctx, True
)
def call_test(
self,
name: str,
value: t.Any,
args: t.Optional[t.Sequence[t.Any]] = None,
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
context: t.Optional[Context] = None,
eval_ctx: t.Optional[EvalContext] = None,
) -> t.Any:
"""Invoke a test on a value the same way the compiler does.
This might return a coroutine if the test is running from an
environment in async mode and the test supports async execution.
It's your responsibility to await this if needed.
.. versionchanged:: 3.0
Tests support ``@pass_context``, etc. decorators. Added
the ``context`` and ``eval_ctx`` parameters.
.. versionadded:: 2.7
"""
return self._filter_test_common(
name, value, args, kwargs, context, eval_ctx, False
)
def parse(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> nodes.Template:
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
self.handle_exception(source=source)
def _parse(
self, source: str, name: t.Optional[str], filename: t.Optional[str]
) -> nodes.Template:
"""Internal parsing function used by `parse` and `compile`."""
return Parser(self, source, name, filename).parse()
def lex(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> t.Iterator[t.Tuple[int, str, str]]:
"""Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = str(source)
try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
self.handle_exception(source=source)
def preprocess(
self,
source: str,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> str:
"""Preprocesses the source with all extensions. This is automatically
called for all parsing and compiling methods but *not* for :meth:`lex`
because there you usually only want the actual source tokenized.
"""
return reduce(
lambda s, e: e.preprocess(s, name, filename),
self.iter_extensions(),
str(source),
)
def _tokenize(
self,
source: str,
name: t.Optional[str],
filename: t.Optional[str] = None,
state: t.Optional[str] = None,
) -> TokenStream:
"""Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
"""
source = self.preprocess(source, name, filename)
stream = self.lexer.tokenize(source, name, filename, state)
for ext in self.iter_extensions():
stream = ext.filter_stream(stream) # type: ignore
if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename) # type: ignore
return stream
def _generate(
self,
source: nodes.Template,
name: t.Optional[str],
filename: t.Optional[str],
defer_init: bool = False,
) -> str:
"""Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
"""
return generate( # type: ignore
source,
self,
name,
filename,
defer_init=defer_init,
optimized=self.optimized,
)
def _compile(self, source: str, filename: str) -> CodeType:
"""Internal hook that can be overridden to hook a different compile
method in.
.. versionadded:: 2.5
"""
return compile(source, filename, "exec") # type: ignore
def compile( # type: ignore
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: "te.Literal[False]" = False,
defer_init: bool = False,
) -> CodeType:
...
def compile(
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: "te.Literal[True]" = ...,
defer_init: bool = False,
) -> str:
...
def compile(
self,
source: t.Union[str, nodes.Template],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
raw: bool = False,
defer_init: bool = False,
) -> t.Union[str, CodeType]:
"""Compile a node or template source code. The `name` parameter is
the load name of the template after it was joined using
:meth:`join_path` if necessary, not the filename on the file system.
the `filename` parameter is the estimated filename of the template on
the file system. If the template came from a database or memory this
can be omitted.
The return value of this method is a python code object. If the `raw`
parameter is `True` the return value will be a string with python
code equivalent to the bytecode returned otherwise. This method is
mainly used internally.
`defer_init` is use internally to aid the module code generator. This
causes the generated code to be able to import without the global
environment variable to be set.
.. versionadded:: 2.4
`defer_init` parameter added.
"""
source_hint = None
try:
if isinstance(source, str):
source_hint = source
source = self._parse(source, name, filename)
source = self._generate(source, name, filename, defer_init=defer_init)
if raw:
return source
if filename is None:
filename = "<template>"
return self._compile(source, filename)
except TemplateSyntaxError:
self.handle_exception(source=source_hint)
def compile_expression(
self, source: str, undefined_to_none: bool = True
) -> "TemplateExpression":
"""A handy helper method that returns a callable that accepts keyword
arguments that appear as variables in the expression. If called it
returns the result of the expression.
This is useful if applications want to use the same rules as Jinja
in template "configuration files" or similar situations.
Example usage:
>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True
Per default the return value is converted to `None` if the
expression returns an undefined value. This can be changed
by setting `undefined_to_none` to `False`.
>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined
.. versionadded:: 2.1
"""
parser = Parser(self, source, state="variable")
try:
expr = parser.parse_expression()
if not parser.stream.eos:
raise TemplateSyntaxError(
"chunk after expression", parser.stream.current.lineno, None, None
)
expr.set_environment(self)
except TemplateSyntaxError:
self.handle_exception(source=source)
body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
template = self.from_string(nodes.Template(body, lineno=1))
return TemplateExpression(template, undefined_to_none)
def compile_templates(
self,
target: t.Union[str, os.PathLike],
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
zip: t.Optional[str] = "deflated",
log_function: t.Optional[t.Callable[[str], None]] = None,
ignore_errors: bool = True,
) -> None:
"""Finds all the templates the loader can find, compiles them
and stores them in `target`. If `zip` is `None`, instead of in a
zipfile, the templates will be stored in a directory.
By default a deflate zip algorithm is used. To switch to
the stored algorithm, `zip` can be set to ``'stored'``.
`extensions` and `filter_func` are passed to :meth:`list_templates`.
Each template returned will be compiled to the target folder or
zipfile.
By default template compilation errors are ignored. In case a
log function is provided, errors are logged. If you want template
syntax errors to abort the compilation you can set `ignore_errors`
to `False` and you will get an exception on syntax errors.
.. versionadded:: 2.4
"""
from .loaders import ModuleLoader
if log_function is None:
def log_function(x: str) -> None:
pass
assert log_function is not None
assert self.loader is not None, "No loader configured."
def write_file(filename: str, data: str) -> None:
if zip:
info = ZipInfo(filename)
info.external_attr = 0o755 << 16
zip_file.writestr(info, data)
else:
with open(os.path.join(target, filename), "wb") as f:
f.write(data.encode("utf8"))
if zip is not None:
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
zip_file = ZipFile(
target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
)
log_function(f"Compiling into Zip archive {target!r}")
else:
if not os.path.isdir(target):
os.makedirs(target)
log_function(f"Compiling into folder {target!r}")
try:
for name in self.list_templates(extensions, filter_func):
source, filename, _ = self.loader.get_source(self, name)
try:
code = self.compile(source, name, filename, True, True)
except TemplateSyntaxError as e:
if not ignore_errors:
raise
log_function(f'Could not compile "{name}": {e}')
continue
filename = ModuleLoader.get_module_filename(name)
write_file(filename, code)
log_function(f'Compiled "{name}" as {filename}')
finally:
if zip:
zip_file.close()
log_function("Finished compiling templates")
def list_templates(
self,
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
) -> t.List[str]:
"""Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4
"""
assert self.loader is not None, "No loader configured."
names = self.loader.list_templates()
if extensions is not None:
if filter_func is not None:
raise TypeError(
"either extensions or filter_func can be passed, but not both"
)
def filter_func(x: str) -> bool:
return "." in x and x.rsplit(".", 1)[1] in extensions # type: ignore
if filter_func is not None:
names = [name for name in names if filter_func(name)]
return names
def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
"""Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template.
"""
from .debug import rewrite_traceback_stack
raise rewrite_traceback_stack(source=source)
def join_path(self, template: str, parent: str) -> str:
"""Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here.
"""
return template
def _load_template(
self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]
) -> "Template":
if self.loader is None:
raise TypeError("no loader for this environment specified")
cache_key = (weakref.ref(self.loader), name)
if self.cache is not None:
template = self.cache.get(cache_key)
if template is not None and (
not self.auto_reload or template.is_up_to_date
):
# template.globals is a ChainMap, modifying it will only
# affect the template, not the environment globals.
if globals:
template.globals.update(globals)
return template
template = self.loader.load(self, name, self.make_globals(globals))
if self.cache is not None:
self.cache[cache_key] = template
return template
def get_template(
self,
name: t.Union[str, "Template"],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Load a template by name with :attr:`loader` and return a
:class:`Template`. If the template does not exist a
:exc:`TemplateNotFound` exception is raised.
:param name: Name of the template to load. When loading
templates from the filesystem, "/" is used as the path
separator, even on Windows.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.4
If ``name`` is a :class:`Template` object it is returned
unchanged.
"""
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
return self._load_template(name, globals)
def select_template(
self,
names: t.Iterable[t.Union[str, "Template"]],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Like :meth:`get_template`, but tries loading multiple names.
If none of the names can be loaded a :exc:`TemplatesNotFound`
exception is raised.
:param names: List of template names to try loading in order.
:param parent: The name of the parent template importing this
template. :meth:`join_path` can be used to implement name
transformations with this.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
.. versionchanged:: 3.0
If a template is loaded from cache, ``globals`` will update
the template's globals instead of ignoring the new values.
.. versionchanged:: 2.11
If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
is raised instead. If no templates were found and ``names``
contains :class:`Undefined`, the message is more helpful.
.. versionchanged:: 2.4
If ``names`` contains a :class:`Template` object it is
returned unchanged.
.. versionadded:: 2.3
"""
if isinstance(names, Undefined):
names._fail_with_undefined_error()
if not names:
raise TemplatesNotFound(
message="Tried to select from an empty list of templates."
)
for name in names:
if isinstance(name, Template):
return name
if parent is not None:
name = self.join_path(name, parent)
try:
return self._load_template(name, globals)
except (TemplateNotFound, UndefinedError):
pass
raise TemplatesNotFound(names) # type: ignore
def get_or_select_template(
self,
template_name_or_list: t.Union[
str, "Template", t.List[t.Union[str, "Template"]]
],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
) -> "Template":
"""Use :meth:`select_template` if an iterable of template names
is given, or :meth:`get_template` if one name is given.
.. versionadded:: 2.3
"""
if isinstance(template_name_or_list, (str, Undefined)):
return self.get_template(template_name_or_list, parent, globals)
elif isinstance(template_name_or_list, Template):
return template_name_or_list
return self.select_template(template_name_or_list, parent, globals)
def from_string(
self,
source: t.Union[str, nodes.Template],
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
template_class: t.Optional[t.Type["Template"]] = None,
) -> "Template":
"""Load a template from a source string without using
:attr:`loader`.
:param source: Jinja source to compile into a template.
:param globals: Extend the environment :attr:`globals` with
these extra variables available for all renders of this
template. If the template has already been loaded and
cached, its globals are updated with any new items.
:param template_class: Return an instance of this
:class:`Template` class.
"""
gs = self.make_globals(globals)
cls = template_class or self.template_class
return cls.from_code(self, self.compile(source), gs, None)
def make_globals(
self, d: t.Optional[t.MutableMapping[str, t.Any]]
) -> t.MutableMapping[str, t.Any]:
"""Make the globals map for a template. Any given template
globals overlay the environment :attr:`globals`.
Returns a :class:`collections.ChainMap`. This allows any changes
to a template's globals to only affect that template, while
changes to the environment's globals are still reflected.
However, avoid modifying any globals after a template is loaded.
:param d: Dict of template-specific globals.
.. versionchanged:: 3.0
Use :class:`collections.ChainMap` to always prevent mutating
environment globals.
"""
if d is None:
d = {}
return ChainMap(d, self.globals)
Environment.template_class = Template
class TemplateSyntaxError(TemplateError):
"""Raised to tell the user that there is a problem with the template."""
def __init__(
self,
message: str,
lineno: int,
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> None:
super().__init__(message)
self.lineno = lineno
self.name = name
self.filename = filename
self.source: t.Optional[str] = None
# this is set to True if the debug.translate_syntax_error
# function translated the syntax error into a new traceback
self.translated = False
def __str__(self) -> str:
# for translated errors we only return the message
if self.translated:
return t.cast(str, self.message)
# otherwise attach some stuff
location = f"line {self.lineno}"
name = self.filename or self.name
if name:
location = f'File "{name}", {location}'
lines = [t.cast(str, self.message), " " + location]
# if the source is set, add the line to the output
if self.source is not None:
try:
line = self.source.splitlines()[self.lineno - 1]
except IndexError:
pass
else:
lines.append(" " + line.strip())
return "\n".join(lines)
def __reduce__(self): # type: ignore
# https://bugs.python.org/issue1692335 Exceptions that take
# multiple required arguments have problems with pickling.
# Without this, raises TypeError: __init__() missing 1 required
# positional argument: 'lineno'
return self.__class__, (self.message, self.lineno, self.name, self.filename)
def import_string(import_name: str, silent: bool = False) -> t.Any:
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ":" in import_name:
module, obj = import_name.split(":", 1)
elif "." in import_name:
module, _, obj = import_name.rpartition(".")
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
The provided code snippet includes necessary dependencies for implementing the `babel_extract` function. Write a Python function `def babel_extract( fileobj: t.BinaryIO, keywords: t.Sequence[str], comment_tags: t.Sequence[str], options: t.Dict[str, t.Any], ) -> t.Iterator[ t.Tuple[ int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str] ] ]` to solve the following problem:
Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceding comment that begins with one of the keywords. For best results, make sure to not have more than one gettext call in one line of code and the matching comment in the same line or the line before. .. versionchanged:: 2.5.1 The `newstyle_gettext` flag can be set to `True` to enable newstyle gettext calls. .. versionchanged:: 2.7 A `silent` option can now be provided. If set to `False` template syntax errors are propagated instead of being ignored. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results. :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples. (comments will be empty currently)
Here is the function:
def babel_extract(
fileobj: t.BinaryIO,
keywords: t.Sequence[str],
comment_tags: t.Sequence[str],
options: t.Dict[str, t.Any],
) -> t.Iterator[
t.Tuple[
int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]
]
]:
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
"""
extensions: t.Dict[t.Type[Extension], None] = {}
for extension_name in options.get("extensions", "").split(","):
extension_name = extension_name.strip()
if not extension_name:
continue
extensions[import_string(extension_name)] = None
if InternationalizationExtension not in extensions:
extensions[InternationalizationExtension] = None
def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:
return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}
silent = getbool(options, "silent", True)
environment = Environment(
options.get("block_start_string", defaults.BLOCK_START_STRING),
options.get("block_end_string", defaults.BLOCK_END_STRING),
options.get("variable_start_string", defaults.VARIABLE_START_STRING),
options.get("variable_end_string", defaults.VARIABLE_END_STRING),
options.get("comment_start_string", defaults.COMMENT_START_STRING),
options.get("comment_end_string", defaults.COMMENT_END_STRING),
options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,
options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,
getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),
getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),
defaults.NEWLINE_SEQUENCE,
getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),
tuple(extensions),
cache_size=0,
auto_reload=False,
)
if getbool(options, "trimmed"):
environment.policies["ext.i18n.trimmed"] = True
if getbool(options, "newstyle_gettext"):
environment.newstyle_gettext = True # type: ignore
source = fileobj.read().decode(options.get("encoding", "utf-8"))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError:
if not silent:
raise
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno) | Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceding comment that begins with one of the keywords. For best results, make sure to not have more than one gettext call in one line of code and the matching comment in the same line or the line before. .. versionchanged:: 2.5.1 The `newstyle_gettext` flag can be set to `True` to enable newstyle gettext calls. .. versionchanged:: 2.7 A `silent` option can now be provided. If set to `False` template syntax errors are propagated instead of being ignored. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results. :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples. (comments will be empty currently) |
172,725 | import inspect
import operator
import typing as t
from collections import deque
from markupsafe import Markup
from .utils import _PassArg
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
class EvalContext:
def __init__(
self, environment: "Environment", template_name: t.Optional[str] = None
) -> None:
def save(self) -> t.Mapping[str, t.Any]:
def revert(self, old: t.Mapping[str, t.Any]) -> None:
def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:
if ctx is None:
if node.environment is None:
raise RuntimeError(
"if no eval context is passed, the node must have an"
" attached environment."
)
return EvalContext(node.environment)
return ctx | null |
172,726 | import inspect
import operator
import typing as t
from collections import deque
from markupsafe import Markup
from .utils import _PassArg
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
class Impossible(Exception):
"""Raised if the node could not perform a requested action."""
class EvalContext:
"""Holds evaluation time information. Custom attributes can be attached
to it in extensions.
"""
def __init__(
self, environment: "Environment", template_name: t.Optional[str] = None
) -> None:
self.environment = environment
if callable(environment.autoescape):
self.autoescape = environment.autoescape(template_name)
else:
self.autoescape = environment.autoescape
self.volatile = False
def save(self) -> t.Mapping[str, t.Any]:
return self.__dict__.copy()
def revert(self, old: t.Mapping[str, t.Any]) -> None:
self.__dict__.clear()
self.__dict__.update(old)
class Tuple(Literal):
"""For loop unpacking and some other things like multiple arguments
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
is used for loading the names or storing.
"""
fields = ("items", "ctx")
items: t.List[Expr]
ctx: str
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:
eval_ctx = get_eval_context(self, eval_ctx)
return tuple(x.as_const(eval_ctx) for x in self.items)
def can_assign(self) -> bool:
for item in self.items:
if not item.can_assign():
return False
return True
class List(Literal):
"""Any list literal such as ``[1, 2, 3]``"""
fields = ("items",)
items: t.List[Expr]
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return [x.as_const(eval_ctx) for x in self.items]
class Dict(Literal):
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair` nodes.
"""
fields = ("items",)
items: t.List["Pair"]
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Dict[t.Any, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return dict(x.as_const(eval_ctx) for x in self.items)
def args_as_const(
node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
args = [x.as_const(eval_ctx) for x in node.args]
kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
if node.dyn_args is not None:
try:
args.extend(node.dyn_args.as_const(eval_ctx))
except Exception as e:
raise Impossible() from e
if node.dyn_kwargs is not None:
try:
kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
except Exception as e:
raise Impossible() from e
return args, kwargs | null |
172,727 | import inspect
import operator
import typing as t
from collections import deque
from markupsafe import Markup
from .utils import _PassArg
if t.TYPE_CHECKING:
import typing_extensions as te
from .environment import Environment
def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
raise TypeError("can't create custom node types") | null |
172,728 | import typing as t
from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
if t.TYPE_CHECKING:
from .environment import Environment
class TrackingCodeGenerator(CodeGenerator):
"""We abuse the code generator for introspection."""
def __init__(self, environment: "Environment") -> None:
super().__init__(environment, "<introspection>", "<introspection>")
self.undeclared_identifiers: t.Set[str] = set()
def write(self, x: str) -> None:
"""Don't write."""
def enter_frame(self, frame: Frame) -> None:
"""Remember all undeclared identifiers."""
super().enter_frame(frame)
for _, (action, param) in frame.symbols.loads.items():
if action == "resolve" and param not in self.environment.globals:
self.undeclared_identifiers.add(param)
The provided code snippet includes necessary dependencies for implementing the `find_undeclared_variables` function. Write a Python function `def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]` to solve the following problem:
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == {'bar'} True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well.
Here is the function:
def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]:
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast) == {'bar'}
True
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
"""
codegen = TrackingCodeGenerator(ast.environment) # type: ignore
codegen.visit(ast)
return codegen.undeclared_identifiers | Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == {'bar'} True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well. |
172,729 | import typing as t
from . import nodes
from .compiler import CodeGenerator
from .compiler import Frame
if t.TYPE_CHECKING:
from .environment import Environment
_ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)
The provided code snippet includes necessary dependencies for implementing the `find_referenced_templates` function. Write a Python function `def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]` to solve the following problem:
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') >>> list(meta.find_referenced_templates(ast)) ['layout.html', None] This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed.
Here is the function:
def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]:
"""Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
"""
template_name: t.Any
for node in ast.find_all(_ref_types):
template: nodes.Expr = node.template # type: ignore
if not isinstance(template, nodes.Const):
# a tuple with some non consts in there
if isinstance(template, (nodes.Tuple, nodes.List)):
for template_name in template.items:
# something const, only yield the strings and ignore
# non-string consts that really just make no sense
if isinstance(template_name, nodes.Const):
if isinstance(template_name.value, str):
yield template_name.value
# something dynamic in there
else:
yield None
# something dynamic we don't know about here
else:
yield None
continue
# constant is a basestring, direct template name
if isinstance(template.value, str):
yield template.value
# a tuple or list (latter *should* not happen) made of consts,
# yield the consts that are strings. We could warn here for
# non string values
elif isinstance(node, nodes.Include) and isinstance(
template.value, (tuple, list)
):
for template_name in template.value:
if isinstance(template_name, str):
yield template_name
# something else we don't care about, we could warn here
else:
yield None | Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}') >>> list(meta.find_referenced_templates(ast)) ['layout.html', None] This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed. |
172,730 | import importlib.util
import os
import posixpath
import sys
import typing as t
import weakref
import zipimport
from collections import abc
from hashlib import sha1
from importlib import import_module
from types import ModuleType
from .exceptions import TemplateNotFound
from .utils import internalcode
from .utils import open_if_exists
if t.TYPE_CHECKING:
from .environment import Environment
from .environment import Template
class TemplateNotFound(IOError, LookupError, TemplateError):
"""Raised if a template does not exist.
.. versionchanged:: 2.11
If the given name is :class:`Undefined` and no message was
provided, an :exc:`UndefinedError` is raised.
"""
# Silence the Python warning about message being deprecated since
# it's not valid here.
message: t.Optional[str] = None
def __init__(
self,
name: t.Optional[t.Union[str, "Undefined"]],
message: t.Optional[str] = None,
) -> None:
IOError.__init__(self, name)
if message is None:
from .runtime import Undefined
if isinstance(name, Undefined):
name._fail_with_undefined_error()
message = name
self.message = message
self.name = name
self.templates = [name]
def __str__(self) -> str:
return str(self.message)
The provided code snippet includes necessary dependencies for implementing the `split_template_path` function. Write a Python function `def split_template_path(template: str) -> t.List[str]` to solve the following problem:
Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error.
Here is the function:
def split_template_path(template: str) -> t.List[str]:
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in template.split("/"):
if (
os.path.sep in piece
or (os.path.altsep and os.path.altsep in piece)
or piece == os.path.pardir
):
raise TemplateNotFound(template)
elif piece and piece != ".":
pieces.append(piece)
return pieces | Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. |
172,731 | import ast
import builtins
import operator
from collections import ChainMap, OrderedDict, deque
from contextlib import suppress
from types import FrameType
from typing import Any, Tuple, Iterable, List, Mapping, Dict, Union, Set
from pure_eval.my_getattr_static import getattr_static
from pure_eval.utils import (
CannotEval,
has_ast_name,
copy_ast_without_context,
is_standard_types,
of_standard_types,
is_any,
of_type,
ensure_dict,
)
Any = object()
def has_ast_name(value, node):
value_name = safe_name(value)
if type(value_name) is not str:
return False
return eq_checking_types(ast_name(node), value_name)
The provided code snippet includes necessary dependencies for implementing the `is_expression_interesting` function. Write a Python function `def is_expression_interesting(node: ast.expr, value: Any) -> bool` to solve the following problem:
Determines if an expression is potentially interesting, at least in my opinion. Returns False for the following expressions whose value is generally obvious: - Literals (e.g. 123, 'abc', [1, 2, 3], {'a': (), 'b': ([1, 2], [3])}) - Variables or attributes whose name is equal to the value's __name__. For example, a function `def foo(): ...` is not interesting when referred to as `foo` as it usually would, but `bar` can be interesting if `bar is foo`. Similarly the method `self.foo` is not interesting. - Builtins (e.g. `len`) referred to by their usual name. This is a low level API, typically you will use `interesting_expressions_grouped`. :param node: an AST expression :param value: the value of the node :return: a boolean: True if the expression is interesting, False otherwise
Here is the function:
def is_expression_interesting(node: ast.expr, value: Any) -> bool:
"""
Determines if an expression is potentially interesting, at least in my opinion.
Returns False for the following expressions whose value is generally obvious:
- Literals (e.g. 123, 'abc', [1, 2, 3], {'a': (), 'b': ([1, 2], [3])})
- Variables or attributes whose name is equal to the value's __name__.
For example, a function `def foo(): ...` is not interesting when referred to
as `foo` as it usually would, but `bar` can be interesting if `bar is foo`.
Similarly the method `self.foo` is not interesting.
- Builtins (e.g. `len`) referred to by their usual name.
This is a low level API, typically you will use `interesting_expressions_grouped`.
:param node: an AST expression
:param value: the value of the node
:return: a boolean: True if the expression is interesting, False otherwise
"""
with suppress(ValueError):
ast.literal_eval(node)
return False
# TODO exclude inner modules, e.g. numpy.random.__name__ == 'numpy.random' != 'random'
# TODO exclude common module abbreviations, e.g. numpy as np, pandas as pd
if has_ast_name(value, node):
return False
if (
isinstance(node, ast.Name)
and getattr(builtins, node.id, object()) is value
):
return False
return True | Determines if an expression is potentially interesting, at least in my opinion. Returns False for the following expressions whose value is generally obvious: - Literals (e.g. 123, 'abc', [1, 2, 3], {'a': (), 'b': ([1, 2], [3])}) - Variables or attributes whose name is equal to the value's __name__. For example, a function `def foo(): ...` is not interesting when referred to as `foo` as it usually would, but `bar` can be interesting if `bar is foo`. Similarly the method `self.foo` is not interesting. - Builtins (e.g. `len`) referred to by their usual name. This is a low level API, typically you will use `interesting_expressions_grouped`. :param node: an AST expression :param value: the value of the node :return: a boolean: True if the expression is interesting, False otherwise |
172,732 | import ast
import builtins
import operator
from collections import ChainMap, OrderedDict, deque
from contextlib import suppress
from types import FrameType
from typing import Any, Tuple, Iterable, List, Mapping, Dict, Union, Set
from pure_eval.my_getattr_static import getattr_static
from pure_eval.utils import (
CannotEval,
has_ast_name,
copy_ast_without_context,
is_standard_types,
of_standard_types,
is_any,
of_type,
ensure_dict,
)
Any = object()
List = _Alias()
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]: ...
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
# To specify a variable-length tuple of homogeneous type, Tuple[T, ...]
# is used.
return self._generics_manager.is_homogenous_tuple()
def py__simple_getitem__(self, index):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
else:
if isinstance(index, int):
return self._generics_manager.get_index_and_execute(index)
debug.dbg('The getitem type on Tuple was %s' % index)
return NO_VALUES
def py__iter__(self, contextualized_node=None):
if self._is_homogenous():
yield LazyKnownValues(self._generics_manager.get_index_and_execute(0))
else:
for v in self._generics_manager.to_tuple():
yield LazyKnownValues(v.execute_annotation())
def py__getitem__(self, index_value_set, contextualized_node):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
return ValueSet.from_sets(
self._generics_manager.to_tuple()
).execute_annotation()
def _get_wrapped_value(self):
tuple_, = self.inference_state.builtins_module \
.py__getattribute__('tuple').execute_annotation()
return tuple_
def name(self):
return self._wrapped_value.name
def infer_type_vars(self, value_set):
# Circular
from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts
value_set = value_set.filter(
lambda x: x.py__name__().lower() == 'tuple',
)
if self._is_homogenous():
# The parameter annotation is of the form `Tuple[T, ...]`,
# so we treat the incoming tuple like a iterable sequence
# rather than a positional container of elements.
return self._class_value.get_generics()[0].infer_type_vars(
value_set.merge_types_of_iterate(),
)
else:
# The parameter annotation has only explicit type parameters
# (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we
# treat the incoming values as needing to match the annotation
# exactly, just as we would for non-tuple annotations.
type_var_dict = {}
for element in value_set:
try:
method = element.get_annotated_class_object
except AttributeError:
# This might still happen, because the tuple name matching
# above is not 100% correct, so just catch the remaining
# cases here.
continue
py_class = method()
merge_type_var_dicts(
type_var_dict,
merge_pairwise_generics(self._class_value, py_class),
)
return type_var_dict
def copy_ast_without_context(x):
if isinstance(x, ast.AST):
kwargs = {
field: copy_ast_without_context(getattr(x, field))
for field in x._fields
if field != 'ctx'
if hasattr(x, field)
}
return type(x)(**kwargs)
elif isinstance(x, list):
return list(map(copy_ast_without_context, x))
else:
return x
The provided code snippet includes necessary dependencies for implementing the `group_expressions` function. Write a Python function `def group_expressions(expressions: Iterable[Tuple[ast.expr, Any]]) -> List[Tuple[List[ast.expr], Any]]` to solve the following problem:
Organise expression nodes and their values such that equivalent nodes are together. Two nodes are considered equivalent if they have the same structure, ignoring context (Load, Store, or Delete) and location (lineno, col_offset). For example, this will group together the same variable name mentioned multiple times in an expression. This will not check the values of the nodes. Equivalent nodes should have the same values, unless threads are involved. This is a low level API, typically you will use `interesting_expressions_grouped`. :param expressions: pairs of AST expressions and their values, as obtained from `Evaluator.find_expressions`, or `(node, evaluator[node])`. :return: A list of pairs (tuples) containing: - A list of equivalent AST expressions - The value of the first expression node (which should be the same for all nodes, unless threads are involved)
Here is the function:
def group_expressions(expressions: Iterable[Tuple[ast.expr, Any]]) -> List[Tuple[List[ast.expr], Any]]:
"""
Organise expression nodes and their values such that equivalent nodes are together.
Two nodes are considered equivalent if they have the same structure,
ignoring context (Load, Store, or Delete) and location (lineno, col_offset).
For example, this will group together the same variable name mentioned multiple times in an expression.
This will not check the values of the nodes. Equivalent nodes should have the same values,
unless threads are involved.
This is a low level API, typically you will use `interesting_expressions_grouped`.
:param expressions: pairs of AST expressions and their values, as obtained from
`Evaluator.find_expressions`, or `(node, evaluator[node])`.
:return: A list of pairs (tuples) containing:
- A list of equivalent AST expressions
- The value of the first expression node
(which should be the same for all nodes, unless threads are involved)
"""
result = {}
for node, value in expressions:
dump = ast.dump(copy_ast_without_context(node))
result.setdefault(dump, ([], value))[0].append(node)
return list(result.values()) | Organise expression nodes and their values such that equivalent nodes are together. Two nodes are considered equivalent if they have the same structure, ignoring context (Load, Store, or Delete) and location (lineno, col_offset). For example, this will group together the same variable name mentioned multiple times in an expression. This will not check the values of the nodes. Equivalent nodes should have the same values, unless threads are involved. This is a low level API, typically you will use `interesting_expressions_grouped`. :param expressions: pairs of AST expressions and their values, as obtained from `Evaluator.find_expressions`, or `(node, evaluator[node])`. :return: A list of pairs (tuples) containing: - A list of equivalent AST expressions - The value of the first expression node (which should be the same for all nodes, unless threads are involved) |
172,733 | from collections import OrderedDict, deque
from datetime import date, time, datetime
from decimal import Decimal
from fractions import Fraction
import ast
import enum
import typing
class CannotEval(Exception):
def __repr__(self):
return self.__class__.__name__
__str__ = __repr__
def is_standard_types(x, *, check_dict_values: bool, deep: bool):
try:
return _is_standard_types_deep(x, check_dict_values, deep)[0]
except RecursionError:
return False
def of_standard_types(x, *, check_dict_values: bool, deep: bool):
if is_standard_types(x, check_dict_values=check_dict_values, deep=deep):
return x
else:
raise CannotEval | null |
172,734 | from collections import OrderedDict, deque
from datetime import date, time, datetime
from decimal import Decimal
from fractions import Fraction
import ast
import enum
import typing
The provided code snippet includes necessary dependencies for implementing the `ensure_dict` function. Write a Python function `def ensure_dict(x)` to solve the following problem:
Handles invalid non-dict inputs
Here is the function:
def ensure_dict(x):
"""
Handles invalid non-dict inputs
"""
try:
return dict(x)
except Exception:
return {} | Handles invalid non-dict inputs |
172,735 | import types
from pure_eval.utils import of_type, CannotEval
_sentinel = object()
def _static_getmro(klass):
return type.__dict__['__mro__'].__get__(klass)
def _check_instance(obj, attr):
instance_dict = {}
try:
instance_dict = object.__getattribute__(obj, "__dict__")
except AttributeError:
pass
return dict.get(instance_dict, attr, _sentinel)
def _check_class(klass, attr):
for entry in _static_getmro(klass):
if _shadowed_dict(type(entry)) is _sentinel:
try:
return entry.__dict__[attr]
except KeyError:
pass
else:
break
return _sentinel
def _is_type(obj):
try:
_static_getmro(obj)
except TypeError:
return False
return True
def _shadowed_dict(klass):
dict_attr = type.__dict__["__dict__"]
for entry in _static_getmro(klass):
try:
class_dict = dict_attr.__get__(entry)["__dict__"]
except KeyError:
pass
else:
if not (type(class_dict) is types.GetSetDescriptorType and
class_dict.__name__ == "__dict__" and
class_dict.__objclass__ is entry):
return class_dict
return _sentinel
def _resolve_descriptor(d, instance, owner):
try:
return type(of_type(d, *safe_descriptor_types)).__get__(d, instance, owner)
except AttributeError as e:
raise CannotEval from e
class CannotEval(Exception):
def __repr__(self):
return self.__class__.__name__
__str__ = __repr__
The provided code snippet includes necessary dependencies for implementing the `getattr_static` function. Write a Python function `def getattr_static(obj, attr)` to solve the following problem:
Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases. See the documentation for details.
Here is the function:
def getattr_static(obj, attr):
"""Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases. See the
documentation for details.
"""
instance_result = _sentinel
if not _is_type(obj):
klass = type(obj)
dict_attr = _shadowed_dict(klass)
if (dict_attr is _sentinel or
type(dict_attr) is types.MemberDescriptorType):
instance_result = _check_instance(obj, attr)
else:
raise CannotEval
else:
klass = obj
klass_result = _check_class(klass, attr)
if instance_result is not _sentinel and klass_result is not _sentinel:
if (_check_class(type(klass_result), '__get__') is not _sentinel and
_check_class(type(klass_result), '__set__') is not _sentinel):
return _resolve_descriptor(klass_result, obj, klass)
if instance_result is not _sentinel:
return instance_result
if klass_result is not _sentinel:
get = _check_class(type(klass_result), '__get__')
if get is _sentinel:
return klass_result
else:
if obj is klass:
instance = None
else:
instance = obj
return _resolve_descriptor(klass_result, instance, klass)
if obj is klass:
# for types we check the metaclass too
for entry in _static_getmro(type(klass)):
if _shadowed_dict(type(entry)) is _sentinel:
try:
result = entry.__dict__[attr]
get = _check_class(type(result), '__get__')
if get is not _sentinel:
raise CannotEval
return result
except KeyError:
pass
raise CannotEval | Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases. See the documentation for details. |
172,736 | import enum
import string
import unicodedata
from collections import defaultdict
import regex._regex as _regex
The provided code snippet includes necessary dependencies for implementing the `is_cased_i` function. Write a Python function `def is_cased_i(info, char)` to solve the following problem:
Checks whether a character is cased.
Here is the function:
def is_cased_i(info, char):
"Checks whether a character is cased."
return len(_regex.get_all_cases(info.flags, char)) > 1 | Checks whether a character is cased. |
172,737 | import enum
import string
import unicodedata
from collections import defaultdict
import regex._regex as _regex
The provided code snippet includes necessary dependencies for implementing the `is_cased_f` function. Write a Python function `def is_cased_f(flags, char)` to solve the following problem:
Checks whether a character is cased.
Here is the function:
def is_cased_f(flags, char):
"Checks whether a character is cased."
return len(_regex.get_all_cases(flags, char)) > 1 | Checks whether a character is cased. |
172,738 | import enum
import string
import unicodedata
from collections import defaultdict
import regex._regex as _regex
DIGITS = frozenset(string.digits)
The provided code snippet includes necessary dependencies for implementing the `is_decimal` function. Write a Python function `def is_decimal(string)` to solve the following problem:
Checks whether a string is decimal.
Here is the function:
def is_decimal(string):
"Checks whether a string is decimal."
return all(ch in DIGITS for ch in string) | Checks whether a string is decimal. |
172,739 | import enum
import string
import unicodedata
from collections import defaultdict
import regex._regex as _regex
HEX_DIGITS = frozenset(string.hexdigits)
The provided code snippet includes necessary dependencies for implementing the `is_hexadecimal` function. Write a Python function `def is_hexadecimal(string)` to solve the following problem:
Checks whether a string is hexadecimal.
Here is the function:
def is_hexadecimal(string):
"Checks whether a string is hexadecimal."
return all(ch in HEX_DIGITS for ch in string) | Checks whether a string is hexadecimal. |
172,740 | import enum
import string
import unicodedata
from collections import defaultdict
import regex._regex as _regex
class Sequence(RegexBase):
def __init__(self, items=None):
RegexBase.__init__(self)
if items is None:
items = []
self.items = items
def fix_groups(self, pattern, reverse, fuzzy):
for s in self.items:
s.fix_groups(pattern, reverse, fuzzy)
def optimise(self, info, reverse):
# Flatten the sequences.
items = []
for s in self.items:
s = s.optimise(info, reverse)
if isinstance(s, Sequence):
items.extend(s.items)
else:
items.append(s)
return make_sequence(items)
def pack_characters(self, info):
"Packs sequences of characters into strings."
items = []
characters = []
case_flags = NOCASE
for s in self.items:
if type(s) is Character and s.positive and not s.zerowidth:
if s.case_flags != case_flags:
# Different case sensitivity, so flush, unless neither the
# previous nor the new character are cased.
if s.case_flags or is_cased_i(info, s.value):
Sequence._flush_characters(info, characters,
case_flags, items)
case_flags = s.case_flags
characters.append(s.value)
elif type(s) is String or type(s) is Literal:
if s.case_flags != case_flags:
# Different case sensitivity, so flush, unless the neither
# the previous nor the new string are cased.
if s.case_flags or any(is_cased_i(info, c) for c in
characters):
Sequence._flush_characters(info, characters,
case_flags, items)
case_flags = s.case_flags
characters.extend(s.characters)
else:
Sequence._flush_characters(info, characters, case_flags, items)
items.append(s.pack_characters(info))
Sequence._flush_characters(info, characters, case_flags, items)
return make_sequence(items)
def remove_captures(self):
self.items = [s.remove_captures() for s in self.items]
return self
def is_atomic(self):
return all(s.is_atomic() for s in self.items)
def can_be_affix(self):
return False
def contains_group(self):
return any(s.contains_group() for s in self.items)
def get_firstset(self, reverse):
fs = set()
items = self.items
if reverse:
items.reverse()
for s in items:
fs |= s.get_firstset(reverse)
if None not in fs:
return fs
fs.discard(None)
return fs | set([None])
def has_simple_start(self):
return bool(self.items) and self.items[0].has_simple_start()
def _compile(self, reverse, fuzzy):
seq = self.items
if reverse:
seq = seq[::-1]
code = []
for s in seq:
code.extend(s.compile(reverse, fuzzy))
return code
def dump(self, indent, reverse):
for s in self.items:
s.dump(indent, reverse)
def _flush_characters(info, characters, case_flags, items):
if not characters:
return
# Disregard case_flags if all of the characters are case-less.
if case_flags & IGNORECASE:
if not any(is_cased_i(info, c) for c in characters):
case_flags = NOCASE
if (case_flags & FULLIGNORECASE) == FULLIGNORECASE:
literals = Sequence._fix_full_casefold(characters)
for item in literals:
chars = item.characters
if len(chars) == 1:
items.append(Character(chars[0], case_flags=item.case_flags))
else:
items.append(String(chars, case_flags=item.case_flags))
else:
if len(characters) == 1:
items.append(Character(characters[0], case_flags=case_flags))
else:
items.append(String(characters, case_flags=case_flags))
characters[:] = []
def _fix_full_casefold(characters):
# Split a literal needing full case-folding into chunks that need it
# and chunks that can use simple case-folding, which is faster.
expanded = [_regex.fold_case(FULL_CASE_FOLDING, c) for c in
_regex.get_expand_on_folding()]
string = _regex.fold_case(FULL_CASE_FOLDING, ''.join(chr(c)
for c in characters)).lower()
chunks = []
for e in expanded:
found = string.find(e)
while found >= 0:
chunks.append((found, found + len(e)))
found = string.find(e, found + 1)
pos = 0
literals = []
for start, end in Sequence._merge_chunks(chunks):
if pos < start:
literals.append(Literal(characters[pos : start],
case_flags=IGNORECASE))
literals.append(Literal(characters[start : end],
case_flags=FULLIGNORECASE))
pos = end
if pos < len(characters):
literals.append(Literal(characters[pos : ], case_flags=IGNORECASE))
return literals
def _merge_chunks(chunks):
if len(chunks) < 2:
return chunks
chunks.sort()
start, end = chunks[0]
new_chunks = []
for s, e in chunks[1 : ]:
if s <= end:
end = max(end, e)
else:
new_chunks.append((start, end))
start, end = s, e
new_chunks.append((start, end))
return new_chunks
def is_empty(self):
return all(i.is_empty() for i in self.items)
def __eq__(self, other):
return type(self) is type(other) and self.items == other.items
def max_width(self):
return sum(s.max_width() for s in self.items)
def get_required_string(self, reverse):
seq = self.items
if reverse:
seq = seq[::-1]
offset = 0
for s in seq:
ofs, req = s.get_required_string(reverse)
offset += ofs
if req:
return offset, req
return offset, None
def make_sequence(items):
if len(items) == 1:
return items[0]
return Sequence(items) | null |
172,741 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `match` function. Write a Python function `def match(pattern, string, flags=0, pos=None, endpos=None, partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.
Here is the function:
def match(pattern, string, flags=0, pos=None, endpos=None, partial=False,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Try to apply the pattern at the start of the string, returning a match
object, or None if no match was found."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.match(string, pos, endpos, concurrent, partial, timeout) | Try to apply the pattern at the start of the string, returning a match object, or None if no match was found. |
172,742 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `fullmatch` function. Write a Python function `def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Try to apply the pattern against all of the string, returning a match object, or None if no match was found.
Here is the function:
def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Try to apply the pattern against all of the string, returning a match
object, or None if no match was found."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.fullmatch(string, pos, endpos, concurrent, partial, timeout) | Try to apply the pattern against all of the string, returning a match object, or None if no match was found. |
172,743 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `search` function. Write a Python function `def search(pattern, string, flags=0, pos=None, endpos=None, partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Search through string looking for a match to the pattern, returning a match object, or None if no match was found.
Here is the function:
def search(pattern, string, flags=0, pos=None, endpos=None, partial=False,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Search through string looking for a match to the pattern, returning a
match object, or None if no match was found."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.search(string, pos, endpos, concurrent, partial, timeout) | Search through string looking for a match to the pattern, returning a match object, or None if no match was found. |
172,744 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `sub` function. Write a Python function `def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed; if a callable, it's passed the match object and must return a replacement string to be used.
Here is the function:
def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Return the string obtained by replacing the leftmost (or rightmost with a
reverse pattern) non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable; if a string,
backslash escapes in it are processed; if a callable, it's passed the match
object and must return a replacement string to be used."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.sub(repl, string, count, pos, endpos, concurrent, timeout) | Return the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed; if a callable, it's passed the match object and must return a replacement string to be used. |
172,745 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `subf` function. Write a Python function `def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in string by the replacement format. format can be either a string or a callable; if a string, it's treated as a format string; if a callable, it's passed the match object and must return a replacement string to be used.
Here is the function:
def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Return the string obtained by replacing the leftmost (or rightmost with a
reverse pattern) non-overlapping occurrences of the pattern in string by the
replacement format. format can be either a string or a callable; if a string,
it's treated as a format string; if a callable, it's passed the match object
and must return a replacement string to be used."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.subf(format, string, count, pos, endpos, concurrent, timeout) | Return the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in string by the replacement format. format can be either a string or a callable; if a string, it's treated as a format string; if a callable, it's passed the match object and must return a replacement string to be used. |
172,746 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `subn` function. Write a Python function `def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of substitutions that were made. repl can be either a string or a callable; if a string, backslash escapes in it are processed; if a callable, it's passed the match object and must return a replacement string to be used.
Here is the function:
def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Return a 2-tuple containing (new_string, number). new_string is the string
obtained by replacing the leftmost (or rightmost with a reverse pattern)
non-overlapping occurrences of the pattern in the source string by the
replacement repl. number is the number of substitutions that were made. repl
can be either a string or a callable; if a string, backslash escapes in it
are processed; if a callable, it's passed the match object and must return a
replacement string to be used."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.subn(repl, string, count, pos, endpos, concurrent, timeout) | Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of substitutions that were made. repl can be either a string or a callable; if a string, backslash escapes in it are processed; if a callable, it's passed the match object and must return a replacement string to be used. |
172,747 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `subfn` function. Write a Python function `def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in the source string by the replacement format. number is the number of substitutions that were made. format can be either a string or a callable; if a string, it's treated as a format string; if a callable, it's passed the match object and must return a replacement string to be used.
Here is the function:
def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Return a 2-tuple containing (new_string, number). new_string is the string
obtained by replacing the leftmost (or rightmost with a reverse pattern)
non-overlapping occurrences of the pattern in the source string by the
replacement format. number is the number of substitutions that were made. format
can be either a string or a callable; if a string, it's treated as a format
string; if a callable, it's passed the match object and must return a
replacement string to be used."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.subfn(format, string, count, pos, endpos, concurrent, timeout) | Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost (or rightmost with a reverse pattern) non-overlapping occurrences of the pattern in the source string by the replacement format. number is the number of substitutions that were made. format can be either a string or a callable; if a string, it's treated as a format string; if a callable, it's passed the match object and must return a replacement string to be used. |
172,748 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `split` function. Write a Python function `def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.
Here is the function:
def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None,
ignore_unused=False, **kwargs):
"""Split the source string by the occurrences of the pattern, returning a
list containing the resulting substrings. If capturing parentheses are used
in pattern, then the text of all groups in the pattern are also returned as
part of the resulting list. If maxsplit is nonzero, at most maxsplit splits
occur, and the remainder of the string is returned as the final element of
the list."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.split(string, maxsplit, concurrent, timeout) | Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. |
172,749 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `splititer` function. Write a Python function `def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return an iterator yielding the parts of a split string.
Here is the function:
def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None,
timeout=None, ignore_unused=False, **kwargs):
"Return an iterator yielding the parts of a split string."
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.splititer(string, maxsplit, concurrent, timeout) | Return an iterator yielding the parts of a split string. |
172,750 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `findall` function. Write a Python function `def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return a list of all matches in the string. The matches may be overlapped if overlapped is True. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
Here is the function:
def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Return a list of all matches in the string. The matches may be overlapped
if overlapped is True. If one or more groups are present in the pattern,
return a list of groups; this will be a list of tuples if the pattern has
more than one group. Empty matches are included in the result."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.findall(string, pos, endpos, overlapped, concurrent, timeout) | Return a list of all matches in the string. The matches may be overlapped if overlapped is True. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. |
172,751 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `finditer` function. Write a Python function `def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False, partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs)` to solve the following problem:
Return an iterator over all matches in the string. The matches may be overlapped if overlapped is True. For each match, the iterator returns a match object. Empty matches are included in the result.
Here is the function:
def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs):
"""Return an iterator over all matches in the string. The matches may be
overlapped if overlapped is True. For each match, the iterator returns a
match object. Empty matches are included in the result."""
pat = _compile(pattern, flags, ignore_unused, kwargs, True)
return pat.finditer(string, pos, endpos, overlapped, concurrent, partial,
timeout) | Return an iterator over all matches in the string. The matches may be overlapped if overlapped is True. For each match, the iterator returns a match object. Empty matches are included in the result. |
172,752 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
_cache = {}
_locale_sensitive = {}
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `purge` function. Write a Python function `def purge()` to solve the following problem:
Clear the regular expression cache
Here is the function:
def purge():
"Clear the regular expression cache"
_cache.clear()
_locale_sensitive.clear() | Clear the regular expression cache |
172,753 | _cache_all = True
import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `cache_all` function. Write a Python function `def cache_all(value=True)` to solve the following problem:
Sets whether to cache all patterns, even those are compiled explicitly. Passing None has no effect, but returns the current setting.
Here is the function:
def cache_all(value=True):
"""Sets whether to cache all patterns, even those are compiled explicitly.
Passing None has no effect, but returns the current setting."""
global _cache_all
if value is None:
return _cache_all
_cache_all = value | Sets whether to cache all patterns, even those are compiled explicitly. Passing None has no effect, but returns the current setting. |
172,754 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
"Compiles a regular expression to a PatternObject."
global DEFAULT_VERSION
try:
from regex import DEFAULT_VERSION
except ImportError:
pass
# We won't bother to cache the pattern if we're debugging.
if (flags & DEBUG) != 0:
cache_it = False
# What locale is this pattern using?
locale_key = (type(pattern), pattern)
if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
# This pattern is, or might be, locale-sensitive.
pattern_locale = _getpreferredencoding()
else:
# This pattern is definitely not locale-sensitive.
pattern_locale = None
def complain_unused_args():
if ignore_unused:
return
# Complain about any unused keyword arguments, possibly resulting from a typo.
unused_kwargs = set(kwargs) - {k for k, v in args_needed}
if unused_kwargs:
any_one = next(iter(unused_kwargs))
raise ValueError('unused keyword argument {!a}'.format(any_one))
if cache_it:
try:
# Do we know what keyword arguments are needed?
args_key = pattern, type(pattern), flags
args_needed = _named_args[args_key]
# Are we being provided with its required keyword arguments?
args_supplied = set()
if args_needed:
for k, v in args_needed:
try:
args_supplied.add((k, frozenset(kwargs[k])))
except KeyError:
raise error("missing named list: {!r}".format(k))
complain_unused_args()
args_supplied = frozenset(args_supplied)
# Have we already seen this regular expression and named list?
pattern_key = (pattern, type(pattern), flags, args_supplied,
DEFAULT_VERSION, pattern_locale)
return _cache[pattern_key]
except KeyError:
# It's a new pattern, or new named list for a known pattern.
pass
# Guess the encoding from the class of the pattern string.
if isinstance(pattern, str):
guess_encoding = UNICODE
elif isinstance(pattern, bytes):
guess_encoding = ASCII
elif isinstance(pattern, Pattern):
if flags:
raise ValueError("cannot process flags argument with a compiled pattern")
return pattern
else:
raise TypeError("first argument must be a string or compiled pattern")
# Set the default version in the core code in case it has been changed.
_regex_core.DEFAULT_VERSION = DEFAULT_VERSION
global_flags = flags
while True:
caught_exception = None
try:
source = _Source(pattern)
info = _Info(global_flags, source.char_type, kwargs)
info.guess_encoding = guess_encoding
source.ignore_space = bool(info.flags & VERBOSE)
parsed = _parse_pattern(source, info)
break
except _UnscopedFlagSet:
# Remember the global flags for the next attempt.
global_flags = info.global_flags
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
if not source.at_end():
raise error("unbalanced parenthesis", pattern, source.pos)
# Check the global flags for conflicts.
version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
if version not in (0, VERSION0, VERSION1):
raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
if isinstance(pattern, bytes) and (info.flags & UNICODE):
raise ValueError("cannot use UNICODE flag with a bytes pattern")
if not (info.flags & _ALL_ENCODINGS):
if isinstance(pattern, str):
info.flags |= UNICODE
else:
info.flags |= ASCII
reverse = bool(info.flags & REVERSE)
fuzzy = isinstance(parsed, _Fuzzy)
# Remember whether this pattern as an inline locale flag.
_locale_sensitive[locale_key] = info.inline_locale
# Fix the group references.
caught_exception = None
try:
parsed.fix_groups(pattern, reverse, False)
except error as e:
caught_exception = e
if caught_exception:
raise error(caught_exception.msg, caught_exception.pattern,
caught_exception.pos)
# Should we print the parsed pattern?
if flags & DEBUG:
parsed.dump(indent=0, reverse=reverse)
# Optimise the parsed pattern.
parsed = parsed.optimise(info, reverse)
parsed = parsed.pack_characters(info)
# Get the required string.
req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
# Build the named lists.
named_lists = {}
named_list_indexes = [None] * len(info.named_lists_used)
args_needed = set()
for key, index in info.named_lists_used.items():
name, case_flags = key
values = frozenset(kwargs[name])
if case_flags:
items = frozenset(_fold_case(info, v) for v in values)
else:
items = values
named_lists[name] = values
named_list_indexes[index] = items
args_needed.add((name, values))
complain_unused_args()
# Check the features of the groups.
_check_group_features(info, parsed)
# Compile the parsed pattern. The result is a list of tuples.
code = parsed.compile(reverse)
# Is there a group call to the pattern as a whole?
key = (0, reverse, fuzzy)
ref = info.call_refs.get(key)
if ref is not None:
code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
# Add the final 'success' opcode.
code += [(_OP.SUCCESS, )]
# Compile the additional copies of the groups that we need.
for group, rev, fuz in info.additional_groups:
code += group.compile(rev, fuz)
# Flatten the code into a list of ints.
code = _flatten_code(code)
if not parsed.has_simple_start():
# Get the first set, if possible.
try:
fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
fs_code = _flatten_code(fs_code)
code = fs_code + code
except _FirstSetError:
pass
# The named capture groups.
index_group = dict((v, n) for n, v in info.group_index.items())
# Create the PatternObject.
#
# Local flags like IGNORECASE affect the code generation, but aren't needed
# by the PatternObject itself. Conversely, global flags like LOCALE _don't_
# affect the code generation but _are_ needed by the PatternObject.
compiled_pattern = _regex.compile(pattern, info.flags | version, code,
info.group_index, index_group, named_lists, named_list_indexes,
req_offset, req_chars, req_flags, info.group_count)
# Do we need to reduce the size of the cache?
if len(_cache) >= _MAXCACHE:
with _cache_lock:
_shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
if cache_it:
if (info.flags & LOCALE) == 0:
pattern_locale = None
args_needed = frozenset(args_needed)
# Store this regular expression and named list.
pattern_key = (pattern, type(pattern), flags, args_needed,
DEFAULT_VERSION, pattern_locale)
_cache[pattern_key] = compiled_pattern
# Store what keyword arguments are needed.
_named_args[args_key] = args_needed
return compiled_pattern
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `template` function. Write a Python function `def template(pattern, flags=0)` to solve the following problem:
Compile a template pattern, returning a pattern object.
Here is the function:
def template(pattern, flags=0):
"Compile a template pattern, returning a pattern object."
return _compile(pattern, flags | TEMPLATE, False, {}, False) | Compile a template pattern, returning a pattern object. |
172,755 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
_METACHARS = frozenset("()[]{}?*+|^$\\.-#&~")
import copyreg as _copy_reg
The provided code snippet includes necessary dependencies for implementing the `escape` function. Write a Python function `def escape(pattern, special_only=True, literal_spaces=False)` to solve the following problem:
Escape a string for use as a literal in a pattern. If special_only is True, escape only special characters, else escape all non-alphanumeric characters. If literal_spaces is True, don't escape spaces.
Here is the function:
def escape(pattern, special_only=True, literal_spaces=False):
"""Escape a string for use as a literal in a pattern. If special_only is
True, escape only special characters, else escape all non-alphanumeric
characters. If literal_spaces is True, don't escape spaces."""
# Convert it to Unicode.
if isinstance(pattern, bytes):
p = pattern.decode("latin-1")
else:
p = pattern
s = []
if special_only:
for c in p:
if c == " " and literal_spaces:
s.append(c)
elif c in _METACHARS or c.isspace():
s.append("\\")
s.append(c)
elif c == "\x00":
s.append("\\000")
else:
s.append(c)
else:
for c in p:
if c == " " and literal_spaces:
s.append(c)
elif c in _ALNUM:
s.append(c)
elif c == "\x00":
s.append("\\000")
else:
s.append("\\")
s.append(c)
r = "".join(s)
# Convert it back to bytes if necessary.
if isinstance(pattern, bytes):
r = r.encode("latin-1")
return r | Escape a string for use as a literal in a pattern. If special_only is True, escape only special characters, else escape all non-alphanumeric characters. If literal_spaces is True, don't escape spaces. |
172,756 | import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
_replacement_cache = {}
_MAXREPCACHE = 500
import copyreg as _copy_reg
def _compile_replacement(source, pattern, is_unicode):
"Compiles a replacement template escape sequence."
ch = source.get()
if ch in ALPHA:
# An alphabetic escape sequence.
value = CHARACTER_ESCAPES.get(ch)
if value:
return False, [ord(value)]
if ch in HEX_ESCAPES and (ch == "x" or is_unicode):
# A hexadecimal escape sequence.
return False, [parse_repl_hex_escape(source, HEX_ESCAPES[ch], ch)]
if ch == "g":
# A group preference.
return True, [compile_repl_group(source, pattern)]
if ch == "N" and is_unicode:
# A named character.
value = parse_repl_named_char(source)
if value is not None:
return False, [value]
raise error("bad escape \\%s" % ch, source.string, source.pos)
if isinstance(source.sep, bytes):
octal_mask = 0xFF
else:
octal_mask = 0x1FF
if ch == "0":
# An octal escape sequence.
digits = ch
while len(digits) < 3:
saved_pos = source.pos
ch = source.get()
if ch not in OCT_DIGITS:
source.pos = saved_pos
break
digits += ch
return False, [int(digits, 8) & octal_mask]
if ch in DIGITS:
# Either an octal escape sequence (3 digits) or a group reference (max
# 2 digits).
digits = ch
saved_pos = source.pos
ch = source.get()
if ch in DIGITS:
digits += ch
saved_pos = source.pos
ch = source.get()
if ch and is_octal(digits + ch):
# An octal escape sequence.
return False, [int(digits + ch, 8) & octal_mask]
# A group reference.
source.pos = saved_pos
return True, [int(digits)]
if ch == "\\":
# An escaped backslash is a backslash.
return False, [ord("\\")]
if not ch:
# A trailing backslash.
raise error("bad escape (end of pattern)", source.string, source.pos)
# An escaped non-backslash is a backslash followed by the literal.
return False, [ord("\\"), ord(ch)]
The provided code snippet includes necessary dependencies for implementing the `_compile_replacement_helper` function. Write a Python function `def _compile_replacement_helper(pattern, template)` to solve the following problem:
Compiles a replacement template.
Here is the function:
def _compile_replacement_helper(pattern, template):
"Compiles a replacement template."
# This function is called by the _regex module.
# Have we seen this before?
key = pattern.pattern, pattern.flags, template
compiled = _replacement_cache.get(key)
if compiled is not None:
return compiled
if len(_replacement_cache) >= _MAXREPCACHE:
_replacement_cache.clear()
is_unicode = isinstance(template, str)
source = _Source(template)
if is_unicode:
def make_string(char_codes):
return "".join(chr(c) for c in char_codes)
else:
def make_string(char_codes):
return bytes(char_codes)
compiled = []
literal = []
while True:
ch = source.get()
if not ch:
break
if ch == "\\":
# '_compile_replacement' will return either an int group reference
# or a string literal. It returns items (plural) in order to handle
# a 2-character literal (an invalid escape sequence).
is_group, items = _compile_replacement(source, pattern, is_unicode)
if is_group:
# It's a group, so first flush the literal.
if literal:
compiled.append(make_string(literal))
literal = []
compiled.extend(items)
else:
literal.extend(items)
else:
literal.append(ord(ch))
# Flush the literal.
if literal:
compiled.append(make_string(literal))
_replacement_cache[key] = compiled
return compiled | Compiles a replacement template. |
172,757 | def compile(pattern, flags=0, ignore_unused=False, cache_pattern=None, **kwargs):
"Compile a regular expression pattern, returning a pattern object."
if cache_pattern is None:
cache_pattern = _cache_all
return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern)
import regex._regex_core as _regex_core
import regex._regex as _regex
from threading import RLock as _RLock
from locale import getpreferredencoding as _getpreferredencoding
from regex._regex_core import *
from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
_UnscopedFlagSet, _check_group_features, _compile_firstset,
_compile_replacement, _flatten_code, _fold_case, _get_required_string,
_parse_pattern, _shrink_cache)
from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
as _Source, Fuzzy as _Fuzzy)
import copyreg as _copy_reg
def _pickle(pattern):
return _regex.compile, pattern._pickled_data | null |
172,758 | import winerror
from win32com.server.exception import Exception
class Interpreter:
def __init__(self):
def Eval(self, exp):
def Exec(self, exp):
def Register():
import win32com.server.register
return win32com.server.register.UseCommandLine(Interpreter) | null |
172,759 | import pythoncom
import pywintypes
import winerror
from pythoncom import DISPATCH_METHOD, DISPATCH_PROPERTYGET
from win32com.server import policy, util
from win32com.server.exception import COMException
from winerror import S_OK
class DictionaryPolicy(policy.BasicWrapPolicy):
### BasicWrapPolicy looks for this
_com_interfaces_ = []
### BasicWrapPolicy looks for this
_name_to_dispid_ = {
"item": pythoncom.DISPID_VALUE,
"_newenum": pythoncom.DISPID_NEWENUM,
"count": 1,
}
### Auto-Registration process looks for these...
_reg_desc_ = "Python Dictionary"
_reg_clsid_ = "{39b61048-c755-11d0-86fa-00c04fc2e03e}"
_reg_progid_ = "Python.Dictionary"
_reg_verprogid_ = "Python.Dictionary.1"
_reg_policy_spec_ = "win32com.servers.dictionary.DictionaryPolicy"
def _CreateInstance_(self, clsid, reqIID):
self._wrap_({})
return pythoncom.WrapObject(self, reqIID)
def _wrap_(self, ob):
self._obj_ = ob # ob should be a dictionary
def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
if dispid == 0: # item
l = len(args)
if l < 1:
raise COMException(
desc="not enough parameters", scode=winerror.DISP_E_BADPARAMCOUNT
)
key = args[0]
if type(key) not in [str, str]:
### the nArgErr thing should be 0-based, not reversed... sigh
raise COMException(
desc="Key must be a string", scode=winerror.DISP_E_TYPEMISMATCH
)
key = key.lower()
if wFlags & (DISPATCH_METHOD | DISPATCH_PROPERTYGET):
if l > 1:
raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
try:
return self._obj_[key]
except KeyError:
return None # unknown keys return None (VT_NULL)
if l != 2:
raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
if args[1] is None:
# delete a key when None is assigned to it
try:
del self._obj_[key]
except KeyError:
pass
else:
self._obj_[key] = args[1]
return S_OK
if dispid == 1: # count
if not wFlags & DISPATCH_PROPERTYGET:
raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # not found
if len(args) != 0:
raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
return len(self._obj_)
if dispid == pythoncom.DISPID_NEWENUM:
return util.NewEnum(list(self._obj_.keys()))
raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
def _getidsofnames_(self, names, lcid):
### this is a copy of MappedWrapPolicy._getidsofnames_ ...
name = names[0].lower()
try:
return (self._name_to_dispid_[name],)
except KeyError:
raise COMException(
scode=winerror.DISP_E_MEMBERNOTFOUND, desc="Member not found"
)
def UseCommandLine(*classes, **flags):
unregisterInfo = "--unregister_info" in sys.argv
unregister = "--unregister" in sys.argv
flags["quiet"] = flags.get("quiet", 0) or "--quiet" in sys.argv
flags["debug"] = flags.get("debug", 0) or "--debug" in sys.argv
flags["unattended"] = flags.get("unattended", 0) or "--unattended" in sys.argv
if unregisterInfo:
return UnregisterInfoClasses(*classes, **flags)
try:
if unregister:
UnregisterClasses(*classes, **flags)
else:
RegisterClasses(*classes, **flags)
except win32api.error as exc:
# If we are on xp+ and have "access denied", retry using
# ShellExecuteEx with 'runas' verb to force elevation (vista) and/or
# admin login dialog (vista/xp)
if (
flags["unattended"]
or exc.winerror != winerror.ERROR_ACCESS_DENIED
or sys.getwindowsversion()[0] < 5
):
raise
ReExecuteElevated(flags)
def Register():
from win32com.server.register import UseCommandLine
return UseCommandLine(DictionaryPolicy) | null |
172,760 | import pythoncom
from win32com.client import gencache
def _doCreateVTable(iid, interface_name, is_dispatch, method_defs):
defn = Definition(iid, is_dispatch, method_defs)
vtbl = _univgw.CreateVTable(defn, is_dispatch)
_univgw.RegisterVTable(vtbl, iid, interface_name)
def RegisterInterfaces(typelibGUID, lcid, major, minor, interface_names=None):
ret = [] # return a list of (dispid, funcname for our policy's benefit
# First see if we have makepy support. If so, we can probably satisfy the request without loading the typelib.
try:
mod = gencache.GetModuleForTypelib(typelibGUID, lcid, major, minor)
except ImportError:
mod = None
if mod is None:
import win32com.client.build
# Load up the typelib and build (but don't cache) it now
tlb = pythoncom.LoadRegTypeLib(typelibGUID, major, minor, lcid)
typecomp_lib = tlb.GetTypeComp()
if interface_names is None:
interface_names = []
for i in range(tlb.GetTypeInfoCount()):
info = tlb.GetTypeInfo(i)
doc = tlb.GetDocumentation(i)
attr = info.GetTypeAttr()
if attr.typekind == pythoncom.TKIND_INTERFACE or (
attr.typekind == pythoncom.TKIND_DISPATCH
and attr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL
):
interface_names.append(doc[0])
for name in interface_names:
type_info, type_comp = typecomp_lib.BindType(
name,
)
# Not sure why we don't get an exception here - BindType's C
# impl looks correct..
if type_info is None:
raise ValueError("The interface '%s' can not be located" % (name,))
# If we got back a Dispatch interface, convert to the real interface.
attr = type_info.GetTypeAttr()
if attr.typekind == pythoncom.TKIND_DISPATCH:
refhtype = type_info.GetRefTypeOfImplType(-1)
type_info = type_info.GetRefTypeInfo(refhtype)
attr = type_info.GetTypeAttr()
item = win32com.client.build.VTableItem(
type_info, attr, type_info.GetDocumentation(-1)
)
_doCreateVTable(
item.clsid, item.python_name, item.bIsDispatch, item.vtableFuncs
)
for info in item.vtableFuncs:
names, dispid, desc = info
invkind = desc[4]
ret.append((dispid, invkind, names[0]))
else:
# Cool - can used cached info.
if not interface_names:
interface_names = list(mod.VTablesToClassMap.values())
for name in interface_names:
try:
iid = mod.NamesToIIDMap[name]
except KeyError:
raise ValueError(
"Interface '%s' does not exist in this cached typelib" % (name,)
)
# print "Processing interface", name
sub_mod = gencache.GetModuleForCLSID(iid)
is_dispatch = getattr(sub_mod, name + "_vtables_dispatch_", None)
method_defs = getattr(sub_mod, name + "_vtables_", None)
if is_dispatch is None or method_defs is None:
raise ValueError("Interface '%s' is IDispatch only" % (name,))
# And create the univgw defn
_doCreateVTable(iid, name, is_dispatch, method_defs)
for info in method_defs:
names, dispid, desc = info
invkind = desc[4]
ret.append((dispid, invkind, names[0]))
return ret | null |
172,761 | import pythoncom
from win32com.client import gencache
_univgw = pythoncom._univgw
def _CalcTypeSize(typeTuple):
t = typeTuple[0]
if t & (pythoncom.VT_BYREF | pythoncom.VT_ARRAY):
# Its a pointer.
cb = _univgw.SizeOfVT(pythoncom.VT_PTR)[1]
elif t == pythoncom.VT_RECORD:
# Just because a type library uses records doesn't mean the user
# is trying to. We need to better place to warn about this, but it
# isn't here.
# try:
# import warnings
# warnings.warn("warning: records are known to not work for vtable interfaces")
# except ImportError:
# print "warning: records are known to not work for vtable interfaces"
cb = _univgw.SizeOfVT(pythoncom.VT_PTR)[1]
# cb = typeInfo.GetTypeAttr().cbSizeInstance
else:
cb = _univgw.SizeOfVT(t)[1]
return cb | null |
172,762 | import pythoncom
import win32api
import win32con
The provided code snippet includes necessary dependencies for implementing the `IIDToInterfaceName` function. Write a Python function `def IIDToInterfaceName(iid)` to solve the following problem:
Converts an IID to a string interface name. Used primarily for debugging purposes, this allows a cryptic IID to be converted to a useful string name. This will firstly look for interfaces known (ie, registered) by pythoncom. If not known, it will look in the registry for a registered interface. iid -- An IID object. Result -- Always a string - either an interface name, or '<Unregistered interface>'
Here is the function:
def IIDToInterfaceName(iid):
"""Converts an IID to a string interface name.
Used primarily for debugging purposes, this allows a cryptic IID to
be converted to a useful string name. This will firstly look for interfaces
known (ie, registered) by pythoncom. If not known, it will look in the
registry for a registered interface.
iid -- An IID object.
Result -- Always a string - either an interface name, or '<Unregistered interface>'
"""
try:
return pythoncom.ServerInterfaces[iid]
except KeyError:
try:
try:
return win32api.RegQueryValue(
win32con.HKEY_CLASSES_ROOT, "Interface\\%s" % iid
)
except win32api.error:
pass
except ImportError:
pass
return str(iid) | Converts an IID to a string interface name. Used primarily for debugging purposes, this allows a cryptic IID to be converted to a useful string name. This will firstly look for interfaces known (ie, registered) by pythoncom. If not known, it will look in the registry for a registered interface. iid -- An IID object. Result -- Always a string - either an interface name, or '<Unregistered interface>' |
172,763 | import re
import traceback
def test_regex(r, text):
res = r.search(text, 0)
if res == -1:
print("** Not found")
else:
print(
"%d\n%s\n%s\n%s\n%s" % (res, r.group(1), r.group(2), r.group(3), r.group(4))
) | null |
172,764 | import re
from . import makegwparse
def _write_ifc_h(f, interface):
f.write(
"""\
// ---------------------------------------------------
//
// Interface Declaration
class Py%s : public Py%s
{
public:
MAKE_PYCOM_CTOR(Py%s);
static %s *GetI(PyObject *self);
static PyComTypeObject type;
// The Python methods
"""
% (interface.name, interface.base, interface.name, interface.name)
)
for method in interface.methods:
f.write(
"\tstatic PyObject *%s(PyObject *self, PyObject *args);\n" % method.name
)
f.write(
"""\
protected:
Py%s(IUnknown *pdisp);
~Py%s();
};
"""
% (interface.name, interface.name)
)
def _write_ifc_cpp(f, interface):
name = interface.name
f.write(
"""\
// ---------------------------------------------------
//
// Interface Implementation
Py%(name)s::Py%(name)s(IUnknown *pdisp):
Py%(base)s(pdisp)
{
ob_type = &type;
}
Py%(name)s::~Py%(name)s()
{
}
/* static */ %(name)s *Py%(name)s::GetI(PyObject *self)
{
return (%(name)s *)Py%(base)s::GetI(self);
}
"""
% (interface.__dict__)
)
ptr = re.sub("[a-z]", "", interface.name)
strdict = {"interfacename": interface.name, "ptr": ptr}
for method in interface.methods:
strdict["method"] = method.name
f.write(
"""\
// @pymethod |Py%(interfacename)s|%(method)s|Description of %(method)s.
PyObject *Py%(interfacename)s::%(method)s(PyObject *self, PyObject *args)
{
%(interfacename)s *p%(ptr)s = GetI(self);
if ( p%(ptr)s == NULL )
return NULL;
"""
% strdict
)
argsParseTuple = (
argsCOM
) = (
formatChars
) = codePost = codePobjects = codeCobjects = cleanup = cleanup_gil = ""
needConversion = 0
# if method.name=="Stat": import win32dbg;win32dbg.brk()
for arg in method.args:
try:
argCvt = makegwparse.make_arg_converter(arg)
if arg.HasAttribute("in"):
val = argCvt.GetFormatChar()
if val:
f.write("\t" + argCvt.GetAutoduckString() + "\n")
formatChars = formatChars + val
argsParseTuple = (
argsParseTuple + ", " + argCvt.GetParseTupleArg()
)
codePobjects = (
codePobjects + argCvt.DeclareParseArgTupleInputConverter()
)
codePost = codePost + argCvt.GetParsePostCode()
needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
cleanup = cleanup + argCvt.GetInterfaceArgCleanup()
cleanup_gil = cleanup_gil + argCvt.GetInterfaceArgCleanupGIL()
comArgName, comArgDeclString = argCvt.GetInterfaceCppObjectInfo()
if comArgDeclString: # If we should declare a variable
codeCobjects = codeCobjects + "\t%s;\n" % (comArgDeclString)
argsCOM = argsCOM + ", " + comArgName
except makegwparse.error_not_supported as why:
f.write(
'// *** The input argument %s of type "%s" was not processed ***\n// Please check the conversion function is appropriate and exists!\n'
% (arg.name, arg.raw_type)
)
f.write(
"\t%s %s;\n\tPyObject *ob%s;\n" % (arg.type, arg.name, arg.name)
)
f.write(
"\t// @pyparm <o Py%s>|%s||Description for %s\n"
% (arg.type, arg.name, arg.name)
)
codePost = (
codePost
+ "\tif (bPythonIsHappy && !PyObject_As%s( ob%s, &%s )) bPythonIsHappy = FALSE;\n"
% (arg.type, arg.name, arg.name)
)
formatChars = formatChars + "O"
argsParseTuple = argsParseTuple + ", &ob%s" % (arg.name)
argsCOM = argsCOM + ", " + arg.name
cleanup = cleanup + "\tPyObject_Free%s(%s);\n" % (arg.type, arg.name)
if needConversion:
f.write("\tUSES_CONVERSION;\n")
f.write(codePobjects)
f.write(codeCobjects)
f.write(
'\tif ( !PyArg_ParseTuple(args, "%s:%s"%s) )\n\t\treturn NULL;\n'
% (formatChars, method.name, argsParseTuple)
)
if codePost:
f.write("\tBOOL bPythonIsHappy = TRUE;\n")
f.write(codePost)
f.write("\tif (!bPythonIsHappy) return NULL;\n")
strdict["argsCOM"] = argsCOM[1:]
strdict["cleanup"] = cleanup
strdict["cleanup_gil"] = cleanup_gil
f.write(
""" HRESULT hr;
PY_INTERFACE_PRECALL;
hr = p%(ptr)s->%(method)s(%(argsCOM)s );
%(cleanup)s
PY_INTERFACE_POSTCALL;
%(cleanup_gil)s
if ( FAILED(hr) )
return PyCom_BuildPyException(hr, p%(ptr)s, IID_%(interfacename)s );
"""
% strdict
)
codePre = codePost = formatChars = codeVarsPass = codeDecl = ""
for arg in method.args:
if not arg.HasAttribute("out"):
continue
try:
argCvt = makegwparse.make_arg_converter(arg)
formatChar = argCvt.GetFormatChar()
if formatChar:
formatChars = formatChars + formatChar
codePre = codePre + argCvt.GetBuildForInterfacePreCode()
codePost = codePost + argCvt.GetBuildForInterfacePostCode()
codeVarsPass = codeVarsPass + ", " + argCvt.GetBuildValueArg()
codeDecl = codeDecl + argCvt.DeclareParseArgTupleInputConverter()
except makegwparse.error_not_supported as why:
f.write(
'// *** The output argument %s of type "%s" was not processed ***\n// %s\n'
% (arg.name, arg.raw_type, why)
)
continue
if formatChars:
f.write(
'%s\n%s\tPyObject *pyretval = Py_BuildValue("%s"%s);\n%s\treturn pyretval;'
% (codeDecl, codePre, formatChars, codeVarsPass, codePost)
)
else:
f.write("\tPy_INCREF(Py_None);\n\treturn Py_None;\n")
f.write("\n}\n\n")
f.write("// @object Py%s|Description of the interface\n" % (name))
f.write("static struct PyMethodDef Py%s_methods[] =\n{\n" % name)
for method in interface.methods:
f.write(
'\t{ "%s", Py%s::%s, 1 }, // @pymeth %s|Description of %s\n'
% (method.name, interface.name, method.name, method.name, method.name)
)
interfacebase = interface.base
f.write(
"""\
{ NULL }
};
PyComTypeObject Py%(name)s::type("Py%(name)s",
&Py%(interfacebase)s::type,
sizeof(Py%(name)s),
Py%(name)s_methods,
GET_PYCOM_CTOR(Py%(name)s));
"""
% locals()
)
def _write_gw_h(f, interface):
if interface.name[0] == "I":
gname = "PyG" + interface.name[1:]
else:
gname = "PyG" + interface.name
name = interface.name
if interface.base == "IUnknown" or interface.base == "IDispatch":
base_name = "PyGatewayBase"
else:
if interface.base[0] == "I":
base_name = "PyG" + interface.base[1:]
else:
base_name = "PyG" + interface.base
f.write(
"""\
// ---------------------------------------------------
//
// Gateway Declaration
class %s : public %s, public %s
{
protected:
%s(PyObject *instance) : %s(instance) { ; }
PYGATEWAY_MAKE_SUPPORT2(%s, %s, IID_%s, %s)
"""
% (gname, base_name, name, gname, base_name, gname, name, name, base_name)
)
if interface.base != "IUnknown":
f.write(
"\t// %s\n\t// *** Manually add %s method decls here\n\n"
% (interface.base, interface.base)
)
else:
f.write("\n\n")
f.write("\t// %s\n" % name)
for method in interface.methods:
f.write("\tSTDMETHOD(%s)(\n" % method.name)
if method.args:
for arg in method.args[:-1]:
f.write("\t\t%s,\n" % (arg.GetRawDeclaration()))
arg = method.args[-1]
f.write("\t\t%s);\n\n" % (arg.GetRawDeclaration()))
else:
f.write("\t\tvoid);\n\n")
f.write("};\n")
f.close()
def _write_gw_cpp(f, interface):
if interface.name[0] == "I":
gname = "PyG" + interface.name[1:]
else:
gname = "PyG" + interface.name
name = interface.name
if interface.base == "IUnknown" or interface.base == "IDispatch":
base_name = "PyGatewayBase"
else:
if interface.base[0] == "I":
base_name = "PyG" + interface.base[1:]
else:
base_name = "PyG" + interface.base
f.write(
"""\
// ---------------------------------------------------
//
// Gateway Implementation
"""
% {"name": name, "gname": gname, "base_name": base_name}
)
for method in interface.methods:
f.write(
"""\
STDMETHODIMP %s::%s(
"""
% (gname, method.name)
)
if method.args:
for arg in method.args[:-1]:
inoutstr = "][".join(arg.inout)
f.write("\t\t/* [%s] */ %s,\n" % (inoutstr, arg.GetRawDeclaration()))
arg = method.args[-1]
inoutstr = "][".join(arg.inout)
f.write("\t\t/* [%s] */ %s)\n" % (inoutstr, arg.GetRawDeclaration()))
else:
f.write("\t\tvoid)\n")
f.write("{\n\tPY_GATEWAY_METHOD;\n")
cout = 0
codePre = codePost = codeVars = ""
argStr = ""
needConversion = 0
formatChars = ""
if method.args:
for arg in method.args:
if arg.HasAttribute("out"):
cout = cout + 1
if arg.indirectionLevel == 2:
f.write("\tif (%s==NULL) return E_POINTER;\n" % arg.name)
if arg.HasAttribute("in"):
try:
argCvt = makegwparse.make_arg_converter(arg)
argCvt.SetGatewayMode()
formatchar = argCvt.GetFormatChar()
needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
if formatchar:
formatChars = formatChars + formatchar
codeVars = (
codeVars + argCvt.DeclareParseArgTupleInputConverter()
)
argStr = argStr + ", " + argCvt.GetBuildValueArg()
codePre = codePre + argCvt.GetBuildForGatewayPreCode()
codePost = codePost + argCvt.GetBuildForGatewayPostCode()
except makegwparse.error_not_supported as why:
f.write(
'// *** The input argument %s of type "%s" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - %s\n'
% (arg.name, arg.raw_type, why)
)
f.write(
"\tPyObject *ob%s = PyObject_From%s(%s);\n"
% (arg.name, arg.type, arg.name)
)
f.write(
'\tif (ob%s==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n'
% (arg.name, method.name)
)
codePost = codePost + "\tPy_DECREF(ob%s);\n" % arg.name
formatChars = formatChars + "O"
argStr = argStr + ", ob%s" % (arg.name)
if needConversion:
f.write("\tUSES_CONVERSION;\n")
f.write(codeVars)
f.write(codePre)
if cout:
f.write("\tPyObject *result;\n")
resStr = "&result"
else:
resStr = "NULL"
if formatChars:
fullArgStr = '%s, "%s"%s' % (resStr, formatChars, argStr)
else:
fullArgStr = resStr
f.write('\tHRESULT hr=InvokeViaPolicy("%s", %s);\n' % (method.name, fullArgStr))
f.write(codePost)
if cout:
f.write("\tif (FAILED(hr)) return hr;\n")
f.write(
"\t// Process the Python results, and convert back to the real params\n"
)
# process the output arguments.
formatChars = codePobjects = codePost = argsParseTuple = ""
needConversion = 0
for arg in method.args:
if not arg.HasAttribute("out"):
continue
try:
argCvt = makegwparse.make_arg_converter(arg)
argCvt.SetGatewayMode()
val = argCvt.GetFormatChar()
if val:
formatChars = formatChars + val
argsParseTuple = (
argsParseTuple + ", " + argCvt.GetParseTupleArg()
)
codePobjects = (
codePobjects + argCvt.DeclareParseArgTupleInputConverter()
)
codePost = codePost + argCvt.GetParsePostCode()
needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
except makegwparse.error_not_supported as why:
f.write(
'// *** The output argument %s of type "%s" was not processed ***\n// %s\n'
% (arg.name, arg.raw_type, why)
)
if formatChars: # If I have any to actually process.
if len(formatChars) == 1:
parseFn = "PyArg_Parse"
else:
parseFn = "PyArg_ParseTuple"
if codePobjects:
f.write(codePobjects)
f.write(
'\tif (!%s(result, "%s" %s))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n'
% (parseFn, formatChars, argsParseTuple, method.name)
)
if codePost:
f.write("\tBOOL bPythonIsHappy = TRUE;\n")
f.write(codePost)
f.write(
'\tif (!bPythonIsHappy) hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n'
% method.name
)
f.write("\tPy_DECREF(result);\n")
f.write("\treturn hr;\n}\n\n")
The provided code snippet includes necessary dependencies for implementing the `make_framework_support` function. Write a Python function `def make_framework_support( header_file_name, interface_name, bMakeInterface=1, bMakeGateway=1 )` to solve the following problem:
Generate C++ code for a Python Interface and Gateway header_file_name -- The full path to the .H file which defines the interface. interface_name -- The name of the interface to search for, and to generate. bMakeInterface = 1 -- Should interface (ie, client) support be generated. bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated. This method will write a .cpp and .h file into the current directory, (using the name of the interface to build the file name.
Here is the function:
def make_framework_support(
header_file_name, interface_name, bMakeInterface=1, bMakeGateway=1
):
"""Generate C++ code for a Python Interface and Gateway
header_file_name -- The full path to the .H file which defines the interface.
interface_name -- The name of the interface to search for, and to generate.
bMakeInterface = 1 -- Should interface (ie, client) support be generated.
bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated.
This method will write a .cpp and .h file into the current directory,
(using the name of the interface to build the file name.
"""
fin = open(header_file_name)
try:
interface = makegwparse.parse_interface_info(interface_name, fin)
finally:
fin.close()
if bMakeInterface and bMakeGateway:
desc = "Interface and Gateway"
elif bMakeInterface and not bMakeGateway:
desc = "Interface"
else:
desc = "Gateway"
if interface.name[:5] == "IEnum": # IEnum - use my really simple template-based one
import win32com.makegw.makegwenum
ifc_cpp_writer = win32com.makegw.makegwenum._write_enumifc_cpp
gw_cpp_writer = win32com.makegw.makegwenum._write_enumgw_cpp
else: # Use my harder working ones.
ifc_cpp_writer = _write_ifc_cpp
gw_cpp_writer = _write_gw_cpp
fout = open("Py%s.cpp" % interface.name, "w")
try:
fout.write(
"""\
// This file implements the %s %s for Python.
// Generated by makegw.py
#include "shell_pch.h"
"""
% (interface.name, desc)
)
# if bMakeGateway:
# fout.write('#include "PythonCOMServer.h"\n')
# if interface.base not in ["IUnknown", "IDispatch"]:
# fout.write('#include "Py%s.h"\n' % interface.base)
fout.write(
'#include "Py%s.h"\n\n// @doc - This file contains autoduck documentation\n'
% interface.name
)
if bMakeInterface:
ifc_cpp_writer(fout, interface)
if bMakeGateway:
gw_cpp_writer(fout, interface)
finally:
fout.close()
fout = open("Py%s.h" % interface.name, "w")
try:
fout.write(
"""\
// This file declares the %s %s for Python.
// Generated by makegw.py
"""
% (interface.name, desc)
)
if bMakeInterface:
_write_ifc_h(fout, interface)
if bMakeGateway:
_write_gw_h(fout, interface)
finally:
fout.close() | Generate C++ code for a Python Interface and Gateway header_file_name -- The full path to the .H file which defines the interface. interface_name -- The name of the interface to search for, and to generate. bMakeInterface = 1 -- Should interface (ie, client) support be generated. bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated. This method will write a .cpp and .h file into the current directory, (using the name of the interface to build the file name. |
172,765 | import winerror
FACILITY_CONTROL = 0xA
def MAKE_SCODE(sev, fac, code):
return int((int(-sev) << 31) | ((fac) << 16) | ((code)))
def STD_CTL_SCODE(n):
return MAKE_SCODE(winerror.SEVERITY_ERROR, FACILITY_CONTROL, n) | null |
172,766 | import sys
import pythoncom
from win32com import universal
from win32com.client import Dispatch, DispatchWithEvents, constants, gencache
from win32com.server.exception import COMException
def RegisterAddin(klass):
import winreg
key = winreg.CreateKey(
winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Excel\\Addins"
)
subkey = winreg.CreateKey(key, klass._reg_progid_)
winreg.SetValueEx(subkey, "CommandLineSafe", 0, winreg.REG_DWORD, 0)
winreg.SetValueEx(subkey, "LoadBehavior", 0, winreg.REG_DWORD, 3)
winreg.SetValueEx(subkey, "Description", 0, winreg.REG_SZ, "Excel Addin")
winreg.SetValueEx(subkey, "FriendlyName", 0, winreg.REG_SZ, "A Simple Excel Addin") | null |
172,767 | import sys
import pythoncom
from win32com import universal
from win32com.client import Dispatch, DispatchWithEvents, constants, gencache
from win32com.server.exception import COMException
def UnregisterAddin(klass):
import winreg
try:
winreg.DeleteKey(
winreg.HKEY_CURRENT_USER,
"Software\\Microsoft\\Office\\Excel\\Addins\\" + klass._reg_progid_,
)
except WindowsError:
pass | null |
172,768 | import pythoncom
import win32con
format_name_map = {}
tymeds = [attr for attr in pythoncom.__dict__.keys() if attr.startswith("TYMED_")]
def DumpClipboard():
do = pythoncom.OleGetClipboard()
print("Dumping all clipboard formats...")
for fe in do.EnumFormatEtc():
fmt, td, aspect, index, tymed = fe
tymeds_this = [
getattr(pythoncom, t) for t in tymeds if tymed & getattr(pythoncom, t)
]
print("Clipboard format", format_name_map.get(fmt, str(fmt)))
for t_this in tymeds_this:
# As we are enumerating there should be no need to call
# QueryGetData, but we do anyway!
fetc_query = fmt, td, aspect, index, t_this
try:
do.QueryGetData(fetc_query)
except pythoncom.com_error:
print("Eeek - QGD indicated failure for tymed", t_this)
# now actually get it.
try:
medium = do.GetData(fetc_query)
except pythoncom.com_error as exc:
print("Failed to get the clipboard data:", exc)
continue
if medium.tymed == pythoncom.TYMED_GDI:
data = "GDI handle %d" % medium.data
elif medium.tymed == pythoncom.TYMED_MFPICT:
data = "METAFILE handle %d" % medium.data
elif medium.tymed == pythoncom.TYMED_ENHMF:
data = "ENHMETAFILE handle %d" % medium.data
elif medium.tymed == pythoncom.TYMED_HGLOBAL:
data = "%d bytes via HGLOBAL" % len(medium.data)
elif medium.tymed == pythoncom.TYMED_FILE:
data = "filename '%s'" % data
elif medium.tymed == pythoncom.TYMED_ISTREAM:
stream = medium.data
stream.Seek(0, 0)
bytes = 0
while 1:
chunk = stream.Read(4096)
if not chunk:
break
bytes += len(chunk)
data = "%d bytes via IStream" % bytes
elif medium.tymed == pythoncom.TYMED_ISTORAGE:
data = "a IStorage"
else:
data = "*** unknown tymed!"
print(" -> got", data)
do = None | null |
172,769 | import sys
import pythoncom
import win32api
import win32com.client
import win32event
class ExplorerEvents:
def __init__(self):
# We reuse this event for all events.
self.event = win32event.CreateEvent(None, 0, 0, None)
def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty):
#
# Caution: Since the main thread and events thread(s) are different
# it may be necessary to serialize access to shared data. Because
# this is a simple test case, that is not required here. Your
# situation may be different. Caveat programmer.
#
thread = win32api.GetCurrentThreadId()
print("OnDocumentComplete event processed on thread %d" % thread)
# Set the event our main thread is waiting on.
win32event.SetEvent(self.event)
def OnQuit(self):
thread = win32api.GetCurrentThreadId()
print("OnQuit event processed on thread %d" % thread)
win32event.SetEvent(self.event)
def TestExplorerEvents():
iexplore = win32com.client.DispatchWithEvents(
"InternetExplorer.Application", ExplorerEvents
)
thread = win32api.GetCurrentThreadId()
print("TestExplorerEvents created IE object on thread %d" % thread)
iexplore.Visible = 1
try:
iexplore.Navigate(win32api.GetFullPathName("..\\readme.html"))
except pythoncom.com_error as details:
print("Warning - could not open the test HTML file", details)
# In this free-threaded example, we can simply wait until an event has
# been set - we will give it 2 seconds before giving up.
rc = win32event.WaitForSingleObject(iexplore.event, 2000)
if rc != win32event.WAIT_OBJECT_0:
print("Document load event FAILED to fire!!!")
iexplore.Quit()
# Now we can do the same thing to wait for exit!
# Although Quit generates events, in this free-threaded world we
# do *not* need to run any message pumps.
rc = win32event.WaitForSingleObject(iexplore.event, 2000)
if rc != win32event.WAIT_OBJECT_0:
print("OnQuit event FAILED to fire!!!")
iexplore = None
print("Finished the IE event sample!") | null |
172,770 | import pythoncom
import win32com.server.connect
import win32com.server.util
from pywin32_testutil import str2bytes
from win32com.server.exception import Exception
def CheckEvent(server, client, val, verbose):
client.last_event_arg = None
server.DoIt(val)
if client.last_event_arg != val:
raise RuntimeError("Sent %r, but got back %r" % (val, client.last_event_arg))
if verbose:
print("Sent and received %r" % val) | null |
172,771 | import time
import pythoncom
import win32api
import win32com.client
import win32event
class ExplorerEvents:
def __init__(self):
self.event = win32event.CreateEvent(None, 0, 0, None)
def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty):
thread = win32api.GetCurrentThreadId()
print("OnDocumentComplete event processed on thread %d" % thread)
# Set the event our main thread is waiting on.
win32event.SetEvent(self.event)
def OnQuit(self):
thread = win32api.GetCurrentThreadId()
print("OnQuit event processed on thread %d" % thread)
win32event.SetEvent(self.event)
def WaitWhileProcessingMessages(event, timeout=2):
start = time.perf_counter()
while True:
# Wake 4 times a second - we can't just specify the
# full timeout here, as then it would reset for every
# message we process.
rc = win32event.MsgWaitForMultipleObjects(
(event,), 0, 250, win32event.QS_ALLEVENTS
)
if rc == win32event.WAIT_OBJECT_0:
# event signalled - stop now!
return True
if (time.perf_counter() - start) > timeout:
# Timeout expired.
return False
# must be a message.
pythoncom.PumpWaitingMessages()
def TestExplorerEvents():
iexplore = win32com.client.DispatchWithEvents(
"InternetExplorer.Application", ExplorerEvents
)
thread = win32api.GetCurrentThreadId()
print("TestExplorerEvents created IE object on thread %d" % thread)
iexplore.Visible = 1
try:
iexplore.Navigate(win32api.GetFullPathName("..\\readme.html"))
except pythoncom.com_error as details:
print("Warning - could not open the test HTML file", details)
# Wait for the event to be signalled while pumping messages.
if not WaitWhileProcessingMessages(iexplore.event):
print("Document load event FAILED to fire!!!")
iexplore.Quit()
#
# Give IE a chance to shutdown, else it can get upset on fast machines.
# Note, Quit generates events. Although this test does NOT catch them
# it is NECESSARY to pump messages here instead of a sleep so that the Quit
# happens properly!
if not WaitWhileProcessingMessages(iexplore.event):
print("OnQuit event FAILED to fire!!!")
iexplore = None | null |
172,772 | import sys
import pythoncom
from win32com import universal
from win32com.client import DispatchWithEvents, constants, gencache
from win32com.server.exception import COMException
def RegisterAddin(klass):
import winreg
key = winreg.CreateKey(
winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\Addins"
)
subkey = winreg.CreateKey(key, klass._reg_progid_)
winreg.SetValueEx(subkey, "CommandLineSafe", 0, winreg.REG_DWORD, 0)
winreg.SetValueEx(subkey, "LoadBehavior", 0, winreg.REG_DWORD, 3)
winreg.SetValueEx(subkey, "Description", 0, winreg.REG_SZ, klass._reg_progid_)
winreg.SetValueEx(subkey, "FriendlyName", 0, winreg.REG_SZ, klass._reg_progid_) | null |
172,773 | import sys
import pythoncom
from win32com import universal
from win32com.client import DispatchWithEvents, constants, gencache
from win32com.server.exception import COMException
def UnregisterAddin(klass):
import winreg
try:
winreg.DeleteKey(
winreg.HKEY_CURRENT_USER,
"Software\\Microsoft\\Office\\Outlook\\Addins\\" + klass._reg_progid_,
)
except WindowsError:
pass | null |
172,774 | import pythoncom
import winerror
from . import policy
from .exception import COMException
class Collection:
"A collection of VARIANT values."
_public_methods_ = ["Item", "Count", "Add", "Remove", "Insert"]
def __init__(self, data=None, readOnly=0):
if data is None:
data = []
self.data = data
# disable Add/Remove if read-only. note that we adjust _public_methods_
# on this instance only.
if readOnly:
self._public_methods_ = ["Item", "Count"]
# This method is also used as the "default" method.
# Thus "print ob" will cause this to be called with zero
# params. Handle this slightly more elegantly here.
# Ideally the policy should handle this.
def Item(self, *args):
if len(args) != 1:
raise COMException(scode=winerror.DISP_E_BADPARAMCOUNT)
try:
return self.data[args[0]]
except IndexError as desc:
raise COMException(scode=winerror.DISP_E_BADINDEX, desc=str(desc))
_value_ = Item
def Count(self):
return len(self.data)
def Add(self, value):
self.data.append(value)
def Remove(self, index):
try:
del self.data[index]
except IndexError as desc:
raise COMException(scode=winerror.DISP_E_BADINDEX, desc=str(desc))
def Insert(self, index, value):
try:
index = int(index)
except (ValueError, TypeError):
raise COMException(scode=winerror.DISP_E_TYPEMISMATCH)
self.data.insert(index, value)
def _NewEnum(self):
return NewEnum(self.data)
The provided code snippet includes necessary dependencies for implementing the `NewCollection` function. Write a Python function `def NewCollection(seq, cls=Collection)` to solve the following problem:
Creates a new COM collection object This function creates a new COM Server that implements the common collection protocols, including enumeration. (_NewEnum) A COM server that can enumerate the passed in sequence will be created, then wrapped up for return through the COM framework. Optionally, a custom COM server for enumeration can be passed (the default is @Collection@).
Here is the function:
def NewCollection(seq, cls=Collection):
"""Creates a new COM collection object
This function creates a new COM Server that implements the
common collection protocols, including enumeration. (_NewEnum)
A COM server that can enumerate the passed in sequence will be
created, then wrapped up for return through the COM framework.
Optionally, a custom COM server for enumeration can be passed
(the default is @Collection@).
"""
return pythoncom.WrapObject(
policy.DefaultPolicy(cls(seq)), pythoncom.IID_IDispatch, pythoncom.IID_IDispatch
) | Creates a new COM collection object This function creates a new COM Server that implements the common collection protocols, including enumeration. (_NewEnum) A COM server that can enumerate the passed in sequence will be created, then wrapped up for return through the COM framework. Optionally, a custom COM server for enumeration can be passed (the default is @Collection@). |
172,775 | import sys
import pythoncom
import sys
if sys.version_info >= (3, 7):
from builtins import _PathLike
if sys.version_info >= (3, 7):
class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): # undocumented
def IsCOMException(t=None):
if t is None:
t = sys.exc_info()[0]
try:
return issubclass(t, pythoncom.com_error)
except TypeError: # 1.5 in -X mode?
return t is pythoncon.com_error | null |
172,776 | import sys
import pythoncom
class COMException(pythoncom.com_error):
"""An Exception object that is understood by the framework.
If the framework is presented with an exception of type class,
it looks for certain known attributes on this class to provide rich
error information to the caller.
It should be noted that the framework supports providing this error
information via COM Exceptions, or via the ISupportErrorInfo interface.
By using this class, you automatically provide rich error information to the
server.
"""
def __init__(
self,
description=None,
scode=None,
source=None,
helpfile=None,
helpContext=None,
desc=None,
hresult=None,
):
"""Initialize an exception
**Params**
description -- A string description for the exception.
scode -- An integer scode to be returned to the server, if necessary.
The pythoncom framework defaults this to be DISP_E_EXCEPTION if not specified otherwise.
source -- A string which identifies the source of the error.
helpfile -- A string which points to a help file which contains details on the error.
helpContext -- An integer context in the help file.
desc -- A short-cut for description.
hresult -- A short-cut for scode.
"""
# convert a WIN32 error into an HRESULT
scode = scode or hresult
if scode and scode != 1: # We dont want S_FALSE mapped!
if scode >= -32768 and scode < 32768:
# this is HRESULT_FROM_WIN32()
scode = -2147024896 | (scode & 0x0000FFFF)
self.scode = scode
self.description = description or desc
if scode == 1 and not self.description:
self.description = "S_FALSE"
elif scode and not self.description:
self.description = pythoncom.GetScodeString(scode)
self.source = source
self.helpfile = helpfile
self.helpcontext = helpContext
# todo - fill in the exception value
pythoncom.com_error.__init__(self, scode, self.description, None, -1)
def __repr__(self):
return "<COM Exception - scode=%s, desc=%s>" % (self.scode, self.description)
import sys
if sys.version_info >= (3, 7):
from builtins import _PathLike
if sys.version_info >= (3, 7):
class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
daemon_threads: bool # undocumented
def IsCOMServerException(t=None):
if t is None:
t = sys.exc_info()[0]
try:
return issubclass(t, COMException)
except TypeError: # String exception
return 0 | null |
172,777 | import sys
import pythoncom
import win32api
from win32com.server import factory
def serve(clsids):
infos = factory.RegisterClassFactories(clsids)
pythoncom.EnableQuitMessage(win32api.GetCurrentThreadId())
pythoncom.CoResumeClassObjects()
pythoncom.PumpMessages()
factory.RevokeClassFactories(infos)
pythoncom.CoUninitialize() | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.