nwo
stringlengths 10
28
| sha
stringlengths 40
40
| path
stringlengths 11
97
| identifier
stringlengths 1
64
| parameters
stringlengths 2
2.24k
| return_statement
stringlengths 0
2.17k
| docstring
stringlengths 0
5.45k
| docstring_summary
stringlengths 0
3.83k
| func_begin
int64 1
13.4k
| func_end
int64 2
13.4k
| function
stringlengths 28
56.4k
| url
stringlengths 106
209
| project
int64 1
48
| executed_lines
list | executed_lines_pc
float64 0
153
| missing_lines
list | missing_lines_pc
float64 0
100
| covered
bool 2
classes | filecoverage
float64 2.53
100
| function_lines
int64 2
1.46k
| mccabe
int64 1
253
| coverage
float64 0
100
| docstring_lines
int64 0
112
| function_nodoc
stringlengths 9
56.4k
| id
int64 0
29.8k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
ImmutableSandboxedEnvironment.is_safe_attribute
|
(self, obj: t.Any, attr: str, value: t.Any)
|
return not modifies_known_mutable(obj, attr)
| 402 | 406 |
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
if not super().is_safe_attribute(obj, attr, value):
return False
return not modifies_known_mutable(obj, attr)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L402-L406
| 42 |
[
0,
1,
3,
4
] | 80 |
[
2
] | 20 | false | 70.192308 | 5 | 2 | 80 | 0 |
def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:
if not super().is_safe_attribute(obj, attr, value):
return False
return not modifies_known_mutable(obj, attr)
| 27,661 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedFormatter.__init__
|
(self, env: Environment, **kwargs: t.Any)
| 410 | 412 |
def __init__(self, env: Environment, **kwargs: t.Any) -> None:
self._env = env
super().__init__(**kwargs)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L410-L412
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 70.192308 | 3 | 1 | 100 | 0 |
def __init__(self, env: Environment, **kwargs: t.Any) -> None:
self._env = env
super().__init__(**kwargs)
| 27,662 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/sandbox.py
|
SandboxedFormatter.get_field
|
(
self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]
)
|
return obj, first
| 414 | 424 |
def get_field(
self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]
) -> t.Tuple[t.Any, str]:
first, rest = formatter_field_name_split(field_name)
obj = self.get_value(first, args, kwargs)
for is_attr, i in rest:
if is_attr:
obj = self._env.getattr(obj, i)
else:
obj = self._env.getitem(obj, i)
return obj, first
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/sandbox.py#L414-L424
| 42 |
[
0,
3,
4,
5,
6,
7,
10
] | 63.636364 |
[
9
] | 9.090909 | false | 70.192308 | 11 | 3 | 90.909091 | 0 |
def get_field(
self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]
) -> t.Tuple[t.Any, str]:
first, rest = formatter_field_name_split(field_name)
obj = self.get_value(first, args, kwargs)
for is_attr, i in rest:
if is_attr:
obj = self._env.getattr(obj, i)
else:
obj = self._env.getitem(obj, i)
return obj, first
| 27,663 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
native_concat
|
(values: t.Iterable[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.
|
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.
| 16 | 47 |
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
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L16-L47
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31
] | 96.875 |
[
12
] | 3.125 | false | 87.777778 | 32 | 7 | 96.875 | 7 |
def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:
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
| 27,664 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeCodeGenerator._default_finalize
|
(value: t.Any)
|
return value
| 56 | 57 |
def _default_finalize(value: t.Any) -> t.Any:
return value
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L56-L57
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 87.777778 | 2 | 1 | 100 | 0 |
def _default_finalize(value: t.Any) -> t.Any:
return value
| 27,665 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeCodeGenerator._output_const_repr
|
(self, group: t.Iterable[t.Any])
|
return repr("".join([str(v) for v in group]))
| 59 | 60 |
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
return repr("".join([str(v) for v in group]))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L59-L60
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 87.777778 | 2 | 2 | 100 | 0 |
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
return repr("".join([str(v) for v in group]))
| 27,666 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeCodeGenerator._output_child_to_const
|
(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
)
|
return finalize.const(const)
| 62 | 73 |
def _output_child_to_const(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> t.Any:
const = node.as_const(frame.eval_ctx)
if not has_safe_repr(const):
raise nodes.Impossible()
if isinstance(node, nodes.TemplateData):
return const
return finalize.const(const)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L62-L73
| 42 |
[
0,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 83.333333 |
[] | 0 | false | 87.777778 | 12 | 3 | 100 | 0 |
def _output_child_to_const(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> t.Any:
const = node.as_const(frame.eval_ctx)
if not has_safe_repr(const):
raise nodes.Impossible()
if isinstance(node, nodes.TemplateData):
return const
return finalize.const(const)
| 27,667 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeCodeGenerator._output_child_pre
|
(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
)
| 75 | 79 |
def _output_child_pre(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> None:
if finalize.src is not None:
self.write(finalize.src)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L75-L79
| 42 |
[
0,
3
] | 40 |
[
4
] | 20 | false | 87.777778 | 5 | 2 | 80 | 0 |
def _output_child_pre(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> None:
if finalize.src is not None:
self.write(finalize.src)
| 27,668 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeCodeGenerator._output_child_post
|
(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
)
| 81 | 85 |
def _output_child_post(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> None:
if finalize.src is not None:
self.write(")")
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L81-L85
| 42 |
[
0,
3
] | 40 |
[
4
] | 20 | false | 87.777778 | 5 | 2 | 80 | 0 |
def _output_child_post(
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
) -> None:
if finalize.src is not None:
self.write(")")
| 27,669 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeTemplate.render
|
(self, *args: t.Any, **kwargs: t.Any)
|
Render the template to produce a native Python type. 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.
|
Render the template to produce a native Python type. 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.
| 98 | 112 |
def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
"""Render the template to produce a native Python type. 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.
"""
ctx = self.new_context(dict(*args, **kwargs))
try:
return self.environment_class.concat( # type: ignore
self.root_render_func(ctx) # type: ignore
)
except Exception:
return self.environment.handle_exception()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L98-L112
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 |
[] | 0 | true | 87.777778 | 15 | 2 | 100 | 5 |
def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
ctx = self.new_context(dict(*args, **kwargs))
try:
return self.environment_class.concat( # type: ignore
self.root_render_func(ctx) # type: ignore
)
except Exception:
return self.environment.handle_exception()
| 27,670 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nativetypes.py
|
NativeTemplate.render_async
|
(self, *args: t.Any, **kwargs: t.Any)
| 114 | 127 |
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
if not self.environment.is_async:
raise RuntimeError(
"The environment was not created with async mode enabled."
)
ctx = self.new_context(dict(*args, **kwargs))
try:
return self.environment_class.concat( # type: ignore
[n async for n in self.root_render_func(ctx)] # type: ignore
)
except Exception:
return self.environment.handle_exception()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nativetypes.py#L114-L127
| 42 |
[
0,
1,
5,
6,
7,
8,
9
] | 50 |
[
2,
12,
13
] | 21.428571 | false | 87.777778 | 14 | 4 | 78.571429 | 0 |
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
if not self.environment.is_async:
raise RuntimeError(
"The environment was not created with async mode enabled."
)
ctx = self.new_context(dict(*args, **kwargs))
try:
return self.environment_class.concat( # type: ignore
[n async for n in self.root_render_func(ctx)] # type: ignore
)
except Exception:
return self.environment.handle_exception()
| 27,671 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
pass_context
|
(f: F)
|
return 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``.
|
Pass the :class:`~jinja2.runtime.Context` as the first argument
to the decorated function when called while rendering a template.
| 29 | 43 |
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
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L29-L43
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 |
[] | 0 | true | 88.837209 | 15 | 1 | 100 | 11 |
def pass_context(f: F) -> F:
f.jinja_pass_arg = _PassArg.context # type: ignore
return f
| 27,672 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
pass_eval_context
|
(f: F)
|
return f
|
Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
to the decorated function when called while rendering a template.
See :ref:`eval-context`.
Can be used on functions, filters, and tests.
If only ``EvalContext.environment`` is needed, use
:func:`pass_environment`.
.. versionadded:: 3.0.0
Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
|
Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
to the decorated function when called while rendering a template.
See :ref:`eval-context`.
| 46 | 60 |
def pass_eval_context(f: F) -> F:
"""Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
to the decorated function when called while rendering a template.
See :ref:`eval-context`.
Can be used on functions, filters, and tests.
If only ``EvalContext.environment`` is needed, use
:func:`pass_environment`.
.. versionadded:: 3.0.0
Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
"""
f.jinja_pass_arg = _PassArg.eval_context # type: ignore
return f
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L46-L60
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 |
[] | 0 | true | 88.837209 | 15 | 1 | 100 | 11 |
def pass_eval_context(f: F) -> F:
f.jinja_pass_arg = _PassArg.eval_context # type: ignore
return f
| 27,673 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
pass_environment
|
(f: F)
|
return f
|
Pass the :class:`~jinja2.Environment` as the first argument to
the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
.. versionadded:: 3.0.0
Replaces ``environmentfunction`` and ``environmentfilter``.
|
Pass the :class:`~jinja2.Environment` as the first argument to
the decorated function when called while rendering a template.
| 63 | 73 |
def pass_environment(f: F) -> F:
"""Pass the :class:`~jinja2.Environment` as the first argument to
the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
.. versionadded:: 3.0.0
Replaces ``environmentfunction`` and ``environmentfilter``.
"""
f.jinja_pass_arg = _PassArg.environment # type: ignore
return f
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L63-L73
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 100 |
[] | 0 | true | 88.837209 | 11 | 1 | 100 | 7 |
def pass_environment(f: F) -> F:
f.jinja_pass_arg = _PassArg.environment # type: ignore
return f
| 27,674 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
internalcode
|
(f: F)
|
return f
|
Marks the function as internally used
|
Marks the function as internally used
| 89 | 92 |
def internalcode(f: F) -> F:
"""Marks the function as internally used"""
internal_code.add(f.__code__)
return f
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L89-L92
| 42 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 88.837209 | 4 | 1 | 100 | 1 |
def internalcode(f: F) -> F:
internal_code.add(f.__code__)
return f
| 27,675 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
is_undefined
|
(obj: t.Any)
|
return isinstance(obj, Undefined)
|
Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
def default(var, default=''):
if is_undefined(var):
return default
return var
|
Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
| 95 | 109 |
def is_undefined(obj: t.Any) -> bool:
"""Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
def default(var, default=''):
if is_undefined(var):
return default
return var
"""
from .runtime import Undefined
return isinstance(obj, Undefined)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L95-L109
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
] | 100 |
[] | 0 | true | 88.837209 | 15 | 1 | 100 | 10 |
def is_undefined(obj: t.Any) -> bool:
from .runtime import Undefined
return isinstance(obj, Undefined)
| 27,676 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
consume
|
(iterable: t.Iterable[t.Any])
|
Consumes an iterable without doing anything with it.
|
Consumes an iterable without doing anything with it.
| 112 | 115 |
def consume(iterable: t.Iterable[t.Any]) -> None:
"""Consumes an iterable without doing anything with it."""
for _ in iterable:
pass
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L112-L115
| 42 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 88.837209 | 4 | 2 | 100 | 1 |
def consume(iterable: t.Iterable[t.Any]) -> None:
for _ in iterable:
pass
| 27,677 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
clear_caches
|
()
|
Jinja keeps internal caches for environments and lexers. These are
used so that Jinja doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
measuring memory consumption you may want to clean the caches.
|
Jinja keeps internal caches for environments and lexers. These are
used so that Jinja doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
measuring memory consumption you may want to clean the caches.
| 118 | 128 |
def clear_caches() -> None:
"""Jinja keeps internal caches for environments and lexers. These are
used so that Jinja doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
measuring memory consumption you may want to clean the caches.
"""
from .environment import get_spontaneous_environment
from .lexer import _lexer_cache
get_spontaneous_environment.cache_clear()
_lexer_cache.clear()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L118-L128
| 42 |
[
0,
1,
2,
3,
4,
5
] | 54.545455 |
[
6,
7,
9,
10
] | 36.363636 | false | 88.837209 | 11 | 1 | 63.636364 | 4 |
def clear_caches() -> None:
from .environment import get_spontaneous_environment
from .lexer import _lexer_cache
get_spontaneous_environment.cache_clear()
_lexer_cache.clear()
| 27,678 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
import_string
|
(import_name: str, silent: bool = False)
|
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
|
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``).
| 131 | 152 |
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
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L131-L152
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
14,
15,
16,
18
] | 77.272727 |
[
13,
17,
19,
20,
21
] | 22.727273 | false | 88.837209 | 22 | 5 | 77.272727 | 9 |
def import_string(import_name: str, silent: bool = False) -> t.Any:
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
| 27,679 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
open_if_exists
|
(filename: str, mode: str = "rb")
|
return open(filename, mode)
|
Returns a file descriptor for the filename if that file exists,
otherwise ``None``.
|
Returns a file descriptor for the filename if that file exists,
otherwise ``None``.
| 155 | 162 |
def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:
"""Returns a file descriptor for the filename if that file exists,
otherwise ``None``.
"""
if not os.path.isfile(filename):
return None
return open(filename, mode)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L155-L162
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 88.837209 | 8 | 2 | 100 | 2 |
def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:
if not os.path.isfile(filename):
return None
return open(filename, mode)
| 27,680 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
object_type_repr
|
(obj: t.Any)
|
return f"{cls.__module__}.{cls.__name__} object"
|
Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
|
Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
| 165 | 180 |
def object_type_repr(obj: t.Any) -> str:
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return "None"
elif obj is Ellipsis:
return "Ellipsis"
cls = type(obj)
if cls.__module__ == "builtins":
return f"{cls.__name__} object"
return f"{cls.__module__}.{cls.__name__} object"
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L165-L180
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 |
[] | 0 | true | 88.837209 | 16 | 4 | 100 | 3 |
def object_type_repr(obj: t.Any) -> str:
if obj is None:
return "None"
elif obj is Ellipsis:
return "Ellipsis"
cls = type(obj)
if cls.__module__ == "builtins":
return f"{cls.__name__} object"
return f"{cls.__module__}.{cls.__name__} object"
| 27,681 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
pformat
|
(obj: t.Any)
|
return pformat(obj)
|
Format an object using :func:`pprint.pformat`.
|
Format an object using :func:`pprint.pformat`.
| 183 | 187 |
def pformat(obj: t.Any) -> str:
"""Format an object using :func:`pprint.pformat`."""
from pprint import pformat # type: ignore
return pformat(obj)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L183-L187
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 88.837209 | 5 | 1 | 100 | 1 |
def pformat(obj: t.Any) -> str:
from pprint import pformat # type: ignore
return pformat(obj)
| 27,682 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
urlize
|
(
text: str,
trim_url_limit: t.Optional[int] = None,
rel: t.Optional[str] = None,
target: t.Optional[str] = None,
extra_schemes: t.Optional[t.Iterable[str]] = None,
)
|
return "".join(words)
|
Convert URLs in text into clickable links.
This may not recognize links in some situations. Usually, a more
comprehensive formatter, such as a Markdown library, is a better
choice.
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
addresses. Links with trailing punctuation (periods, commas, closing
parentheses) and leading punctuation (opening parentheses) are
recognized excluding the punctuation. Email addresses that include
header fields are not recognized (for example,
``mailto:address@example.com?cc=copy@example.com``).
:param text: Original text containing URLs to link.
:param trim_url_limit: Shorten displayed URL values to this length.
:param target: Add the ``target`` attribute to links.
:param rel: Add the ``rel`` attribute to links.
:param extra_schemes: Recognize URLs that start with these schemes
in addition to the default behavior.
.. versionchanged:: 3.0
The ``extra_schemes`` parameter was added.
.. versionchanged:: 3.0
Generate ``https://`` links for URLs without a scheme.
.. versionchanged:: 3.0
The parsing rules were updated. Recognize email addresses with
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
parentheses and brackets in more cases.
|
Convert URLs in text into clickable links.
| 221 | 339 |
def urlize(
text: str,
trim_url_limit: t.Optional[int] = None,
rel: t.Optional[str] = None,
target: t.Optional[str] = None,
extra_schemes: t.Optional[t.Iterable[str]] = None,
) -> str:
"""Convert URLs in text into clickable links.
This may not recognize links in some situations. Usually, a more
comprehensive formatter, such as a Markdown library, is a better
choice.
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
addresses. Links with trailing punctuation (periods, commas, closing
parentheses) and leading punctuation (opening parentheses) are
recognized excluding the punctuation. Email addresses that include
header fields are not recognized (for example,
``mailto:address@example.com?cc=copy@example.com``).
:param text: Original text containing URLs to link.
:param trim_url_limit: Shorten displayed URL values to this length.
:param target: Add the ``target`` attribute to links.
:param rel: Add the ``rel`` attribute to links.
:param extra_schemes: Recognize URLs that start with these schemes
in addition to the default behavior.
.. versionchanged:: 3.0
The ``extra_schemes`` parameter was added.
.. versionchanged:: 3.0
Generate ``https://`` links for URLs without a scheme.
.. versionchanged:: 3.0
The parsing rules were updated. Recognize email addresses with
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
parentheses and brackets in more cases.
"""
if trim_url_limit is not None:
def trim_url(x: str) -> str:
if len(x) > trim_url_limit: # type: ignore
return f"{x[:trim_url_limit]}..."
return x
else:
def trim_url(x: str) -> str:
return x
words = re.split(r"(\s+)", str(markupsafe.escape(text)))
rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
target_attr = f' target="{markupsafe.escape(target)}"' if target else ""
for i, word in enumerate(words):
head, middle, tail = "", word, ""
match = re.match(r"^([(<]|<)+", middle)
if match:
head = match.group()
middle = middle[match.end() :]
# Unlike lead, which is anchored to the start of the string,
# need to check that the string ends with any of the characters
# before trying to match all of them, to avoid backtracking.
if middle.endswith((")", ">", ".", ",", "\n", ">")):
match = re.search(r"([)>.,\n]|>)+$", middle)
if match:
tail = match.group()
middle = middle[: match.start()]
# Prefer balancing parentheses in URLs instead of ignoring a
# trailing character.
for start_char, end_char in ("(", ")"), ("<", ">"), ("<", ">"):
start_count = middle.count(start_char)
if start_count <= middle.count(end_char):
# Balanced, or lighter on the left
continue
# Move as many as possible from the tail to balance
for _ in range(min(start_count, tail.count(end_char))):
end_index = tail.index(end_char) + len(end_char)
# Move anything in the tail before the end char too
middle += tail[:end_index]
tail = tail[end_index:]
if _http_re.match(middle):
if middle.startswith("https://") or middle.startswith("http://"):
middle = (
f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'
)
else:
middle = (
f'<a href="https://{middle}"{rel_attr}{target_attr}>'
f"{trim_url(middle)}</a>"
)
elif middle.startswith("mailto:") and _email_re.match(middle[7:]):
middle = f'<a href="{middle}">{middle[7:]}</a>'
elif (
"@" in middle
and not middle.startswith("www.")
and ":" not in middle
and _email_re.match(middle)
):
middle = f'<a href="mailto:{middle}">{middle}</a>'
elif extra_schemes is not None:
for scheme in extra_schemes:
if middle != scheme and middle.startswith(scheme):
middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'
words[i] = f"{head}{middle}{tail}"
return "".join(words)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L221-L339
| 42 |
[
0,
37,
38,
39,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100,
101,
102,
103,
104,
105,
106,
107,
108,
109,
110,
111,
112,
113,
114,
115,
116,
117,
118
] | 63.865546 |
[
40,
41,
42,
44
] | 3.361345 | false | 88.837209 | 119 | 25 | 96.638655 | 30 |
def urlize(
text: str,
trim_url_limit: t.Optional[int] = None,
rel: t.Optional[str] = None,
target: t.Optional[str] = None,
extra_schemes: t.Optional[t.Iterable[str]] = None,
) -> str:
if trim_url_limit is not None:
def trim_url(x: str) -> str:
if len(x) > trim_url_limit: # type: ignore
return f"{x[:trim_url_limit]}..."
return x
else:
def trim_url(x: str) -> str:
return x
words = re.split(r"(\s+)", str(markupsafe.escape(text)))
rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
target_attr = f' target="{markupsafe.escape(target)}"' if target else ""
for i, word in enumerate(words):
head, middle, tail = "", word, ""
match = re.match(r"^([(<]|<)+", middle)
if match:
head = match.group()
middle = middle[match.end() :]
# Unlike lead, which is anchored to the start of the string,
# need to check that the string ends with any of the characters
# before trying to match all of them, to avoid backtracking.
if middle.endswith((")", ">", ".", ",", "\n", ">")):
match = re.search(r"([)>.,\n]|>)+$", middle)
if match:
tail = match.group()
middle = middle[: match.start()]
# Prefer balancing parentheses in URLs instead of ignoring a
# trailing character.
for start_char, end_char in ("(", ")"), ("<", ">"), ("<", ">"):
start_count = middle.count(start_char)
if start_count <= middle.count(end_char):
# Balanced, or lighter on the left
continue
# Move as many as possible from the tail to balance
for _ in range(min(start_count, tail.count(end_char))):
end_index = tail.index(end_char) + len(end_char)
# Move anything in the tail before the end char too
middle += tail[:end_index]
tail = tail[end_index:]
if _http_re.match(middle):
if middle.startswith("https://") or middle.startswith("http://"):
middle = (
f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'
)
else:
middle = (
f'<a href="https://{middle}"{rel_attr}{target_attr}>'
f"{trim_url(middle)}</a>"
)
elif middle.startswith("mailto:") and _email_re.match(middle[7:]):
middle = f'<a href="{middle}">{middle[7:]}</a>'
elif (
"@" in middle
and not middle.startswith("www.")
and ":" not in middle
and _email_re.match(middle)
):
middle = f'<a href="mailto:{middle}">{middle}</a>'
elif extra_schemes is not None:
for scheme in extra_schemes:
if middle != scheme and middle.startswith(scheme):
middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'
words[i] = f"{head}{middle}{tail}"
return "".join(words)
| 27,683 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
generate_lorem_ipsum
|
(
n: int = 5, html: bool = True, min: int = 20, max: int = 100
)
|
return markupsafe.Markup(
"\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
)
|
Generate some lorem ipsum for the template.
|
Generate some lorem ipsum for the template.
| 342 | 394 |
def generate_lorem_ipsum(
n: int = 5, html: bool = True, min: int = 20, max: int = 100
) -> str:
"""Generate some lorem ipsum for the template."""
from .constants import LOREM_IPSUM_WORDS
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in range(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(range(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ","
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += "."
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p_str = " ".join(p)
if p_str.endswith(","):
p_str = p_str[:-1] + "."
elif not p_str.endswith("."):
p_str += "."
result.append(p_str)
if not html:
return "\n\n".join(result)
return markupsafe.Markup(
"\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L342-L394
| 42 |
[
0,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52
] | 96.226415 |
[] | 0 | false | 88.837209 | 53 | 11 | 100 | 1 |
def generate_lorem_ipsum(
n: int = 5, html: bool = True, min: int = 20, max: int = 100
) -> str:
from .constants import LOREM_IPSUM_WORDS
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in range(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(range(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ","
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += "."
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p_str = " ".join(p)
if p_str.endswith(","):
p_str = p_str[:-1] + "."
elif not p_str.endswith("."):
p_str += "."
result.append(p_str)
if not html:
return "\n\n".join(result)
return markupsafe.Markup(
"\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
)
| 27,684 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
url_quote
|
(obj: t.Any, charset: str = "utf-8", for_qs: bool = False)
|
return rv
|
Quote a string for use in a URL using the given charset.
:param obj: String or bytes to quote. Other types are converted to
string then encoded to bytes using the given charset.
:param charset: Encode text to bytes using this charset.
:param for_qs: Quote "/" and use "+" for spaces.
|
Quote a string for use in a URL using the given charset.
| 397 | 417 |
def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
"""Quote a string for use in a URL using the given charset.
:param obj: String or bytes to quote. Other types are converted to
string then encoded to bytes using the given charset.
:param charset: Encode text to bytes using this charset.
:param for_qs: Quote "/" and use "+" for spaces.
"""
if not isinstance(obj, bytes):
if not isinstance(obj, str):
obj = str(obj)
obj = obj.encode(charset)
safe = b"" if for_qs else b"/"
rv = quote_from_bytes(obj, safe)
if for_qs:
rv = rv.replace("%20", "+")
return rv
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L397-L417
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 100 |
[] | 0 | true | 88.837209 | 21 | 4 | 100 | 6 |
def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
if not isinstance(obj, bytes):
if not isinstance(obj, str):
obj = str(obj)
obj = obj.encode(charset)
safe = b"" if for_qs else b"/"
rv = quote_from_bytes(obj, safe)
if for_qs:
rv = rv.replace("%20", "+")
return rv
| 27,685 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
select_autoescape
|
(
enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
disabled_extensions: t.Collection[str] = (),
default_for_string: bool = True,
default: bool = False,
)
|
return autoescape
|
Intelligently sets the initial value of autoescaping based on the
filename of the template. This is the recommended way to configure
autoescaping if you do not want to write a custom function yourself.
If you want to enable it for all templates created from strings or
for all templates with `.html` and `.xml` extensions::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
enabled_extensions=('html', 'xml'),
default_for_string=True,
))
Example configuration to turn it on at all times except if the template
ends with `.txt`::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
disabled_extensions=('txt',),
default_for_string=True,
default=True,
))
The `enabled_extensions` is an iterable of all the extensions that
autoescaping should be enabled for. Likewise `disabled_extensions` is
a list of all templates it should be disabled for. If a template is
loaded from a string then the default from `default_for_string` is used.
If nothing matches then the initial value of autoescaping is set to the
value of `default`.
For security reasons this function operates case insensitive.
.. versionadded:: 2.9
|
Intelligently sets the initial value of autoescaping based on the
filename of the template. This is the recommended way to configure
autoescaping if you do not want to write a custom function yourself.
| 570 | 623 |
def select_autoescape(
enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
disabled_extensions: t.Collection[str] = (),
default_for_string: bool = True,
default: bool = False,
) -> t.Callable[[t.Optional[str]], bool]:
"""Intelligently sets the initial value of autoescaping based on the
filename of the template. This is the recommended way to configure
autoescaping if you do not want to write a custom function yourself.
If you want to enable it for all templates created from strings or
for all templates with `.html` and `.xml` extensions::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
enabled_extensions=('html', 'xml'),
default_for_string=True,
))
Example configuration to turn it on at all times except if the template
ends with `.txt`::
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape(
disabled_extensions=('txt',),
default_for_string=True,
default=True,
))
The `enabled_extensions` is an iterable of all the extensions that
autoescaping should be enabled for. Likewise `disabled_extensions` is
a list of all templates it should be disabled for. If a template is
loaded from a string then the default from `default_for_string` is used.
If nothing matches then the initial value of autoescaping is set to the
value of `default`.
For security reasons this function operates case insensitive.
.. versionadded:: 2.9
"""
enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)
def autoescape(template_name: t.Optional[str]) -> bool:
if template_name is None:
return default_for_string
template_name = template_name.lower()
if template_name.endswith(enabled_patterns):
return True
if template_name.endswith(disabled_patterns):
return False
return default
return autoescape
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L570-L623
| 42 |
[
0,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53
] | 29.62963 |
[] | 0 | false | 88.837209 | 54 | 5 | 100 | 33 |
def select_autoescape(
enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
disabled_extensions: t.Collection[str] = (),
default_for_string: bool = True,
default: bool = False,
) -> t.Callable[[t.Optional[str]], bool]:
enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)
def autoescape(template_name: t.Optional[str]) -> bool:
if template_name is None:
return default_for_string
template_name = template_name.lower()
if template_name.endswith(enabled_patterns):
return True
if template_name.endswith(disabled_patterns):
return False
return default
return autoescape
| 27,686 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
htmlsafe_json_dumps
|
(
obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
)
|
return markupsafe.Markup(
dumps(obj, **kwargs)
.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("&", "\\u0026")
.replace("'", "\\u0027")
)
|
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
|
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`.
| 626 | 663 |
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")
)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L626-L663
| 42 |
[
0,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37
] | 31.578947 |
[] | 0 | false | 88.837209 | 38 | 2 | 100 | 24 |
def htmlsafe_json_dumps(
obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
) -> markupsafe.Markup:
if dumps is None:
dumps = json.dumps
return markupsafe.Markup(
dumps(obj, **kwargs)
.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("&", "\\u0026")
.replace("'", "\\u0027")
)
| 27,687 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
_PassArg.from_obj
|
(cls, obj: F)
|
return None
| 82 | 86 |
def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
if hasattr(obj, "jinja_pass_arg"):
return obj.jinja_pass_arg # type: ignore
return None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L82-L86
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 88.837209 | 5 | 2 | 100 | 0 |
def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
if hasattr(obj, "jinja_pass_arg"):
return obj.jinja_pass_arg # type: ignore
return None
| 27,688 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Cycler.__init__
|
(self, *items: t.Any)
| 692 | 696 |
def __init__(self, *items: t.Any) -> None:
if not items:
raise RuntimeError("at least one item has to be provided")
self.items = items
self.pos = 0
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L692-L696
| 42 |
[
0,
1,
3,
4
] | 80 |
[
2
] | 20 | false | 88.837209 | 5 | 2 | 80 | 0 |
def __init__(self, *items: t.Any) -> None:
if not items:
raise RuntimeError("at least one item has to be provided")
self.items = items
self.pos = 0
| 27,689 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Cycler.reset
|
(self)
|
Resets the current item to the first item.
|
Resets the current item to the first item.
| 698 | 700 |
def reset(self) -> None:
"""Resets the current item to the first item."""
self.pos = 0
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L698-L700
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 88.837209 | 3 | 1 | 100 | 1 |
def reset(self) -> None:
self.pos = 0
| 27,690 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Cycler.current
|
(self)
|
return self.items[self.pos]
|
Return the current item. Equivalent to the item that will be
returned next time :meth:`next` is called.
|
Return the current item. Equivalent to the item that will be
returned next time :meth:`next` is called.
| 703 | 707 |
def current(self) -> t.Any:
"""Return the current item. Equivalent to the item that will be
returned next time :meth:`next` is called.
"""
return self.items[self.pos]
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L703-L707
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 88.837209 | 5 | 1 | 100 | 2 |
def current(self) -> t.Any:
return self.items[self.pos]
| 27,691 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Cycler.next
|
(self)
|
return rv
|
Return the current item, then advance :attr:`current` to the
next item.
|
Return the current item, then advance :attr:`current` to the
next item.
| 709 | 715 |
def next(self) -> t.Any:
"""Return the current item, then advance :attr:`current` to the
next item.
"""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L709-L715
| 42 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 88.837209 | 7 | 1 | 100 | 2 |
def next(self) -> t.Any:
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv
| 27,692 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Joiner.__init__
|
(self, sep: str = ", ")
| 723 | 725 |
def __init__(self, sep: str = ", ") -> None:
self.sep = sep
self.used = False
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L723-L725
| 42 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 88.837209 | 3 | 1 | 33.333333 | 0 |
def __init__(self, sep: str = ", ") -> None:
self.sep = sep
self.used = False
| 27,693 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Joiner.__call__
|
(self)
|
return self.sep
| 727 | 731 |
def __call__(self) -> str:
if not self.used:
self.used = True
return ""
return self.sep
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L727-L731
| 42 |
[
0
] | 20 |
[
1,
2,
3,
4
] | 80 | false | 88.837209 | 5 | 2 | 20 | 0 |
def __call__(self) -> str:
if not self.used:
self.used = True
return ""
return self.sep
| 27,694 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Namespace.__init__
|
(*args: t.Any, **kwargs: t.Any)
| 738 | 740 |
def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902
self, args = args[0], args[1:]
self.__attrs = dict(*args, **kwargs)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L738-L740
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 88.837209 | 3 | 1 | 100 | 0 |
def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902
self, args = args[0], args[1:]
self.__attrs = dict(*args, **kwargs)
| 27,695 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Namespace.__getattribute__
|
(self, name: str)
| 742 | 749 |
def __getattribute__(self, name: str) -> t.Any:
# __class__ is needed for the awaitable check in async mode
if name in {"_Namespace__attrs", "__class__"}:
return object.__getattribute__(self, name)
try:
return self.__attrs[name]
except KeyError:
raise AttributeError(name) from None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L742-L749
| 42 |
[
0,
1,
2,
3,
4,
5
] | 75 |
[
6,
7
] | 25 | false | 88.837209 | 8 | 3 | 75 | 0 |
def __getattribute__(self, name: str) -> t.Any:
# __class__ is needed for the awaitable check in async mode
if name in {"_Namespace__attrs", "__class__"}:
return object.__getattribute__(self, name)
try:
return self.__attrs[name]
except KeyError:
raise AttributeError(name) from None
| 27,696 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Namespace.__setitem__
|
(self, name: str, value: t.Any)
| 751 | 752 |
def __setitem__(self, name: str, value: t.Any) -> None:
self.__attrs[name] = value
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L751-L752
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 88.837209 | 2 | 1 | 100 | 0 |
def __setitem__(self, name: str, value: t.Any) -> None:
self.__attrs[name] = value
| 27,697 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/utils.py
|
Namespace.__repr__
|
(self)
|
return f"<Namespace {self.__attrs!r}>"
| 754 | 755 |
def __repr__(self) -> str:
return f"<Namespace {self.__attrs!r}>"
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/utils.py#L754-L755
| 42 |
[
0
] | 50 |
[
1
] | 50 | false | 88.837209 | 2 | 1 | 50 | 0 |
def __repr__(self) -> str:
return f"<Namespace {self.__attrs!r}>"
| 27,698 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
get_eval_context
|
(node: "Node", ctx: t.Optional[EvalContext])
|
return ctx
| 92 | 100 |
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
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L92-L100
| 42 |
[
0,
1,
8
] | 33.333333 |
[
2,
3,
7
] | 33.333333 | false | 86.435786 | 9 | 3 | 66.666667 | 0 |
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
| 27,699 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
args_as_const
|
(
node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
)
|
return args, kwargs
| 716 | 734 |
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
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L716-L734
| 42 |
[
0,
3,
4,
5,
6,
11,
12,
17,
18
] | 47.368421 |
[
7,
8,
9,
10,
13,
14,
15,
16
] | 42.105263 | false | 86.435786 | 19 | 6 | 57.894737 | 0 |
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
| 27,700 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
NodeType.__new__
|
(mcs, name, bases, d)
|
return type.__new__(mcs, name, bases, d)
| 57 | 66 |
def __new__(mcs, name, bases, d): # type: ignore
for attr in "fields", "attributes":
storage = []
storage.extend(getattr(bases[0] if bases else object, attr, ()))
storage.extend(d.get(attr, ()))
assert len(bases) <= 1, "multiple inheritance not allowed"
assert len(storage) == len(set(storage)), "layout conflict"
d[attr] = tuple(storage)
d.setdefault("abstract", False)
return type.__new__(mcs, name, bases, d)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L57-L66
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 86.435786 | 10 | 4 | 100 | 0 |
def __new__(mcs, name, bases, d): # type: ignore
for attr in "fields", "attributes":
storage = []
storage.extend(getattr(bases[0] if bases else object, attr, ()))
storage.extend(d.get(attr, ()))
assert len(bases) <= 1, "multiple inheritance not allowed"
assert len(storage) == len(set(storage)), "layout conflict"
d[attr] = tuple(storage)
d.setdefault("abstract", False)
return type.__new__(mcs, name, bases, d)
| 27,701 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
EvalContext.__init__
|
(
self, environment: "Environment", template_name: t.Optional[str] = None
)
| 74 | 82 |
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
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L74-L82
| 42 |
[
0,
3,
4,
5,
7,
8
] | 66.666667 |
[] | 0 | false | 86.435786 | 9 | 2 | 100 | 0 |
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
| 27,702 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
EvalContext.save
|
(self)
|
return self.__dict__.copy()
| 84 | 85 |
def save(self) -> t.Mapping[str, t.Any]:
return self.__dict__.copy()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L84-L85
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 86.435786 | 2 | 1 | 100 | 0 |
def save(self) -> t.Mapping[str, t.Any]:
return self.__dict__.copy()
| 27,703 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
EvalContext.revert
|
(self, old: t.Mapping[str, t.Any])
| 87 | 89 |
def revert(self, old: t.Mapping[str, t.Any]) -> None:
self.__dict__.clear()
self.__dict__.update(old)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L87-L89
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 1 | 100 | 0 |
def revert(self, old: t.Mapping[str, t.Any]) -> None:
self.__dict__.clear()
self.__dict__.update(old)
| 27,704 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.__init__
|
(self, *fields: t.Any, **attributes: t.Any)
| 127 | 143 |
def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
if self.abstract:
raise TypeError("abstract nodes are not instantiable")
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
raise TypeError(
f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
f" argument{'s' if len(self.fields) != 1 else ''}"
)
for name, arg in zip(self.fields, fields):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L127-L143
| 42 |
[
0,
1,
3,
4,
11,
12,
13,
14,
15
] | 52.941176 |
[
2,
5,
6,
7,
16
] | 29.411765 | false | 86.435786 | 17 | 8 | 70.588235 | 0 |
def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
if self.abstract:
raise TypeError("abstract nodes are not instantiable")
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
raise TypeError(
f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
f" argument{'s' if len(self.fields) != 1 else ''}"
)
for name, arg in zip(self.fields, fields):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
| 27,705 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.iter_fields
|
(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
)
|
This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
|
This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
| 145 | 165 |
def iter_fields(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator[t.Tuple[str, t.Any]]:
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (
(exclude is None and only is None)
or (exclude is not None and name not in exclude)
or (only is not None and name in only)
):
try:
yield name, getattr(self, name)
except AttributeError:
pass
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L145-L165
| 42 |
[
0,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19
] | 52.380952 |
[
20
] | 4.761905 | false | 86.435786 | 21 | 9 | 95.238095 | 5 |
def iter_fields(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator[t.Tuple[str, t.Any]]:
for name in self.fields:
if (
(exclude is None and only is None)
or (exclude is not None and name not in exclude)
or (only is not None and name in only)
):
try:
yield name, getattr(self, name)
except AttributeError:
pass
| 27,706 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.iter_child_nodes
|
(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
)
|
Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
|
Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
| 167 | 182 |
def iter_child_nodes(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator["Node"]:
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for _, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L167-L182
| 42 |
[
0,
8,
9,
10,
11,
12,
13,
14,
15
] | 56.25 |
[] | 0 | false | 86.435786 | 16 | 6 | 100 | 3 |
def iter_child_nodes(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator["Node"]:
for _, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
| 27,707 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.find
|
(self, node_type: t.Type[_NodeBound])
|
return None
|
Find the first node of a given type. If no such node exists the
return value is `None`.
|
Find the first node of a given type. If no such node exists the
return value is `None`.
| 184 | 191 |
def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result
return None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L184-L191
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 86.435786 | 8 | 2 | 100 | 2 |
def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
for result in self.find_all(node_type):
return result
return None
| 27,708 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.find_all
|
(
self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
)
|
Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
|
Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
| 193 | 202 |
def find_all(
self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
) -> t.Iterator[_NodeBound]:
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child # type: ignore
yield from child.find_all(node_type)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L193-L202
| 42 |
[
0,
5,
6,
7,
8,
9
] | 60 |
[] | 0 | false | 86.435786 | 10 | 3 | 100 | 2 |
def find_all(
self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
) -> t.Iterator[_NodeBound]:
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child # type: ignore
yield from child.find_all(node_type)
| 27,709 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.set_ctx
|
(self, ctx: str)
|
return self
|
Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
|
Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
| 204 | 216 |
def set_ctx(self, ctx: str) -> "Node":
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if "ctx" in node.fields:
node.ctx = ctx # type: ignore
todo.extend(node.iter_child_nodes())
return self
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L204-L216
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
] | 100 |
[] | 0 | true | 86.435786 | 13 | 3 | 100 | 4 |
def set_ctx(self, ctx: str) -> "Node":
todo = deque([self])
while todo:
node = todo.popleft()
if "ctx" in node.fields:
node.ctx = ctx # type: ignore
todo.extend(node.iter_child_nodes())
return self
| 27,710 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.set_lineno
|
(self, lineno: int, override: bool = False)
|
return self
|
Set the line numbers of the node and children.
|
Set the line numbers of the node and children.
| 218 | 227 |
def set_lineno(self, lineno: int, override: bool = False) -> "Node":
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if "lineno" in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L218-L227
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 86.435786 | 10 | 5 | 100 | 1 |
def set_lineno(self, lineno: int, override: bool = False) -> "Node":
todo = deque([self])
while todo:
node = todo.popleft()
if "lineno" in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
| 27,711 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.set_environment
|
(self, environment: "Environment")
|
return self
|
Set the environment for all nodes.
|
Set the environment for all nodes.
| 229 | 236 |
def set_environment(self, environment: "Environment") -> "Node":
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L229-L236
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 86.435786 | 8 | 2 | 100 | 1 |
def set_environment(self, environment: "Environment") -> "Node":
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
| 27,712 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.__eq__
|
(self, other: t.Any)
|
return tuple(self.iter_fields()) == tuple(other.iter_fields())
| 238 | 242 |
def __eq__(self, other: t.Any) -> bool:
if type(self) is not type(other):
return NotImplemented
return tuple(self.iter_fields()) == tuple(other.iter_fields())
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L238-L242
| 42 |
[
0,
1,
3,
4
] | 80 |
[
2
] | 20 | false | 86.435786 | 5 | 2 | 80 | 0 |
def __eq__(self, other: t.Any) -> bool:
if type(self) is not type(other):
return NotImplemented
return tuple(self.iter_fields()) == tuple(other.iter_fields())
| 27,713 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.__repr__
|
(self)
|
return f"{type(self).__name__}({args_str})"
| 246 | 248 |
def __repr__(self) -> str:
args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
return f"{type(self).__name__}({args_str})"
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L246-L248
| 42 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 86.435786 | 3 | 1 | 33.333333 | 0 |
def __repr__(self) -> str:
args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
return f"{type(self).__name__}({args_str})"
| 27,714 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Node.dump
|
(self)
|
return "".join(buf)
| 250 | 277 |
def dump(self) -> str:
def _dump(node: t.Union[Node, t.Any]) -> None:
if not isinstance(node, Node):
buf.append(repr(node))
return
buf.append(f"nodes.{type(node).__name__}(")
if not node.fields:
buf.append(")")
return
for idx, field in enumerate(node.fields):
if idx:
buf.append(", ")
value = getattr(node, field)
if isinstance(value, list):
buf.append("[")
for idx, item in enumerate(value):
if idx:
buf.append(", ")
_dump(item)
buf.append("]")
else:
_dump(value)
buf.append(")")
buf: t.List[str] = []
_dump(self)
return "".join(buf)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L250-L277
| 42 |
[
0
] | 3.571429 |
[
1,
2,
3,
4,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
22,
23,
25,
26,
27
] | 85.714286 | false | 86.435786 | 28 | 9 | 14.285714 | 0 |
def dump(self) -> str:
def _dump(node: t.Union[Node, t.Any]) -> None:
if not isinstance(node, Node):
buf.append(repr(node))
return
buf.append(f"nodes.{type(node).__name__}(")
if not node.fields:
buf.append(")")
return
for idx, field in enumerate(node.fields):
if idx:
buf.append(", ")
value = getattr(node, field)
if isinstance(value, list):
buf.append("[")
for idx, item in enumerate(value):
if idx:
buf.append(", ")
_dump(item)
buf.append("]")
else:
_dump(value)
buf.append(")")
buf: t.List[str] = []
_dump(self)
return "".join(buf)
| 27,715 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Expr.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
|
Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
| 470 | 481 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
"""
raise Impossible()
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L470-L481
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 86.435786 | 12 | 1 | 100 | 9 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
raise Impossible()
| 27,716 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Expr.can_assign
|
(self)
|
return False
|
Check if it's possible to assign something to this node.
|
Check if it's possible to assign something to this node.
| 483 | 485 |
def can_assign(self) -> bool:
"""Check if it's possible to assign something to this node."""
return False
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L483-L485
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 1 | 100 | 1 |
def can_assign(self) -> bool:
return False
| 27,717 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
BinExpr.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
| 497 | 510 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if (
eval_ctx.environment.sandboxed
and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
):
raise Impossible()
f = _binop_to_func[self.operator]
try:
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
except Exception as e:
raise Impossible() from e
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L497-L510
| 42 |
[
0,
1,
2,
3,
4,
8,
9,
10,
11,
12,
13
] | 78.571429 |
[] | 0 | false | 86.435786 | 14 | 4 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if (
eval_ctx.environment.sandboxed
and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
):
raise Impossible()
f = _binop_to_func[self.operator]
try:
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
except Exception as e:
raise Impossible() from e
| 27,718 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
UnaryExpr.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
| 521 | 534 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if (
eval_ctx.environment.sandboxed
and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
):
raise Impossible()
f = _uaop_to_func[self.operator]
try:
return f(self.node.as_const(eval_ctx))
except Exception as e:
raise Impossible() from e
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L521-L534
| 42 |
[
0,
1,
2,
3,
4,
8,
9,
10,
11,
12,
13
] | 78.571429 |
[] | 0 | false | 86.435786 | 14 | 4 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time
if (
eval_ctx.environment.sandboxed
and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
):
raise Impossible()
f = _uaop_to_func[self.operator]
try:
return f(self.node.as_const(eval_ctx))
except Exception as e:
raise Impossible() from e
| 27,719 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Name.can_assign
|
(self)
|
return self.name not in {"true", "false", "none", "True", "False", "None"}
| 550 | 551 |
def can_assign(self) -> bool:
return self.name not in {"true", "false", "none", "True", "False", "None"}
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L550-L551
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 86.435786 | 2 | 1 | 100 | 0 |
def can_assign(self) -> bool:
return self.name not in {"true", "false", "none", "True", "False", "None"}
| 27,720 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
NSRef.can_assign
|
(self)
|
return True
| 561 | 566 |
def can_assign(self) -> bool:
# We don't need any special checks here; NSRef assignments have a
# runtime check to ensure the target is a namespace object which will
# have been checked already as it is created using a normal assignment
# which goes through a `Name` node.
return True
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L561-L566
| 42 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 86.435786 | 6 | 1 | 100 | 0 |
def can_assign(self) -> bool:
# We don't need any special checks here; NSRef assignments have a
# runtime check to ensure the target is a namespace object which will
# have been checked already as it is created using a normal assignment
# which goes through a `Name` node.
return True
| 27,721 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Const.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return self.value
| 585 | 586 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
return self.value
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L585-L586
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 86.435786 | 2 | 1 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
return self.value
| 27,722 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Const.from_untrusted
|
(
cls,
value: t.Any,
lineno: t.Optional[int] = None,
environment: "t.Optional[Environment]" = None,
)
|
return cls(value, lineno=lineno, environment=environment)
|
Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
|
Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
| 589 | 603 |
def from_untrusted(
cls,
value: t.Any,
lineno: t.Optional[int] = None,
environment: "t.Optional[Environment]" = None,
) -> "Const":
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L589-L603
| 42 |
[
0,
9,
10,
11,
12,
13,
14
] | 46.666667 |
[] | 0 | false | 86.435786 | 15 | 2 | 100 | 3 |
def from_untrusted(
cls,
value: t.Any,
lineno: t.Optional[int] = None,
environment: "t.Optional[Environment]" = None,
) -> "Const":
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
| 27,723 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
TemplateData.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return self.data
| 612 | 618 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L612-L618
| 42 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 86.435786 | 7 | 3 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
| 27,724 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Tuple.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return tuple(x.as_const(eval_ctx) for x in self.items)
| 631 | 633 |
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)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L631-L633
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 1 | 100 | 0 |
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)
| 27,725 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Tuple.can_assign
|
(self)
|
return True
| 635 | 639 |
def can_assign(self) -> bool:
for item in self.items:
if not item.can_assign():
return False
return True
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L635-L639
| 42 |
[
0,
1,
2,
4
] | 80 |
[
3
] | 20 | false | 86.435786 | 5 | 3 | 80 | 0 |
def can_assign(self) -> bool:
for item in self.items:
if not item.can_assign():
return False
return True
| 27,726 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
List.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return [x.as_const(eval_ctx) for x in self.items]
| 648 | 650 |
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]
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L648-L650
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 2 | 100 | 0 |
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]
| 27,727 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Dict.as_const
|
(
self, eval_ctx: t.Optional[EvalContext] = None
)
|
return dict(x.as_const(eval_ctx) for x in self.items)
| 661 | 665 |
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)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L661-L665
| 42 |
[
0,
3,
4
] | 60 |
[] | 0 | false | 86.435786 | 5 | 1 | 100 | 0 |
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)
| 27,728 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Pair.as_const
|
(
self, eval_ctx: t.Optional[EvalContext] = None
)
|
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
| 675 | 679 |
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Tuple[t.Any, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L675-L679
| 42 |
[
0,
3,
4
] | 60 |
[] | 0 | false | 86.435786 | 5 | 1 | 100 | 0 |
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Tuple[t.Any, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
| 27,729 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Keyword.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return self.key, self.value.as_const(eval_ctx)
| 689 | 691 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return self.key, self.value.as_const(eval_ctx)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L689-L691
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 1 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return self.key, self.value.as_const(eval_ctx)
| 27,730 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
CondExpr.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return self.expr2.as_const(eval_ctx)
| 704 | 713 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
if self.test.as_const(eval_ctx):
return self.expr1.as_const(eval_ctx)
# if we evaluate to an undefined object, we better do that at runtime
if self.expr2 is None:
raise Impossible()
return self.expr2.as_const(eval_ctx)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L704-L713
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 90 |
[
9
] | 10 | false | 86.435786 | 10 | 3 | 90 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
if self.test.as_const(eval_ctx):
return self.expr1.as_const(eval_ctx)
# if we evaluate to an undefined object, we better do that at runtime
if self.expr2 is None:
raise Impossible()
return self.expr2.as_const(eval_ctx)
| 27,731 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Filter.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return super().as_const(eval_ctx=eval_ctx)
| 795 | 799 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.node is None:
raise Impossible()
return super().as_const(eval_ctx=eval_ctx)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L795-L799
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 86.435786 | 5 | 2 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.node is None:
raise Impossible()
return super().as_const(eval_ctx=eval_ctx)
| 27,732 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Getitem.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
| 839 | 850 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.ctx != "load":
raise Impossible()
eval_ctx = get_eval_context(self, eval_ctx)
try:
return eval_ctx.environment.getitem(
self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
)
except Exception as e:
raise Impossible() from e
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L839-L850
| 42 |
[
0,
1,
3,
4,
5,
6,
7,
10,
11
] | 75 |
[
2
] | 8.333333 | false | 86.435786 | 12 | 3 | 91.666667 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.ctx != "load":
raise Impossible()
eval_ctx = get_eval_context(self, eval_ctx)
try:
return eval_ctx.environment.getitem(
self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
)
except Exception as e:
raise Impossible() from e
| 27,733 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Getattr.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
| 863 | 872 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.ctx != "load":
raise Impossible()
eval_ctx = get_eval_context(self, eval_ctx)
try:
return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
except Exception as e:
raise Impossible() from e
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L863-L872
| 42 |
[
0,
1,
3,
4,
5,
6,
7,
8,
9
] | 90 |
[
2
] | 10 | false | 86.435786 | 10 | 3 | 90 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.ctx != "load":
raise Impossible()
eval_ctx = get_eval_context(self, eval_ctx)
try:
return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
except Exception as e:
raise Impossible() from e
| 27,734 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Slice.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return slice(const(self.start), const(self.stop), const(self.step))
| 885 | 893 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
eval_ctx = get_eval_context(self, eval_ctx)
def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
if obj is None:
return None
return obj.as_const(eval_ctx)
return slice(const(self.start), const(self.stop), const(self.step))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L885-L893
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 |
[] | 0 | true | 86.435786 | 9 | 3 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
eval_ctx = get_eval_context(self, eval_ctx)
def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
if obj is None:
return None
return obj.as_const(eval_ctx)
return slice(const(self.start), const(self.stop), const(self.step))
| 27,735 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Concat.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
| 904 | 906 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
eval_ctx = get_eval_context(self, eval_ctx)
return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L904-L906
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 1 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
eval_ctx = get_eval_context(self, eval_ctx)
return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
| 27,736 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Compare.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return result
| 918 | 934 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
result = value = self.expr.as_const(eval_ctx)
try:
for op in self.ops:
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
if not result:
return False
value = new_value
except Exception as e:
raise Impossible() from e
return result
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L918-L934
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16
] | 100 |
[] | 0 | true | 86.435786 | 17 | 4 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
result = value = self.expr.as_const(eval_ctx)
try:
for op in self.ops:
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
if not result:
return False
value = new_value
except Exception as e:
raise Impossible() from e
return result
| 27,737 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
And.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
| 994 | 996 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L994-L996
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 2 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
| 27,738 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
Or.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
| 1,004 | 1,006 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L1004-L1006
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 86.435786 | 3 | 2 | 100 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
| 27,739 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
MarkSafe.as_const
|
(self, eval_ctx: t.Optional[EvalContext] = None)
|
return Markup(self.expr.as_const(eval_ctx))
| 1,087 | 1,089 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L1087-L1089
| 42 |
[
0
] | 33.333333 |
[
1,
2
] | 66.666667 | false | 86.435786 | 3 | 1 | 33.333333 | 0 |
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
| 27,740 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/nodes.py
|
MarkSafeIfAutoescape.as_const
|
(
self, eval_ctx: t.Optional[EvalContext] = None
)
|
return expr
| 1,102 | 1,111 |
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Union[Markup, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
expr = self.expr.as_const(eval_ctx)
if eval_ctx.autoescape:
return Markup(expr)
return expr
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/nodes.py#L1102-L1111
| 42 |
[
0,
3,
4,
6
] | 40 |
[
5,
7,
8,
9
] | 40 | false | 86.435786 | 10 | 3 | 60 | 0 |
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Union[Markup, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
expr = self.expr.as_const(eval_ctx)
if eval_ctx.autoescape:
return Markup(expr)
return expr
| 27,741 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
_describe_token_type
|
(token_type: str)
|
return {
TOKEN_COMMENT_BEGIN: "begin of comment",
TOKEN_COMMENT_END: "end of comment",
TOKEN_COMMENT: "comment",
TOKEN_LINECOMMENT: "comment",
TOKEN_BLOCK_BEGIN: "begin of statement block",
TOKEN_BLOCK_END: "end of statement block",
TOKEN_VARIABLE_BEGIN: "begin of print statement",
TOKEN_VARIABLE_END: "end of print statement",
TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",
TOKEN_LINESTATEMENT_END: "end of line statement",
TOKEN_DATA: "template data / text",
TOKEN_EOF: "end of template",
}.get(token_type, token_type)
| 163 | 180 |
def _describe_token_type(token_type: str) -> str:
if token_type in reverse_operators:
return reverse_operators[token_type]
return {
TOKEN_COMMENT_BEGIN: "begin of comment",
TOKEN_COMMENT_END: "end of comment",
TOKEN_COMMENT: "comment",
TOKEN_LINECOMMENT: "comment",
TOKEN_BLOCK_BEGIN: "begin of statement block",
TOKEN_BLOCK_END: "end of statement block",
TOKEN_VARIABLE_BEGIN: "begin of print statement",
TOKEN_VARIABLE_END: "end of print statement",
TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",
TOKEN_LINESTATEMENT_END: "end of line statement",
TOKEN_DATA: "template data / text",
TOKEN_EOF: "end of template",
}.get(token_type, token_type)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L163-L180
| 42 |
[
0,
1,
2,
3,
4
] | 27.777778 |
[] | 0 | false | 93.501048 | 18 | 2 | 100 | 0 |
def _describe_token_type(token_type: str) -> str:
if token_type in reverse_operators:
return reverse_operators[token_type]
return {
TOKEN_COMMENT_BEGIN: "begin of comment",
TOKEN_COMMENT_END: "end of comment",
TOKEN_COMMENT: "comment",
TOKEN_LINECOMMENT: "comment",
TOKEN_BLOCK_BEGIN: "begin of statement block",
TOKEN_BLOCK_END: "end of statement block",
TOKEN_VARIABLE_BEGIN: "begin of print statement",
TOKEN_VARIABLE_END: "end of print statement",
TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",
TOKEN_LINESTATEMENT_END: "end of line statement",
TOKEN_DATA: "template data / text",
TOKEN_EOF: "end of template",
}.get(token_type, token_type)
| 27,742 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
describe_token
|
(token: "Token")
|
return _describe_token_type(token.type)
|
Returns a description of the token.
|
Returns a description of the token.
| 183 | 188 |
def describe_token(token: "Token") -> str:
"""Returns a description of the token."""
if token.type == TOKEN_NAME:
return token.value
return _describe_token_type(token.type)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L183-L188
| 42 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 93.501048 | 6 | 2 | 100 | 1 |
def describe_token(token: "Token") -> str:
if token.type == TOKEN_NAME:
return token.value
return _describe_token_type(token.type)
| 27,743 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
describe_token_expr
|
(expr: str)
|
return _describe_token_type(type)
|
Like `describe_token` but for token expressions.
|
Like `describe_token` but for token expressions.
| 191 | 201 |
def describe_token_expr(expr: str) -> str:
"""Like `describe_token` but for token expressions."""
if ":" in expr:
type, value = expr.split(":", 1)
if type == TOKEN_NAME:
return value
else:
type = expr
return _describe_token_type(type)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L191-L201
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 100 |
[] | 0 | true | 93.501048 | 11 | 3 | 100 | 1 |
def describe_token_expr(expr: str) -> str:
if ":" in expr:
type, value = expr.split(":", 1)
if type == TOKEN_NAME:
return value
else:
type = expr
return _describe_token_type(type)
| 27,744 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
count_newlines
|
(value: str)
|
return len(newline_re.findall(value))
|
Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
|
Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
| 204 | 208 |
def count_newlines(value: str) -> int:
"""Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
"""
return len(newline_re.findall(value))
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L204-L208
| 42 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 93.501048 | 5 | 1 | 100 | 2 |
def count_newlines(value: str) -> int:
return len(newline_re.findall(value))
| 27,745 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
compile_rules
|
(environment: "Environment")
|
return [x[1:] for x in sorted(rules, reverse=True)]
|
Compiles all the rules from the environment into a list of rules.
|
Compiles all the rules from the environment into a list of rules.
| 211 | 249 |
def compile_rules(environment: "Environment") -> t.List[t.Tuple[str, str]]:
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(
len(environment.comment_start_string),
TOKEN_COMMENT_BEGIN,
e(environment.comment_start_string),
),
(
len(environment.block_start_string),
TOKEN_BLOCK_BEGIN,
e(environment.block_start_string),
),
(
len(environment.variable_start_string),
TOKEN_VARIABLE_BEGIN,
e(environment.variable_start_string),
),
]
if environment.line_statement_prefix is not None:
rules.append(
(
len(environment.line_statement_prefix),
TOKEN_LINESTATEMENT_BEGIN,
r"^[ \t\v]*" + e(environment.line_statement_prefix),
)
)
if environment.line_comment_prefix is not None:
rules.append(
(
len(environment.line_comment_prefix),
TOKEN_LINECOMMENT_BEGIN,
r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),
)
)
return [x[1:] for x in sorted(rules, reverse=True)]
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L211-L249
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38
] | 100 |
[] | 0 | true | 93.501048 | 39 | 4 | 100 | 1 |
def compile_rules(environment: "Environment") -> t.List[t.Tuple[str, str]]:
e = re.escape
rules = [
(
len(environment.comment_start_string),
TOKEN_COMMENT_BEGIN,
e(environment.comment_start_string),
),
(
len(environment.block_start_string),
TOKEN_BLOCK_BEGIN,
e(environment.block_start_string),
),
(
len(environment.variable_start_string),
TOKEN_VARIABLE_BEGIN,
e(environment.variable_start_string),
),
]
if environment.line_statement_prefix is not None:
rules.append(
(
len(environment.line_statement_prefix),
TOKEN_LINESTATEMENT_BEGIN,
r"^[ \t\v]*" + e(environment.line_statement_prefix),
)
)
if environment.line_comment_prefix is not None:
rules.append(
(
len(environment.line_comment_prefix),
TOKEN_LINECOMMENT_BEGIN,
r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),
)
)
return [x[1:] for x in sorted(rules, reverse=True)]
| 27,746 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
get_lexer
|
(environment: "Environment")
|
return lexer
|
Return a lexer which is probably cached.
|
Return a lexer which is probably cached.
| 426 | 447 |
def get_lexer(environment: "Environment") -> "Lexer":
"""Return a lexer which is probably cached."""
key = (
environment.block_start_string,
environment.block_end_string,
environment.variable_start_string,
environment.variable_end_string,
environment.comment_start_string,
environment.comment_end_string,
environment.line_statement_prefix,
environment.line_comment_prefix,
environment.trim_blocks,
environment.lstrip_blocks,
environment.newline_sequence,
environment.keep_trailing_newline,
)
lexer = _lexer_cache.get(key)
if lexer is None:
_lexer_cache[key] = lexer = Lexer(environment)
return lexer
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L426-L447
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21
] | 100 |
[] | 0 | true | 93.501048 | 22 | 2 | 100 | 1 |
def get_lexer(environment: "Environment") -> "Lexer":
key = (
environment.block_start_string,
environment.block_end_string,
environment.variable_start_string,
environment.variable_end_string,
environment.comment_start_string,
environment.comment_end_string,
environment.line_statement_prefix,
environment.line_comment_prefix,
environment.trim_blocks,
environment.lstrip_blocks,
environment.newline_sequence,
environment.keep_trailing_newline,
)
lexer = _lexer_cache.get(key)
if lexer is None:
_lexer_cache[key] = lexer = Lexer(environment)
return lexer
| 27,747 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
Failure.__init__
|
(
self, message: str, cls: t.Type[TemplateSyntaxError] = TemplateSyntaxError
)
| 257 | 261 |
def __init__(
self, message: str, cls: t.Type[TemplateSyntaxError] = TemplateSyntaxError
) -> None:
self.message = message
self.error_class = cls
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L257-L261
| 42 |
[
0,
3,
4
] | 60 |
[] | 0 | false | 93.501048 | 5 | 1 | 100 | 0 |
def __init__(
self, message: str, cls: t.Type[TemplateSyntaxError] = TemplateSyntaxError
) -> None:
self.message = message
self.error_class = cls
| 27,748 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
Token.__str__
|
(self)
|
return describe_token(self)
| 272 | 273 |
def __str__(self) -> str:
return describe_token(self)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L272-L273
| 42 |
[
0
] | 50 |
[
1
] | 50 | false | 93.501048 | 2 | 1 | 50 | 0 |
def __str__(self) -> str:
return describe_token(self)
| 27,749 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStreamIterator.__init__
|
(self, stream: "TokenStream")
| 300 | 301 |
def __init__(self, stream: "TokenStream") -> None:
self.stream = stream
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L300-L301
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 93.501048 | 2 | 1 | 100 | 0 |
def __init__(self, stream: "TokenStream") -> None:
self.stream = stream
| 27,750 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStreamIterator.__iter__
|
(self)
|
return self
| 303 | 304 |
def __iter__(self) -> "TokenStreamIterator":
return self
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L303-L304
| 42 |
[
0
] | 50 |
[
1
] | 50 | false | 93.501048 | 2 | 1 | 50 | 0 |
def __iter__(self) -> "TokenStreamIterator":
return self
| 27,751 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStreamIterator.__next__
|
(self)
|
return token
| 306 | 314 |
def __next__(self) -> Token:
token = self.stream.current
if token.type is TOKEN_EOF:
self.stream.close()
raise StopIteration
next(self.stream)
return token
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L306-L314
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 100 |
[] | 0 | true | 93.501048 | 9 | 2 | 100 | 0 |
def __next__(self) -> Token:
token = self.stream.current
if token.type is TOKEN_EOF:
self.stream.close()
raise StopIteration
next(self.stream)
return token
| 27,752 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.__init__
|
(
self,
generator: t.Iterable[Token],
name: t.Optional[str],
filename: t.Optional[str],
)
| 323 | 335 |
def __init__(
self,
generator: t.Iterable[Token],
name: t.Optional[str],
filename: t.Optional[str],
):
self._iter = iter(generator)
self._pushed: "te.Deque[Token]" = deque()
self.name = name
self.filename = filename
self.closed = False
self.current = Token(1, TOKEN_INITIAL, "")
next(self)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L323-L335
| 42 |
[
0,
6,
7,
8,
9,
10,
11,
12
] | 61.538462 |
[] | 0 | false | 93.501048 | 13 | 1 | 100 | 0 |
def __init__(
self,
generator: t.Iterable[Token],
name: t.Optional[str],
filename: t.Optional[str],
):
self._iter = iter(generator)
self._pushed: "te.Deque[Token]" = deque()
self.name = name
self.filename = filename
self.closed = False
self.current = Token(1, TOKEN_INITIAL, "")
next(self)
| 27,753 |
|||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.__iter__
|
(self)
|
return TokenStreamIterator(self)
| 337 | 338 |
def __iter__(self) -> TokenStreamIterator:
return TokenStreamIterator(self)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L337-L338
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 93.501048 | 2 | 1 | 100 | 0 |
def __iter__(self) -> TokenStreamIterator:
return TokenStreamIterator(self)
| 27,754 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.__bool__
|
(self)
|
return bool(self._pushed) or self.current.type is not TOKEN_EOF
| 340 | 341 |
def __bool__(self) -> bool:
return bool(self._pushed) or self.current.type is not TOKEN_EOF
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L340-L341
| 42 |
[
0,
1
] | 100 |
[] | 0 | true | 93.501048 | 2 | 2 | 100 | 0 |
def __bool__(self) -> bool:
return bool(self._pushed) or self.current.type is not TOKEN_EOF
| 27,755 |
||
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.eos
|
(self)
|
return not self
|
Are we at the end of the stream?
|
Are we at the end of the stream?
| 344 | 346 |
def eos(self) -> bool:
"""Are we at the end of the stream?"""
return not self
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L344-L346
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 93.501048 | 3 | 1 | 100 | 1 |
def eos(self) -> bool:
return not self
| 27,756 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.push
|
(self, token: Token)
|
Push a token back to the stream.
|
Push a token back to the stream.
| 348 | 350 |
def push(self, token: Token) -> None:
"""Push a token back to the stream."""
self._pushed.append(token)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L348-L350
| 42 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 93.501048 | 3 | 1 | 100 | 1 |
def push(self, token: Token) -> None:
self._pushed.append(token)
| 27,757 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.look
|
(self)
|
return result
|
Look at the next token.
|
Look at the next token.
| 352 | 358 |
def look(self) -> Token:
"""Look at the next token."""
old_token = next(self)
result = self.current
self.push(result)
self.current = old_token
return result
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L352-L358
| 42 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 93.501048 | 7 | 1 | 100 | 1 |
def look(self) -> Token:
old_token = next(self)
result = self.current
self.push(result)
self.current = old_token
return result
| 27,758 |
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.skip
|
(self, n: int = 1)
|
Got n tokens ahead.
|
Got n tokens ahead.
| 360 | 363 |
def skip(self, n: int = 1) -> None:
"""Got n tokens ahead."""
for _ in range(n):
next(self)
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L360-L363
| 42 |
[
0,
1,
2,
3
] | 100 |
[] | 0 | true | 93.501048 | 4 | 2 | 100 | 1 |
def skip(self, n: int = 1) -> None:
for _ in range(n):
next(self)
| 27,759 |
|
pallets/jinja
|
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
|
src/jinja2/lexer.py
|
TokenStream.next_if
|
(self, expr: str)
|
return None
|
Perform the token test and return the token if it matched.
Otherwise the return value is `None`.
|
Perform the token test and return the token if it matched.
Otherwise the return value is `None`.
| 365 | 372 |
def next_if(self, expr: str) -> t.Optional[Token]:
"""Perform the token test and return the token if it matched.
Otherwise the return value is `None`.
"""
if self.current.test(expr):
return next(self)
return None
|
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/lexer.py#L365-L372
| 42 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 93.501048 | 8 | 2 | 100 | 2 |
def next_if(self, expr: str) -> t.Optional[Token]:
if self.current.test(expr):
return next(self)
return None
| 27,760 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.