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/environment.py
Environment.compile
( self, source: t.Union[str, nodes.Template], name: t.Optional[str] = None, filename: t.Optional[str] = None, raw: bool = False, defer_init: bool = False, )
Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted. The return value of this method is a python code object. If the `raw` parameter is `True` the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally. `defer_init` is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set. .. versionadded:: 2.4 `defer_init` parameter added.
Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted.
729
768
def compile( self, source: t.Union[str, nodes.Template], name: t.Optional[str] = None, filename: t.Optional[str] = None, raw: bool = False, defer_init: bool = False, ) -> t.Union[str, CodeType]: """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted. The return value of this method is a python code object. If the `raw` parameter is `True` the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally. `defer_init` is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set. .. versionadded:: 2.4 `defer_init` parameter added. """ source_hint = None try: if isinstance(source, str): source_hint = source source = self._parse(source, name, filename) source = self._generate(source, name, filename, defer_init=defer_init) if raw: return source if filename is None: filename = "<template>" return self._compile(source, filename) except TemplateSyntaxError: self.handle_exception(source=source_hint)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L729-L768
42
[ 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ]
37.5
[]
0
false
84.441656
40
5
100
18
def compile( self, source: t.Union[str, nodes.Template], name: t.Optional[str] = None, filename: t.Optional[str] = None, raw: bool = False, defer_init: bool = False, ) -> t.Union[str, CodeType]: source_hint = None try: if isinstance(source, str): source_hint = source source = self._parse(source, name, filename) source = self._generate(source, name, filename, defer_init=defer_init) if raw: return source if filename is None: filename = "<template>" return self._compile(source, filename) except TemplateSyntaxError: self.handle_exception(source=source_hint)
27,461
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.compile_expression
( self, source: str, undefined_to_none: bool = True )
return TemplateExpression(template, undefined_to_none)
A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1
A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.
770
813
def compile_expression( self, source: str, undefined_to_none: bool = True ) -> "TemplateExpression": """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1 """ parser = Parser(self, source, state="variable") try: expr = parser.parse_expression() if not parser.stream.eos: raise TemplateSyntaxError( "chunk after expression", parser.stream.current.lineno, None, None ) expr.set_environment(self) except TemplateSyntaxError: self.handle_exception(source=source) body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)] template = self.from_string(nodes.Template(body, lineno=1)) return TemplateExpression(template, undefined_to_none)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L770-L813
42
[ 0, 29, 30, 31, 32, 33, 36, 37, 40, 41, 42, 43 ]
27.272727
[ 34, 38, 39 ]
6.818182
false
84.441656
44
3
93.181818
26
def compile_expression( self, source: str, undefined_to_none: bool = True ) -> "TemplateExpression": parser = Parser(self, source, state="variable") try: expr = parser.parse_expression() if not parser.stream.eos: raise TemplateSyntaxError( "chunk after expression", parser.stream.current.lineno, None, None ) expr.set_environment(self) except TemplateSyntaxError: self.handle_exception(source=source) body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)] template = self.from_string(nodes.Template(body, lineno=1)) return TemplateExpression(template, undefined_to_none)
27,462
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.compile_templates
( self, target: t.Union[str, os.PathLike], extensions: t.Optional[t.Collection[str]] = None, filter_func: t.Optional[t.Callable[[str], bool]] = None, zip: t.Optional[str] = "deflated", log_function: t.Optional[t.Callable[[str], None]] = None, ignore_errors: bool = True, )
Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, `zip` can be set to ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. .. versionadded:: 2.4
Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, `zip` can be set to ``'stored'``.
815
891
def compile_templates( self, target: t.Union[str, os.PathLike], extensions: t.Optional[t.Collection[str]] = None, filter_func: t.Optional[t.Callable[[str], bool]] = None, zip: t.Optional[str] = "deflated", log_function: t.Optional[t.Callable[[str], None]] = None, ignore_errors: bool = True, ) -> None: """Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, `zip` can be set to ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. .. versionadded:: 2.4 """ from .loaders import ModuleLoader if log_function is None: def log_function(x: str) -> None: pass assert log_function is not None assert self.loader is not None, "No loader configured." def write_file(filename: str, data: str) -> None: if zip: info = ZipInfo(filename) info.external_attr = 0o755 << 16 zip_file.writestr(info, data) else: with open(os.path.join(target, filename), "wb") as f: f.write(data.encode("utf8")) if zip is not None: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED zip_file = ZipFile( target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip] ) log_function(f"Compiling into Zip archive {target!r}") else: if not os.path.isdir(target): os.makedirs(target) log_function(f"Compiling into folder {target!r}") try: for name in self.list_templates(extensions, filter_func): source, filename, _ = self.loader.get_source(self, name) try: code = self.compile(source, name, filename, True, True) except TemplateSyntaxError as e: if not ignore_errors: raise log_function(f'Could not compile "{name}": {e}') continue filename = ModuleLoader.get_module_filename(name) write_file(filename, code) log_function(f'Compiled "{name}" as {filename}') finally: if zip: zip_file.close() log_function("Finished compiling templates")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L815-L891
42
[ 0, 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, 53, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 ]
66.233766
[ 54, 64 ]
2.597403
false
84.441656
77
14
97.402597
16
def compile_templates( self, target: t.Union[str, os.PathLike], extensions: t.Optional[t.Collection[str]] = None, filter_func: t.Optional[t.Callable[[str], bool]] = None, zip: t.Optional[str] = "deflated", log_function: t.Optional[t.Callable[[str], None]] = None, ignore_errors: bool = True, ) -> None: from .loaders import ModuleLoader if log_function is None: def log_function(x: str) -> None: pass assert log_function is not None assert self.loader is not None, "No loader configured." def write_file(filename: str, data: str) -> None: if zip: info = ZipInfo(filename) info.external_attr = 0o755 << 16 zip_file.writestr(info, data) else: with open(os.path.join(target, filename), "wb") as f: f.write(data.encode("utf8")) if zip is not None: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED zip_file = ZipFile( target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip] ) log_function(f"Compiling into Zip archive {target!r}") else: if not os.path.isdir(target): os.makedirs(target) log_function(f"Compiling into folder {target!r}") try: for name in self.list_templates(extensions, filter_func): source, filename, _ = self.loader.get_source(self, name) try: code = self.compile(source, name, filename, True, True) except TemplateSyntaxError as e: if not ignore_errors: raise log_function(f'Could not compile "{name}": {e}') continue filename = ModuleLoader.get_module_filename(name) write_file(filename, code) log_function(f'Compiled "{name}" as {filename}') finally: if zip: zip_file.close() log_function("Finished compiling templates")
27,463
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.list_templates
( self, extensions: t.Optional[t.Collection[str]] = None, filter_func: t.Optional[t.Callable[[str], bool]] = None, )
return names
Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either `extensions` is set to a list of file extensions for templates, or a `filter_func` can be provided which is a callable that is passed a template name and should return `True` if it should end up in the result list. If the loader does not support that, a :exc:`TypeError` is raised. .. versionadded:: 2.4
Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method.
893
928
def list_templates( self, extensions: t.Optional[t.Collection[str]] = None, filter_func: t.Optional[t.Callable[[str], bool]] = None, ) -> t.List[str]: """Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either `extensions` is set to a list of file extensions for templates, or a `filter_func` can be provided which is a callable that is passed a template name and should return `True` if it should end up in the result list. If the loader does not support that, a :exc:`TypeError` is raised. .. versionadded:: 2.4 """ assert self.loader is not None, "No loader configured." names = self.loader.list_templates() if extensions is not None: if filter_func is not None: raise TypeError( "either extensions or filter_func can be passed, but not both" ) def filter_func(x: str) -> bool: return "." in x and x.rsplit(".", 1)[1] in extensions # type: ignore if filter_func is not None: names = [name for name in names if filter_func(name)] return names
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L893-L928
42
[ 0, 19, 20, 21, 22, 23, 31, 32, 34, 35 ]
27.777778
[ 24, 25, 29, 30, 33 ]
13.888889
false
84.441656
36
8
86.111111
14
def list_templates( self, extensions: t.Optional[t.Collection[str]] = None, filter_func: t.Optional[t.Callable[[str], bool]] = None, ) -> t.List[str]: assert self.loader is not None, "No loader configured." names = self.loader.list_templates() if extensions is not None: if filter_func is not None: raise TypeError( "either extensions or filter_func can be passed, but not both" ) def filter_func(x: str) -> bool: return "." in x and x.rsplit(".", 1)[1] in extensions # type: ignore if filter_func is not None: names = [name for name in names if filter_func(name)] return names
27,464
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.handle_exception
(self, source: t.Optional[str] = None)
Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.
Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.
930
936
def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn": """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ from .debug import rewrite_traceback_stack raise rewrite_traceback_stack(source=source)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L930-L936
42
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
84.441656
7
1
100
2
def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn": from .debug import rewrite_traceback_stack raise rewrite_traceback_stack(source=source)
27,465
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.join_path
(self, template: str, parent: str)
return template
Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here.
Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.
938
948
def join_path(self, template: str, parent: str) -> str: """Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here. """ return template
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L938-L948
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
84.441656
11
1
100
8
def join_path(self, template: str, parent: str) -> str: return template
27,466
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment._load_template
( self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] )
return template
951
973
def _load_template( self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] ) -> "Template": if self.loader is None: raise TypeError("no loader for this environment specified") cache_key = (weakref.ref(self.loader), name) if self.cache is not None: template = self.cache.get(cache_key) if template is not None and ( not self.auto_reload or template.is_up_to_date ): # template.globals is a ChainMap, modifying it will only # affect the template, not the environment globals. if globals: template.globals.update(globals) return template template = self.loader.load(self, name, self.make_globals(globals)) if self.cache is not None: self.cache[cache_key] = template return template
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L951-L973
42
[ 0, 3, 5, 6, 7, 8, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
73.913043
[ 4 ]
4.347826
false
84.441656
23
8
95.652174
0
def _load_template( self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] ) -> "Template": if self.loader is None: raise TypeError("no loader for this environment specified") cache_key = (weakref.ref(self.loader), name) if self.cache is not None: template = self.cache.get(cache_key) if template is not None and ( not self.auto_reload or template.is_up_to_date ): # template.globals is a ChainMap, modifying it will only # affect the template, not the environment globals. if globals: template.globals.update(globals) return template template = self.loader.load(self, name, self.make_globals(globals)) if self.cache is not None: self.cache[cache_key] = template return template
27,467
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.get_template
( self, name: t.Union[str, "Template"], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
return self._load_template(name, globals)
Load a template by name with :attr:`loader` and return a :class:`Template`. If the template does not exist a :exc:`TemplateNotFound` exception is raised. :param name: Name of the template to load. When loading templates from the filesystem, "/" is used as the path separator, even on Windows. :param parent: The name of the parent template importing this template. :meth:`join_path` can be used to implement name transformations with this. :param globals: Extend the environment :attr:`globals` with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items. .. versionchanged:: 3.0 If a template is loaded from cache, ``globals`` will update the template's globals instead of ignoring the new values. .. versionchanged:: 2.4 If ``name`` is a :class:`Template` object it is returned unchanged.
Load a template by name with :attr:`loader` and return a :class:`Template`. If the template does not exist a :exc:`TemplateNotFound` exception is raised.
976
1,010
def get_template( self, name: t.Union[str, "Template"], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": """Load a template by name with :attr:`loader` and return a :class:`Template`. If the template does not exist a :exc:`TemplateNotFound` exception is raised. :param name: Name of the template to load. When loading templates from the filesystem, "/" is used as the path separator, even on Windows. :param parent: The name of the parent template importing this template. :meth:`join_path` can be used to implement name transformations with this. :param globals: Extend the environment :attr:`globals` with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items. .. versionchanged:: 3.0 If a template is loaded from cache, ``globals`` will update the template's globals instead of ignoring the new values. .. versionchanged:: 2.4 If ``name`` is a :class:`Template` object it is returned unchanged. """ if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) return self._load_template(name, globals)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L976-L1010
42
[ 0, 28, 29, 30, 31, 32, 33, 34 ]
22.857143
[]
0
false
84.441656
35
3
100
22
def get_template( self, name: t.Union[str, "Template"], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) return self._load_template(name, globals)
27,468
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.select_template
( self, names: t.Iterable[t.Union[str, "Template"]], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
Like :meth:`get_template`, but tries loading multiple names. If none of the names can be loaded a :exc:`TemplatesNotFound` exception is raised. :param names: List of template names to try loading in order. :param parent: The name of the parent template importing this template. :meth:`join_path` can be used to implement name transformations with this. :param globals: Extend the environment :attr:`globals` with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items. .. versionchanged:: 3.0 If a template is loaded from cache, ``globals`` will update the template's globals instead of ignoring the new values. .. versionchanged:: 2.11 If ``names`` is :class:`Undefined`, an :exc:`UndefinedError` is raised instead. If no templates were found and ``names`` contains :class:`Undefined`, the message is more helpful. .. versionchanged:: 2.4 If ``names`` contains a :class:`Template` object it is returned unchanged. .. versionadded:: 2.3
Like :meth:`get_template`, but tries loading multiple names. If none of the names can be loaded a :exc:`TemplatesNotFound` exception is raised.
1,013
1,064
def select_template( self, names: t.Iterable[t.Union[str, "Template"]], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": """Like :meth:`get_template`, but tries loading multiple names. If none of the names can be loaded a :exc:`TemplatesNotFound` exception is raised. :param names: List of template names to try loading in order. :param parent: The name of the parent template importing this template. :meth:`join_path` can be used to implement name transformations with this. :param globals: Extend the environment :attr:`globals` with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items. .. versionchanged:: 3.0 If a template is loaded from cache, ``globals`` will update the template's globals instead of ignoring the new values. .. versionchanged:: 2.11 If ``names`` is :class:`Undefined`, an :exc:`UndefinedError` is raised instead. If no templates were found and ``names`` contains :class:`Undefined`, the message is more helpful. .. versionchanged:: 2.4 If ``names`` contains a :class:`Template` object it is returned unchanged. .. versionadded:: 2.3 """ if isinstance(names, Undefined): names._fail_with_undefined_error() if not names: raise TemplatesNotFound( message="Tried to select from an empty list of templates." ) for name in names: if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) try: return self._load_template(name, globals) except (TemplateNotFound, UndefinedError): pass raise TemplatesNotFound(names)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1013-L1064
42
[ 0, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 47, 48, 49, 50, 51 ]
30.769231
[ 38, 46 ]
3.846154
false
84.441656
52
7
96.153846
27
def select_template( self, names: t.Iterable[t.Union[str, "Template"]], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": if isinstance(names, Undefined): names._fail_with_undefined_error() if not names: raise TemplatesNotFound( message="Tried to select from an empty list of templates." ) for name in names: if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) try: return self._load_template(name, globals) except (TemplateNotFound, UndefinedError): pass raise TemplatesNotFound(names)
27,469
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.get_or_select_template
( self, template_name_or_list: t.Union[ str, "Template", t.List[t.Union[str, "Template"]] ], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, )
return self.select_template(template_name_or_list, parent, globals)
Use :meth:`select_template` if an iterable of template names is given, or :meth:`get_template` if one name is given. .. versionadded:: 2.3
Use :meth:`select_template` if an iterable of template names is given, or :meth:`get_template` if one name is given.
1,067
1,084
def get_or_select_template( self, template_name_or_list: t.Union[ str, "Template", t.List[t.Union[str, "Template"]] ], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": """Use :meth:`select_template` if an iterable of template names is given, or :meth:`get_template` if one name is given. .. versionadded:: 2.3 """ if isinstance(template_name_or_list, (str, Undefined)): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1067-L1084
42
[ 0, 12, 13, 14, 15, 16, 17 ]
38.888889
[]
0
false
84.441656
18
3
100
4
def get_or_select_template( self, template_name_or_list: t.Union[ str, "Template", t.List[t.Union[str, "Template"]] ], parent: t.Optional[str] = None, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": if isinstance(template_name_or_list, (str, Undefined)): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals)
27,470
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.from_string
( self, source: t.Union[str, nodes.Template], globals: t.Optional[t.MutableMapping[str, t.Any]] = None, template_class: t.Optional[t.Type["Template"]] = None, )
return cls.from_code(self, self.compile(source), gs, None)
Load a template from a source string without using :attr:`loader`. :param source: Jinja source to compile into a template. :param globals: Extend the environment :attr:`globals` with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items. :param template_class: Return an instance of this :class:`Template` class.
Load a template from a source string without using :attr:`loader`.
1,086
1,105
def from_string( self, source: t.Union[str, nodes.Template], globals: t.Optional[t.MutableMapping[str, t.Any]] = None, template_class: t.Optional[t.Type["Template"]] = None, ) -> "Template": """Load a template from a source string without using :attr:`loader`. :param source: Jinja source to compile into a template. :param globals: Extend the environment :attr:`globals` with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items. :param template_class: Return an instance of this :class:`Template` class. """ gs = self.make_globals(globals) cls = template_class or self.template_class return cls.from_code(self, self.compile(source), gs, None)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1086-L1105
42
[ 0, 16, 17, 18, 19 ]
25
[]
0
false
84.441656
20
2
100
10
def from_string( self, source: t.Union[str, nodes.Template], globals: t.Optional[t.MutableMapping[str, t.Any]] = None, template_class: t.Optional[t.Type["Template"]] = None, ) -> "Template": gs = self.make_globals(globals) cls = template_class or self.template_class return cls.from_code(self, self.compile(source), gs, None)
27,471
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Environment.make_globals
( self, d: t.Optional[t.MutableMapping[str, t.Any]] )
return ChainMap(d, self.globals)
Make the globals map for a template. Any given template globals overlay the environment :attr:`globals`. Returns a :class:`collections.ChainMap`. This allows any changes to a template's globals to only affect that template, while changes to the environment's globals are still reflected. However, avoid modifying any globals after a template is loaded. :param d: Dict of template-specific globals. .. versionchanged:: 3.0 Use :class:`collections.ChainMap` to always prevent mutating environment globals.
Make the globals map for a template. Any given template globals overlay the environment :attr:`globals`.
1,107
1,127
def make_globals( self, d: t.Optional[t.MutableMapping[str, t.Any]] ) -> t.MutableMapping[str, t.Any]: """Make the globals map for a template. Any given template globals overlay the environment :attr:`globals`. Returns a :class:`collections.ChainMap`. This allows any changes to a template's globals to only affect that template, while changes to the environment's globals are still reflected. However, avoid modifying any globals after a template is loaded. :param d: Dict of template-specific globals. .. versionchanged:: 3.0 Use :class:`collections.ChainMap` to always prevent mutating environment globals. """ if d is None: d = {} return ChainMap(d, self.globals)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1107-L1127
42
[ 0, 16, 17, 18, 19, 20 ]
28.571429
[]
0
false
84.441656
21
2
100
13
def make_globals( self, d: t.Optional[t.MutableMapping[str, t.Any]] ) -> t.MutableMapping[str, t.Any]: if d is None: d = {} return ChainMap(d, self.globals)
27,472
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.__new__
( cls, source: t.Union[str, nodes.Template], block_start_string: str = BLOCK_START_STRING, block_end_string: str = BLOCK_END_STRING, variable_start_string: str = VARIABLE_START_STRING, variable_end_string: str = VARIABLE_END_STRING, comment_start_string: str = COMMENT_START_STRING, comment_end_string: str = COMMENT_END_STRING, line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, trim_blocks: bool = TRIM_BLOCKS, lstrip_blocks: bool = LSTRIP_BLOCKS, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), optimized: bool = True, undefined: t.Type[Undefined] = Undefined, finalize: t.Optional[t.Callable[..., t.Any]] = None, autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, enable_async: bool = False, )
return env.from_string(source, template_class=cls)
1,161
1,208
def __new__( cls, source: t.Union[str, nodes.Template], block_start_string: str = BLOCK_START_STRING, block_end_string: str = BLOCK_END_STRING, variable_start_string: str = VARIABLE_START_STRING, variable_end_string: str = VARIABLE_END_STRING, comment_start_string: str = COMMENT_START_STRING, comment_end_string: str = COMMENT_END_STRING, line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, trim_blocks: bool = TRIM_BLOCKS, lstrip_blocks: bool = LSTRIP_BLOCKS, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), optimized: bool = True, undefined: t.Type[Undefined] = Undefined, finalize: t.Optional[t.Callable[..., t.Any]] = None, autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, enable_async: bool = False, ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build... env = get_spontaneous_environment( cls.environment_class, # type: ignore block_start_string, block_end_string, variable_start_string, variable_end_string, comment_start_string, comment_end_string, line_statement_prefix, line_comment_prefix, trim_blocks, lstrip_blocks, newline_sequence, keep_trailing_newline, frozenset(extensions), optimized, undefined, # type: ignore finalize, autoescape, None, 0, False, None, enable_async, ) return env.from_string(source, template_class=cls)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1161-L1208
42
[ 0, 22, 47 ]
6.25
[]
0
false
84.441656
48
1
100
0
def __new__( cls, source: t.Union[str, nodes.Template], block_start_string: str = BLOCK_START_STRING, block_end_string: str = BLOCK_END_STRING, variable_start_string: str = VARIABLE_START_STRING, variable_end_string: str = VARIABLE_END_STRING, comment_start_string: str = COMMENT_START_STRING, comment_end_string: str = COMMENT_END_STRING, line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, trim_blocks: bool = TRIM_BLOCKS, lstrip_blocks: bool = LSTRIP_BLOCKS, newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), optimized: bool = True, undefined: t.Type[Undefined] = Undefined, finalize: t.Optional[t.Callable[..., t.Any]] = None, autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, enable_async: bool = False, ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build... env = get_spontaneous_environment( cls.environment_class, # type: ignore block_start_string, block_end_string, variable_start_string, variable_end_string, comment_start_string, comment_end_string, line_statement_prefix, line_comment_prefix, trim_blocks, lstrip_blocks, newline_sequence, keep_trailing_newline, frozenset(extensions), optimized, undefined, # type: ignore finalize, autoescape, None, 0, False, None, enable_async, ) return env.from_string(source, template_class=cls)
27,473
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.from_code
( cls, environment: Environment, code: CodeType, globals: t.MutableMapping[str, t.Any], uptodate: t.Optional[t.Callable[[], bool]] = None, )
return rv
Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object.
Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object.
1,211
1,225
def from_code( cls, environment: Environment, code: CodeType, globals: t.MutableMapping[str, t.Any], uptodate: t.Optional[t.Callable[[], bool]] = None, ) -> "Template": """Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object. """ namespace = {"environment": environment, "__file__": code.co_filename} exec(code, namespace) rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1211-L1225
42
[ 0, 9, 10, 11, 12, 13, 14 ]
46.666667
[]
0
false
84.441656
15
1
100
2
def from_code( cls, environment: Environment, code: CodeType, globals: t.MutableMapping[str, t.Any], uptodate: t.Optional[t.Callable[[], bool]] = None, ) -> "Template": namespace = {"environment": environment, "__file__": code.co_filename} exec(code, namespace) rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv
27,474
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.from_module_dict
( cls, environment: Environment, module_dict: t.MutableMapping[str, t.Any], globals: t.MutableMapping[str, t.Any], )
return cls._from_namespace(environment, module_dict, globals)
Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4
Creates a template object from a module. This is used by the module loader to create a template object.
1,228
1,239
def from_module_dict( cls, environment: Environment, module_dict: t.MutableMapping[str, t.Any], globals: t.MutableMapping[str, t.Any], ) -> "Template": """Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4 """ return cls._from_namespace(environment, module_dict, globals)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1228-L1239
42
[ 0, 10, 11 ]
25
[]
0
false
84.441656
12
1
100
4
def from_module_dict( cls, environment: Environment, module_dict: t.MutableMapping[str, t.Any], globals: t.MutableMapping[str, t.Any], ) -> "Template": return cls._from_namespace(environment, module_dict, globals)
27,475
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template._from_namespace
( cls, environment: Environment, namespace: t.MutableMapping[str, t.Any], globals: t.MutableMapping[str, t.Any], )
return t
1,242
1,267
def _from_namespace( cls, environment: Environment, namespace: t.MutableMapping[str, t.Any], globals: t.MutableMapping[str, t.Any], ) -> "Template": t: "Template" = object.__new__(cls) t.environment = environment t.globals = globals t.name = namespace["name"] t.filename = namespace["__file__"] t.blocks = namespace["blocks"] # render function and module t.root_render_func = namespace["root"] t._module = None # debug and loader helpers t._debug_info = namespace["debug_info"] t._uptodate = None # store the reference namespace["environment"] = environment namespace["__jinja_template__"] = t return t
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1242-L1267
42
[ 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
80.769231
[]
0
false
84.441656
26
1
100
0
def _from_namespace( cls, environment: Environment, namespace: t.MutableMapping[str, t.Any], globals: t.MutableMapping[str, t.Any], ) -> "Template": t: "Template" = object.__new__(cls) t.environment = environment t.globals = globals t.name = namespace["name"] t.filename = namespace["__file__"] t.blocks = namespace["blocks"] # render function and module t.root_render_func = namespace["root"] t._module = None # debug and loader helpers t._debug_info = namespace["debug_info"] t._uptodate = None # store the reference namespace["environment"] = environment namespace["__jinja_template__"] = t return t
27,476
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.render
(self, *args: t.Any, **kwargs: t.Any)
This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights='that say nih') template.render({'knights': 'that say nih'}) This will return the rendered template as a string.
This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same::
1,269
1,301
def render(self, *args: t.Any, **kwargs: t.Any) -> str: """This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights='that say nih') template.render({'knights': 'that say nih'}) This will return the rendered template as a string. """ if self.environment.is_async: import asyncio close = False try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() close = True try: return loop.run_until_complete(self.render_async(*args, **kwargs)) finally: if close: loop.close() ctx = self.new_context(dict(*args, **kwargs)) try: return self.environment.concat(self.root_render_func(ctx)) # type: ignore except Exception: self.environment.handle_exception()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1269-L1301
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 ]
100
[]
0
true
84.441656
33
5
100
8
def render(self, *args: t.Any, **kwargs: t.Any) -> str: if self.environment.is_async: import asyncio close = False try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() close = True try: return loop.run_until_complete(self.render_async(*args, **kwargs)) finally: if close: loop.close() ctx = self.new_context(dict(*args, **kwargs)) try: return self.environment.concat(self.root_render_func(ctx)) # type: ignore except Exception: self.environment.handle_exception()
27,477
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.render_async
(self, *args: t.Any, **kwargs: t.Any)
This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled. Example usage:: await template.render_async(knights='that say nih; asynchronously')
This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled.
1,303
1,324
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str: """This works similar to :meth:`render` but returns a coroutine that when awaited returns the entire rendered template string. This requires the async feature to be enabled. Example usage:: await template.render_async(knights='that say nih; asynchronously') """ 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.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/environment.py#L1303-L1324
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
86.363636
[ 10 ]
4.545455
false
84.441656
22
4
95.454545
7
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str: 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.concat( # type: ignore [n async for n in self.root_render_func(ctx)] # type: ignore ) except Exception: return self.environment.handle_exception()
27,478
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.stream
(self, *args: t.Any, **kwargs: t.Any)
return TemplateStream(self.generate(*args, **kwargs))
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
1,326
1,330
def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream": """Works exactly like :meth:`generate` but returns a :class:`TemplateStream`. """ return TemplateStream(self.generate(*args, **kwargs))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1326-L1330
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
84.441656
5
1
100
2
def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream": return TemplateStream(self.generate(*args, **kwargs))
27,479
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.generate
(self, *args: t.Any, **kwargs: t.Any)
For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as strings. It accepts the same arguments as :meth:`render`.
For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as strings.
1,332
1,354
def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]: """For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as strings. It accepts the same arguments as :meth:`render`. """ if self.environment.is_async: import asyncio async def to_list() -> t.List[str]: return [x async for x in self.generate_async(*args, **kwargs)] yield from asyncio.run(to_list()) return ctx = self.new_context(dict(*args, **kwargs)) try: yield from self.root_render_func(ctx) except Exception: yield self.environment.handle_exception()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1332-L1354
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
95.652174
[ 22 ]
4.347826
false
84.441656
23
5
95.652174
6
def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]: if self.environment.is_async: import asyncio async def to_list() -> t.List[str]: return [x async for x in self.generate_async(*args, **kwargs)] yield from asyncio.run(to_list()) return ctx = self.new_context(dict(*args, **kwargs)) try: yield from self.root_render_func(ctx) except Exception: yield self.environment.handle_exception()
27,480
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.generate_async
( self, *args: t.Any, **kwargs: t.Any )
An async version of :meth:`generate`. Works very similarly but returns an async iterator instead.
An async version of :meth:`generate`. Works very similarly but returns an async iterator instead.
1,356
1,373
async def generate_async( self, *args: t.Any, **kwargs: t.Any ) -> t.AsyncIterator[str]: """An async version of :meth:`generate`. Works very similarly but returns an async iterator instead. """ 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: async for event in self.root_render_func(ctx): # type: ignore yield event except Exception: yield self.environment.handle_exception()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1356-L1373
42
[ 0, 5, 6, 10, 11, 12, 13, 14, 15 ]
50
[ 7, 16, 17 ]
16.666667
false
84.441656
18
4
83.333333
2
async def generate_async( self, *args: t.Any, **kwargs: t.Any ) -> t.AsyncIterator[str]: 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: async for event in self.root_render_func(ctx): # type: ignore yield event except Exception: yield self.environment.handle_exception()
27,481
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.new_context
( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, )
return new_context( self.environment, self.name, self.blocks, vars, shared, self.globals, locals )
Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as is to the context without adding the globals. `locals` can be a dict of local variables for internal usage.
Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as is to the context without adding the globals.
1,375
1,390
def new_context( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> Context: """Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as is to the context without adding the globals. `locals` can be a dict of local variables for internal usage. """ return new_context( self.environment, self.name, self.blocks, vars, shared, self.globals, locals )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1375-L1390
42
[ 0, 12, 13, 14, 15 ]
31.25
[]
0
false
84.441656
16
1
100
6
def new_context( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> Context: return new_context( self.environment, self.name, self.blocks, vars, shared, self.globals, locals )
27,482
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.make_module
( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, )
return TemplateModule(self, ctx)
This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method.
This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method.
1,392
1,405
def make_module( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> "TemplateModule": """This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method. """ ctx = self.new_context(vars, shared, locals) return TemplateModule(self, ctx)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1392-L1405
42
[ 0, 11, 12, 13 ]
28.571429
[]
0
false
84.441656
14
1
100
5
def make_module( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> "TemplateModule": ctx = self.new_context(vars, shared, locals) return TemplateModule(self, ctx)
27,483
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.make_module_async
( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, )
return TemplateModule( self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore )
As template module creation can invoke template code for asynchronous executions this method must be used instead of the normal :meth:`make_module` one. Likewise the module attribute becomes unavailable in async mode.
As template module creation can invoke template code for asynchronous executions this method must be used instead of the normal :meth:`make_module` one. Likewise the module attribute becomes unavailable in async mode.
1,407
1,421
async def make_module_async( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> "TemplateModule": """As template module creation can invoke template code for asynchronous executions this method must be used instead of the normal :meth:`make_module` one. Likewise the module attribute becomes unavailable in async mode. """ ctx = self.new_context(vars, shared, locals) return TemplateModule( self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1407-L1421
42
[ 0, 10, 11, 12, 13, 14 ]
40
[]
0
false
84.441656
15
2
100
4
async def make_module_async( self, vars: t.Optional[t.Dict[str, t.Any]] = None, shared: bool = False, locals: t.Optional[t.Mapping[str, t.Any]] = None, ) -> "TemplateModule": ctx = self.new_context(vars, shared, locals) return TemplateModule( self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore )
27,484
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template._get_default_module
(self, ctx: t.Optional[Context] = None)
return self._module
If a context is passed in, this means that the template was imported. Imported templates have access to the current template's globals by default, but they can only be accessed via the context during runtime. If there are new globals, we need to create a new module because the cached module is already rendered and will not have access to globals from the current context. This new module is not cached because the template can be imported elsewhere, and it should have access to only the current template's globals.
If a context is passed in, this means that the template was imported. Imported templates have access to the current template's globals by default, but they can only be accessed via the context during runtime.
1,424
1,448
def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule": """If a context is passed in, this means that the template was imported. Imported templates have access to the current template's globals by default, but they can only be accessed via the context during runtime. If there are new globals, we need to create a new module because the cached module is already rendered and will not have access to globals from the current context. This new module is not cached because the template can be imported elsewhere, and it should have access to only the current template's globals. """ if self.environment.is_async: raise RuntimeError("Module is not available in async mode.") if ctx is not None: keys = ctx.globals_keys - self.globals.keys() if keys: return self.make_module({k: ctx.parent[k] for k in keys}) if self._module is None: self._module = self.make_module() return self._module
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1424-L1448
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
96
[ 13 ]
4
false
84.441656
25
5
96
10
def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule": if self.environment.is_async: raise RuntimeError("Module is not available in async mode.") if ctx is not None: keys = ctx.globals_keys - self.globals.keys() if keys: return self.make_module({k: ctx.parent[k] for k in keys}) if self._module is None: self._module = self.make_module() return self._module
27,485
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template._get_default_module_async
( self, ctx: t.Optional[Context] = None )
return self._module
1,450
1,462
async def _get_default_module_async( self, ctx: t.Optional[Context] = None ) -> "TemplateModule": if ctx is not None: keys = ctx.globals_keys - self.globals.keys() if keys: return await self.make_module_async({k: ctx.parent[k] for k in keys}) if self._module is None: self._module = await self.make_module_async() return self._module
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1450-L1462
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
84.615385
[]
0
false
84.441656
13
4
100
0
async def _get_default_module_async( self, ctx: t.Optional[Context] = None ) -> "TemplateModule": if ctx is not None: keys = ctx.globals_keys - self.globals.keys() if keys: return await self.make_module_async({k: ctx.parent[k] for k in keys}) if self._module is None: self._module = await self.make_module_async() return self._module
27,486
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.module
(self)
return self._get_default_module()
The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> str(t.module) '23' >>> t.module.foo() == u'42' True This attribute is not available if async mode is enabled.
The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer:
1,465
1,478
def module(self) -> "TemplateModule": """The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> str(t.module) '23' >>> t.module.foo() == u'42' True This attribute is not available if async mode is enabled. """ return self._get_default_module()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1465-L1478
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
84.441656
14
1
100
11
def module(self) -> "TemplateModule": return self._get_default_module()
27,487
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.get_corresponding_lineno
(self, lineno: int)
return 1
Return the source line number of a line number in the generated bytecode as they are not in sync.
Return the source line number of a line number in the generated bytecode as they are not in sync.
1,480
1,487
def get_corresponding_lineno(self, lineno: int) -> int: """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1480-L1487
42
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
84.441656
8
3
100
2
def get_corresponding_lineno(self, lineno: int) -> int: for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1
27,488
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.is_up_to_date
(self)
return self._uptodate()
If this variable is `False` there is a newer version available.
If this variable is `False` there is a newer version available.
1,490
1,494
def is_up_to_date(self) -> bool: """If this variable is `False` there is a newer version available.""" if self._uptodate is None: return True return self._uptodate()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1490-L1494
42
[ 0, 1, 2, 4 ]
80
[ 3 ]
20
false
84.441656
5
2
80
1
def is_up_to_date(self) -> bool: if self._uptodate is None: return True return self._uptodate()
27,489
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.debug_info
(self)
return []
The debug info mapping.
The debug info mapping.
1,497
1,505
def debug_info(self) -> t.List[t.Tuple[int, int]]: """The debug info mapping.""" if self._debug_info: return [ tuple(map(int, x.split("="))) # type: ignore for x in self._debug_info.split("&") ] return []
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1497-L1505
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
84.441656
9
3
100
1
def debug_info(self) -> t.List[t.Tuple[int, int]]: if self._debug_info: return [ tuple(map(int, x.split("="))) # type: ignore for x in self._debug_info.split("&") ] return []
27,490
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
Template.__repr__
(self)
return f"<{type(self).__name__} {name}>"
1,507
1,512
def __repr__(self) -> str: if self.name is None: name = f"memory:{id(self):x}" else: name = repr(self.name) return f"<{type(self).__name__} {name}>"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1507-L1512
42
[ 0 ]
16.666667
[ 1, 2, 4, 5 ]
66.666667
false
84.441656
6
2
33.333333
0
def __repr__(self) -> str: if self.name is None: name = f"memory:{id(self):x}" else: name = repr(self.name) return f"<{type(self).__name__} {name}>"
27,491
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
TemplateModule.__init__
( self, template: Template, context: Context, body_stream: t.Optional[t.Iterable[str]] = None, )
1,521
1,539
def __init__( self, template: Template, context: Context, body_stream: t.Optional[t.Iterable[str]] = None, ) -> None: if body_stream is None: if context.environment.is_async: raise RuntimeError( "Async mode requires a body stream to be passed to" " a template module. Use the async methods of the" " API you are using." ) body_stream = list(template.root_render_func(context)) self._body_stream = body_stream self.__dict__.update(context.get_exported()) self.__name__ = template.name
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1521-L1539
42
[ 0, 6, 7, 13, 14, 15, 16, 17, 18 ]
47.368421
[ 8 ]
5.263158
false
84.441656
19
3
94.736842
0
def __init__( self, template: Template, context: Context, body_stream: t.Optional[t.Iterable[str]] = None, ) -> None: if body_stream is None: if context.environment.is_async: raise RuntimeError( "Async mode requires a body stream to be passed to" " a template module. Use the async methods of the" " API you are using." ) body_stream = list(template.root_render_func(context)) self._body_stream = body_stream self.__dict__.update(context.get_exported()) self.__name__ = template.name
27,492
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
TemplateModule.__html__
(self)
return Markup(concat(self._body_stream))
1,541
1,542
def __html__(self) -> Markup: return Markup(concat(self._body_stream))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1541-L1542
42
[ 0, 1 ]
100
[]
0
true
84.441656
2
1
100
0
def __html__(self) -> Markup: return Markup(concat(self._body_stream))
27,493
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
TemplateModule.__str__
(self)
return concat(self._body_stream)
1,544
1,545
def __str__(self) -> str: return concat(self._body_stream)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1544-L1545
42
[ 0, 1 ]
100
[]
0
true
84.441656
2
1
100
0
def __str__(self) -> str: return concat(self._body_stream)
27,494
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
TemplateModule.__repr__
(self)
return f"<{type(self).__name__} {name}>"
1,547
1,552
def __repr__(self) -> str: if self.__name__ is None: name = f"memory:{id(self):x}" else: name = repr(self.__name__) return f"<{type(self).__name__} {name}>"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1547-L1552
42
[ 0 ]
16.666667
[ 1, 2, 4, 5 ]
66.666667
false
84.441656
6
2
33.333333
0
def __repr__(self) -> str: if self.__name__ is None: name = f"memory:{id(self):x}" else: name = repr(self.__name__) return f"<{type(self).__name__} {name}>"
27,495
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
TemplateExpression.__init__
(self, template: Template, undefined_to_none: bool)
1,561
1,563
def __init__(self, template: Template, undefined_to_none: bool) -> None: self._template = template self._undefined_to_none = undefined_to_none
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1561-L1563
42
[ 0, 1, 2 ]
100
[]
0
true
84.441656
3
1
100
0
def __init__(self, template: Template, undefined_to_none: bool) -> None: self._template = template self._undefined_to_none = undefined_to_none
27,496
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/environment.py
TemplateExpression.__call__
(self, *args: t.Any, **kwargs: t.Any)
return rv
1,565
1,571
def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]: context = self._template.new_context(dict(*args, **kwargs)) consume(self._template.root_render_func(context)) rv = context.vars["result"] if self._undefined_to_none and isinstance(rv, Undefined): rv = None return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/environment.py#L1565-L1571
42
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
84.441656
7
3
100
0
def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]: context = self._template.new_context(dict(*args, **kwargs)) consume(self._template.root_render_func(context)) rv = context.vars["result"] if self._undefined_to_none and isinstance(rv, Undefined): rv = None return rv
27,497
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/debug.py
rewrite_traceback_stack
(source: t.Optional[str] = None)
return exc_value.with_traceback(tb_next)
Rewrite the current exception to replace any tracebacks from within compiled template code with tracebacks that look like they came from the template source. This must be called within an ``except`` block. :param source: For ``TemplateSyntaxError``, the original source if known. :return: The original exception with the rewritten traceback.
Rewrite the current exception to replace any tracebacks from within compiled template code with tracebacks that look like they came from the template source.
14
73
def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException: """Rewrite the current exception to replace any tracebacks from within compiled template code with tracebacks that look like they came from the template source. This must be called within an ``except`` block. :param source: For ``TemplateSyntaxError``, the original source if known. :return: The original exception with the rewritten traceback. """ _, exc_value, tb = sys.exc_info() exc_value = t.cast(BaseException, exc_value) tb = t.cast(TracebackType, tb) if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated: exc_value.translated = True exc_value.source = source # Remove the old traceback, otherwise the frames from the # compiler still show up. exc_value.with_traceback(None) # Outside of runtime, so the frame isn't executing template # code, but it still needs to point at the template. tb = fake_traceback( exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno ) else: # Skip the frame for the render function. tb = tb.tb_next stack = [] # Build the stack of traceback object, replacing any in template # code with the source file and line information. while tb is not None: # Skip frames decorated with @internalcode. These are internal # calls that aren't useful in template debugging output. if tb.tb_frame.f_code in internal_code: tb = tb.tb_next continue template = tb.tb_frame.f_globals.get("__jinja_template__") if template is not None: lineno = template.get_corresponding_lineno(tb.tb_lineno) fake_tb = fake_traceback(exc_value, tb, template.filename, lineno) stack.append(fake_tb) else: stack.append(tb) tb = tb.tb_next tb_next = None # Assign tb_next in reverse to avoid circular references. for tb in reversed(stack): tb.tb_next = tb_next tb_next = tb return exc_value.with_traceback(tb_next)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/debug.py#L14-L73
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, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 ]
100
[]
0
true
90.265487
60
8
100
9
def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException: _, exc_value, tb = sys.exc_info() exc_value = t.cast(BaseException, exc_value) tb = t.cast(TracebackType, tb) if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated: exc_value.translated = True exc_value.source = source # Remove the old traceback, otherwise the frames from the # compiler still show up. exc_value.with_traceback(None) # Outside of runtime, so the frame isn't executing template # code, but it still needs to point at the template. tb = fake_traceback( exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno ) else: # Skip the frame for the render function. tb = tb.tb_next stack = [] # Build the stack of traceback object, replacing any in template # code with the source file and line information. while tb is not None: # Skip frames decorated with @internalcode. These are internal # calls that aren't useful in template debugging output. if tb.tb_frame.f_code in internal_code: tb = tb.tb_next continue template = tb.tb_frame.f_globals.get("__jinja_template__") if template is not None: lineno = template.get_corresponding_lineno(tb.tb_lineno) fake_tb = fake_traceback(exc_value, tb, template.filename, lineno) stack.append(fake_tb) else: stack.append(tb) tb = tb.tb_next tb_next = None # Assign tb_next in reverse to avoid circular references. for tb in reversed(stack): tb.tb_next = tb_next tb_next = tb return exc_value.with_traceback(tb_next)
27,498
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/debug.py
fake_traceback
( # type: ignore exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int )
Produce a new traceback object that looks like it came from the template source instead of the compiled code. The filename, line number, and location name will point to the template, and the local variables will be the current template context. :param exc_value: The original exception to be re-raised to create the new traceback. :param tb: The original traceback to get the local variables and code info from. :param filename: The template filename. :param lineno: The line number in the template source.
Produce a new traceback object that looks like it came from the template source instead of the compiled code. The filename, line number, and location name will point to the template, and the local variables will be the current template context.
76
147
def fake_traceback( # type: ignore exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int ) -> TracebackType: """Produce a new traceback object that looks like it came from the template source instead of the compiled code. The filename, line number, and location name will point to the template, and the local variables will be the current template context. :param exc_value: The original exception to be re-raised to create the new traceback. :param tb: The original traceback to get the local variables and code info from. :param filename: The template filename. :param lineno: The line number in the template source. """ if tb is not None: # Replace the real locals with the context that would be # available at that point in the template. locals = get_template_locals(tb.tb_frame.f_locals) locals.pop("__jinja_exception__", None) else: locals = {} globals = { "__name__": filename, "__file__": filename, "__jinja_exception__": exc_value, } # Raise an exception at the correct line number. code: CodeType = compile( "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec" ) # Build a new code object that points to the template file and # replaces the location with a block name. location = "template" if tb is not None: function = tb.tb_frame.f_code.co_name if function == "root": location = "top-level template code" elif function.startswith("block_"): location = f"block {function[6:]!r}" if sys.version_info >= (3, 8): code = code.replace(co_name=location) else: code = CodeType( code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, code.co_varnames, code.co_filename, location, code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars, ) # Execute the new code, which is guaranteed to raise, and return # the new traceback without this frame. try: exec(code, globals, locals) except BaseException: return sys.exc_info()[2].tb_next
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/debug.py#L76-L147
42
[ 0, 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, 44, 45, 46, 47, 67, 68, 69, 70, 71 ]
54.166667
[ 43, 48 ]
2.777778
false
90.265487
72
7
97.222222
11
def fake_traceback( # type: ignore exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int ) -> TracebackType: if tb is not None: # Replace the real locals with the context that would be # available at that point in the template. locals = get_template_locals(tb.tb_frame.f_locals) locals.pop("__jinja_exception__", None) else: locals = {} globals = { "__name__": filename, "__file__": filename, "__jinja_exception__": exc_value, } # Raise an exception at the correct line number. code: CodeType = compile( "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec" ) # Build a new code object that points to the template file and # replaces the location with a block name. location = "template" if tb is not None: function = tb.tb_frame.f_code.co_name if function == "root": location = "top-level template code" elif function.startswith("block_"): location = f"block {function[6:]!r}" if sys.version_info >= (3, 8): code = code.replace(co_name=location) else: code = CodeType( code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, code.co_varnames, code.co_filename, location, code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars, ) # Execute the new code, which is guaranteed to raise, and return # the new traceback without this frame. try: exec(code, globals, locals) except BaseException: return sys.exc_info()[2].tb_next
27,499
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/debug.py
get_template_locals
(real_locals: t.Mapping[str, t.Any])
return data
Based on the runtime locals, get the context that would be available at that point in the template.
Based on the runtime locals, get the context that would be available at that point in the template.
150
191
def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]: """Based on the runtime locals, get the context that would be available at that point in the template. """ # Start with the current template context. ctx: "t.Optional[Context]" = real_locals.get("context") if ctx is not None: data: t.Dict[str, t.Any] = ctx.get_all().copy() else: data = {} # Might be in a derived context that only sets local variables # rather than pushing a context. Local variables follow the scheme # l_depth_name. Find the highest-depth local that has a value for # each name. local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {} for name, value in real_locals.items(): if not name.startswith("l_") or value is missing: # Not a template variable, or no longer relevant. continue try: _, depth_str, name = name.split("_", 2) depth = int(depth_str) except ValueError: continue cur_depth = local_overrides.get(name, (-1,))[0] if cur_depth < depth: local_overrides[name] = (depth, value) # Modify the context with any derived context. for name, (_, value) in local_overrides.items(): if value is missing: data.pop(name, None) else: data[name] = value return data
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/debug.py#L150-L191
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, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41 ]
92.857143
[ 26, 27, 37 ]
7.142857
false
90.265487
42
9
92.857143
2
def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]: # Start with the current template context. ctx: "t.Optional[Context]" = real_locals.get("context") if ctx is not None: data: t.Dict[str, t.Any] = ctx.get_all().copy() else: data = {} # Might be in a derived context that only sets local variables # rather than pushing a context. Local variables follow the scheme # l_depth_name. Find the highest-depth local that has a value for # each name. local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {} for name, value in real_locals.items(): if not name.startswith("l_") or value is missing: # Not a template variable, or no longer relevant. continue try: _, depth_str, name = name.split("_", 2) depth = int(depth_str) except ValueError: continue cur_depth = local_overrides.get(name, (-1,))[0] if cur_depth < depth: local_overrides[name] = (depth, value) # Modify the context with any derived context. for name, (_, value) in local_overrides.items(): if value is missing: data.pop(name, None) else: data[name] = value return data
27,500
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/optimizer.py
optimize
(node: nodes.Node, environment: "Environment")
return t.cast(nodes.Node, optimizer.visit(node))
The context hint can be used to perform an static optimization based on the context given.
The context hint can be used to perform an static optimization based on the context given.
19
23
def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node: """The context hint can be used to perform an static optimization based on the context given.""" optimizer = Optimizer(environment) return t.cast(nodes.Node, optimizer.visit(node))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/optimizer.py#L19-L23
42
[ 0, 1, 2 ]
60
[ 3, 4 ]
40
false
82.608696
5
1
60
2
def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node: optimizer = Optimizer(environment) return t.cast(nodes.Node, optimizer.visit(node))
27,501
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/optimizer.py
Optimizer.__init__
(self, environment: "t.Optional[Environment]")
27
28
def __init__(self, environment: "t.Optional[Environment]") -> None: self.environment = environment
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/optimizer.py#L27-L28
42
[ 0, 1 ]
100
[]
0
true
82.608696
2
1
100
0
def __init__(self, environment: "t.Optional[Environment]") -> None: self.environment = environment
27,502
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/optimizer.py
Optimizer.generic_visit
( self, node: nodes.Node, *args: t.Any, **kwargs: t.Any )
return node
30
47
def generic_visit( self, node: nodes.Node, *args: t.Any, **kwargs: t.Any ) -> nodes.Node: node = super().generic_visit(node, *args, **kwargs) # Do constant folding. Some other nodes besides Expr have # as_const, but folding them causes errors later on. if isinstance(node, nodes.Expr): try: return nodes.Const.from_untrusted( node.as_const(args[0] if args else None), lineno=node.lineno, environment=self.environment, ) except nodes.Impossible: pass return node
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/optimizer.py#L30-L47
42
[ 0, 3, 4, 5, 6, 7, 8, 9, 14, 15, 16, 17 ]
66.666667
[]
0
false
82.608696
18
3
100
0
def generic_visit( self, node: nodes.Node, *args: t.Any, **kwargs: t.Any ) -> nodes.Node: node = super().generic_visit(node, *args, **kwargs) # Do constant folding. Some other nodes besides Expr have # as_const, but folding them causes errors later on. if isinstance(node, nodes.Expr): try: return nodes.Const.from_untrusted( node.as_const(args[0] if args else None), lineno=node.lineno, environment=self.environment, ) except nodes.Impossible: pass return node
27,503
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
ignore_case
(value: V)
return value
For use as a postprocessor for :func:`make_attrgetter`. Converts strings to lowercase and returns other types as-is.
For use as a postprocessor for :func:`make_attrgetter`. Converts strings to lowercase and returns other types as-is.
46
52
def ignore_case(value: V) -> V: """For use as a postprocessor for :func:`make_attrgetter`. Converts strings to lowercase and returns other types as-is.""" if isinstance(value, str): return t.cast(V, value.lower()) return value
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L46-L52
42
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
88.768606
7
2
100
2
def ignore_case(value: V) -> V: if isinstance(value, str): return t.cast(V, value.lower()) return value
27,504
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
make_attrgetter
( environment: "Environment", attribute: t.Optional[t.Union[str, int]], postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None, default: t.Optional[t.Any] = None, )
return attrgetter
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers.
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers.
55
80
def make_attrgetter( environment: "Environment", attribute: t.Optional[t.Union[str, int]], postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None, default: t.Optional[t.Any] = None, ) -> t.Callable[[t.Any], t.Any]: """Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers. """ parts = _prepare_attribute_parts(attribute) def attrgetter(item: t.Any) -> t.Any: for part in parts: item = environment.getitem(item, part) if default is not None and isinstance(item, Undefined): item = default if postprocess is not None: item = postprocess(item) return item return attrgetter
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L55-L80
42
[ 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
65.384615
[]
0
false
88.768606
26
6
100
4
def make_attrgetter( environment: "Environment", attribute: t.Optional[t.Union[str, int]], postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None, default: t.Optional[t.Any] = None, ) -> t.Callable[[t.Any], t.Any]: parts = _prepare_attribute_parts(attribute) def attrgetter(item: t.Any) -> t.Any: for part in parts: item = environment.getitem(item, part) if default is not None and isinstance(item, Undefined): item = default if postprocess is not None: item = postprocess(item) return item return attrgetter
27,505
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
make_multi_attrgetter
( environment: "Environment", attribute: t.Optional[t.Union[str, int]], postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None, )
return attrgetter
Returns a callable that looks up the given comma separated attributes from a passed object with the rules of the environment. Dots are allowed to access attributes of each attribute. Integer parts in paths are looked up as integers. The value returned by the returned callable is a list of extracted attribute values. Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.
Returns a callable that looks up the given comma separated attributes from a passed object with the rules of the environment. Dots are allowed to access attributes of each attribute. Integer parts in paths are looked up as integers.
83
121
def make_multi_attrgetter( environment: "Environment", attribute: t.Optional[t.Union[str, int]], postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None, ) -> t.Callable[[t.Any], t.List[t.Any]]: """Returns a callable that looks up the given comma separated attributes from a passed object with the rules of the environment. Dots are allowed to access attributes of each attribute. Integer parts in paths are looked up as integers. The value returned by the returned callable is a list of extracted attribute values. Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc. """ if isinstance(attribute, str): split: t.Sequence[t.Union[str, int, None]] = attribute.split(",") else: split = [attribute] parts = [_prepare_attribute_parts(item) for item in split] def attrgetter(item: t.Any) -> t.List[t.Any]: items = [None] * len(parts) for i, attribute_part in enumerate(parts): item_i = item for part in attribute_part: item_i = environment.getitem(item_i, part) if postprocess is not None: item_i = postprocess(item_i) items[i] = item_i return items return attrgetter
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L83-L121
42
[ 0, 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 ]
66.666667
[]
0
false
88.768606
39
7
100
9
def make_multi_attrgetter( environment: "Environment", attribute: t.Optional[t.Union[str, int]], postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None, ) -> t.Callable[[t.Any], t.List[t.Any]]: if isinstance(attribute, str): split: t.Sequence[t.Union[str, int, None]] = attribute.split(",") else: split = [attribute] parts = [_prepare_attribute_parts(item) for item in split] def attrgetter(item: t.Any) -> t.List[t.Any]: items = [None] * len(parts) for i, attribute_part in enumerate(parts): item_i = item for part in attribute_part: item_i = environment.getitem(item_i, part) if postprocess is not None: item_i = postprocess(item_i) items[i] = item_i return items return attrgetter
27,506
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
_prepare_attribute_parts
( attr: t.Optional[t.Union[str, int]] )
return [attr]
124
133
def _prepare_attribute_parts( attr: t.Optional[t.Union[str, int]] ) -> t.List[t.Union[str, int]]: if attr is None: return [] if isinstance(attr, str): return [int(x) if x.isdigit() else x for x in attr.split(".")] return [attr]
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L124-L133
42
[ 0, 3, 4, 5, 6, 7, 8, 9 ]
80
[]
0
false
88.768606
10
4
100
0
def _prepare_attribute_parts( attr: t.Optional[t.Union[str, int]] ) -> t.List[t.Union[str, int]]: if attr is None: return [] if isinstance(attr, str): return [int(x) if x.isdigit() else x for x in attr.split(".")] return [attr]
27,507
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_forceescape
(value: "t.Union[str, HasHTML]")
return escape(str(value))
Enforce HTML escaping. This will probably double escape variables.
Enforce HTML escaping. This will probably double escape variables.
136
141
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup: """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, "__html__"): value = t.cast("HasHTML", value).__html__() return escape(str(value))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L136-L141
42
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
88.768606
6
2
100
1
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup: if hasattr(value, "__html__"): value = t.cast("HasHTML", value).__html__() return escape(str(value))
27,508
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_urlencode
( value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]] )
return "&".join( f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items )
Quote data for use in a URL path or query using UTF-8. Basic wrapper around :func:`urllib.parse.quote` when given a string, or :func:`urllib.parse.urlencode` for a dict or iterable. :param value: Data to quote. A string will be quoted directly. A dict or iterable of ``(key, value)`` pairs will be joined as a query string. When given a string, "/" is not quoted. HTTP servers treat "/" and "%2F" equivalently in paths. If you need quoted slashes, use the ``|replace("/", "%2F")`` filter. .. versionadded:: 2.7
Quote data for use in a URL path or query using UTF-8.
144
172
def do_urlencode( value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]] ) -> str: """Quote data for use in a URL path or query using UTF-8. Basic wrapper around :func:`urllib.parse.quote` when given a string, or :func:`urllib.parse.urlencode` for a dict or iterable. :param value: Data to quote. A string will be quoted directly. A dict or iterable of ``(key, value)`` pairs will be joined as a query string. When given a string, "/" is not quoted. HTTP servers treat "/" and "%2F" equivalently in paths. If you need quoted slashes, use the ``|replace("/", "%2F")`` filter. .. versionadded:: 2.7 """ if isinstance(value, str) or not isinstance(value, abc.Iterable): return url_quote(value) if isinstance(value, dict): items: t.Iterable[t.Tuple[str, t.Any]] = value.items() else: items = value # type: ignore return "&".join( f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L144-L172
42
[ 0, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ]
44.827586
[]
0
false
88.768606
29
4
100
14
def do_urlencode( value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]] ) -> str: if isinstance(value, str) or not isinstance(value, abc.Iterable): return url_quote(value) if isinstance(value, dict): items: t.Iterable[t.Tuple[str, t.Any]] = value.items() else: items = value # type: ignore return "&".join( f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items )
27,509
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_replace
( eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None )
return s.replace(soft_str(old), soft_str(new), count)
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcecode:: jinja {{ "Hello World"|replace("Hello", "Goodbye") }} -> Goodbye World {{ "aaaaargh"|replace("a", "d'oh, ", 2) }} -> d'oh, d'oh, aaargh
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced:
176
208
def do_replace( eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None ) -> str: """Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcecode:: jinja {{ "Hello World"|replace("Hello", "Goodbye") }} -> Goodbye World {{ "aaaaargh"|replace("a", "d'oh, ", 2) }} -> d'oh, d'oh, aaargh """ if count is None: count = -1 if not eval_ctx.autoescape: return str(s).replace(str(old), str(new), count) if ( hasattr(old, "__html__") or hasattr(new, "__html__") and not hasattr(s, "__html__") ): s = escape(s) else: s = soft_str(s) return s.replace(soft_str(old), soft_str(new), count)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L176-L208
42
[ 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32 ]
51.515152
[ 28 ]
3.030303
false
88.768606
33
6
96.969697
13
def do_replace( eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None ) -> str: if count is None: count = -1 if not eval_ctx.autoescape: return str(s).replace(str(old), str(new), count) if ( hasattr(old, "__html__") or hasattr(new, "__html__") and not hasattr(s, "__html__") ): s = escape(s) else: s = soft_str(s) return s.replace(soft_str(old), soft_str(new), count)
27,510
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_upper
(s: str)
return soft_str(s).upper()
Convert a value to uppercase.
Convert a value to uppercase.
211
213
def do_upper(s: str) -> str: """Convert a value to uppercase.""" return soft_str(s).upper()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L211-L213
42
[ 0, 1, 2 ]
100
[]
0
true
88.768606
3
1
100
1
def do_upper(s: str) -> str: return soft_str(s).upper()
27,511
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_lower
(s: str)
return soft_str(s).lower()
Convert a value to lowercase.
Convert a value to lowercase.
216
218
def do_lower(s: str) -> str: """Convert a value to lowercase.""" return soft_str(s).lower()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L216-L218
42
[ 0, 1, 2 ]
100
[]
0
true
88.768606
3
1
100
1
def do_lower(s: str) -> str: return soft_str(s).lower()
27,512
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_items
(value: t.Union[t.Mapping[K, V], Undefined])
Return an iterator over the ``(key, value)`` items of a mapping. ``x|items`` is the same as ``x.items()``, except if ``x`` is undefined an empty iterator is returned. This filter is useful if you expect the template to be rendered with an implementation of Jinja in another programming language that does not have a ``.items()`` method on its mapping type. .. code-block:: html+jinja <dl> {% for key, value in my_dict|items %} <dt>{{ key }} <dd>{{ value }} {% endfor %} </dl> .. versionadded:: 3.1
Return an iterator over the ``(key, value)`` items of a mapping.
221
248
def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]: """Return an iterator over the ``(key, value)`` items of a mapping. ``x|items`` is the same as ``x.items()``, except if ``x`` is undefined an empty iterator is returned. This filter is useful if you expect the template to be rendered with an implementation of Jinja in another programming language that does not have a ``.items()`` method on its mapping type. .. code-block:: html+jinja <dl> {% for key, value in my_dict|items %} <dt>{{ key }} <dd>{{ value }} {% endfor %} </dl> .. versionadded:: 3.1 """ if isinstance(value, Undefined): return if not isinstance(value, abc.Mapping): raise TypeError("Can only get item pairs from a mapping.") yield from value.items()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L221-L248
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, 26, 27 ]
96.428571
[ 25 ]
3.571429
false
88.768606
28
3
96.428571
19
def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]: if isinstance(value, Undefined): return if not isinstance(value, abc.Mapping): raise TypeError("Can only get item pairs from a mapping.") yield from value.items()
27,513
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_xmlattr
( eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True )
return rv
Create an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped: .. sourcecode:: html+jinja <ul{{ {'class': 'my_list', 'missing': none, 'id': 'list-%d'|format(variable)}|xmlattr }}> ... </ul> Results in something like this: .. sourcecode:: html <ul class="my_list" id="list-42"> ... </ul> As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false.
Create an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped:
252
289
def do_xmlattr( eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True ) -> str: """Create an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped: .. sourcecode:: html+jinja <ul{{ {'class': 'my_list', 'missing': none, 'id': 'list-%d'|format(variable)}|xmlattr }}> ... </ul> Results in something like this: .. sourcecode:: html <ul class="my_list" id="list-42"> ... </ul> As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false. """ rv = " ".join( f'{escape(key)}="{escape(value)}"' for key, value in d.items() if value is not None and not isinstance(value, Undefined) ) if autospace and rv: rv = " " + rv if eval_ctx.autoescape: rv = Markup(rv) return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L252-L289
42
[ 0, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37 ]
39.473684
[]
0
false
88.768606
38
5
100
21
def do_xmlattr( eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True ) -> str: rv = " ".join( f'{escape(key)}="{escape(value)}"' for key, value in d.items() if value is not None and not isinstance(value, Undefined) ) if autospace and rv: rv = " " + rv if eval_ctx.autoescape: rv = Markup(rv) return rv
27,514
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_capitalize
(s: str)
return soft_str(s).capitalize()
Capitalize a value. The first character will be uppercase, all others lowercase.
Capitalize a value. The first character will be uppercase, all others lowercase.
292
296
def do_capitalize(s: str) -> str: """Capitalize a value. The first character will be uppercase, all others lowercase. """ return soft_str(s).capitalize()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L292-L296
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
88.768606
5
1
100
2
def do_capitalize(s: str) -> str: return soft_str(s).capitalize()
27,515
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_title
(s: str)
return "".join( [ item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_str(s)) if item ] )
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
302
312
def do_title(s: str) -> str: """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return "".join( [ item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_str(s)) if item ] )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L302-L312
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
88.768606
11
2
100
2
def do_title(s: str) -> str: return "".join( [ item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_str(s)) if item ] )
27,516
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_dictsort
( value: t.Mapping[K, V], case_sensitive: bool = False, by: 'te.Literal["key", "value"]' = "key", reverse: bool = False, )
return sorted(value.items(), key=sort_func, reverse=reverse)
Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first. .. sourcecode:: jinja {% for key, value in mydict|dictsort %} sort the dict by key, case insensitive {% for key, value in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for key, value in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for key, value in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive
Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first.
315
353
def do_dictsort( value: t.Mapping[K, V], case_sensitive: bool = False, by: 'te.Literal["key", "value"]' = "key", reverse: bool = False, ) -> t.List[t.Tuple[K, V]]: """Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first. .. sourcecode:: jinja {% for key, value in mydict|dictsort %} sort the dict by key, case insensitive {% for key, value in mydict|dictsort(reverse=true) %} sort the dict by key, case insensitive, reverse order {% for key, value in mydict|dictsort(true) %} sort the dict by key, case sensitive {% for key, value in mydict|dictsort(false, 'value') %} sort the dict by value, case insensitive """ if by == "key": pos = 0 elif by == "value": pos = 1 else: raise FilterArgumentError('You can only sort by either "key" or "value"') def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any: value = item[pos] if not case_sensitive: value = ignore_case(value) return value return sorted(value.items(), key=sort_func, reverse=reverse)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L315-L353
42
[ 0, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38 ]
43.589744
[ 28 ]
2.564103
false
88.768606
39
5
97.435897
16
def do_dictsort( value: t.Mapping[K, V], case_sensitive: bool = False, by: 'te.Literal["key", "value"]' = "key", reverse: bool = False, ) -> t.List[t.Tuple[K, V]]: if by == "key": pos = 0 elif by == "value": pos = 1 else: raise FilterArgumentError('You can only sort by either "key" or "value"') def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any: value = item[pos] if not case_sensitive: value = ignore_case(value) return value return sorted(value.items(), key=sort_func, reverse=reverse)
27,517
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_sort
( environment: "Environment", value: "t.Iterable[V]", reverse: bool = False, case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, )
return sorted(value, key=key_func, reverse=reverse)
Sort an iterable using Python's :func:`sorted`. .. sourcecode:: jinja {% for city in cities|sort %} ... {% endfor %} :param reverse: Sort descending instead of ascending. :param case_sensitive: When sorting strings, sort upper and lower case separately. :param attribute: When sorting objects or dicts, an attribute or key to sort by. Can use dot notation like ``"address.city"``. Can be a list of attributes like ``"age,name"``. The sort is stable, it does not change the relative order of elements that compare equal. This makes it is possible to chain sorts on different attributes and ordering. .. sourcecode:: jinja {% for user in users|sort(attribute="name") |sort(reverse=true, attribute="age") %} ... {% endfor %} As a shortcut to chaining when the direction is the same for all attributes, pass a comma separate list of attributes. .. sourcecode:: jinja {% for user in users|sort(attribute="age,name") %} ... {% endfor %} .. versionchanged:: 2.11.0 The ``attribute`` parameter can be a comma separated list of attributes, e.g. ``"age,name"``. .. versionchanged:: 2.6 The ``attribute`` parameter was added.
Sort an iterable using Python's :func:`sorted`.
357
409
def do_sort( environment: "Environment", value: "t.Iterable[V]", reverse: bool = False, case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.List[V]": """Sort an iterable using Python's :func:`sorted`. .. sourcecode:: jinja {% for city in cities|sort %} ... {% endfor %} :param reverse: Sort descending instead of ascending. :param case_sensitive: When sorting strings, sort upper and lower case separately. :param attribute: When sorting objects or dicts, an attribute or key to sort by. Can use dot notation like ``"address.city"``. Can be a list of attributes like ``"age,name"``. The sort is stable, it does not change the relative order of elements that compare equal. This makes it is possible to chain sorts on different attributes and ordering. .. sourcecode:: jinja {% for user in users|sort(attribute="name") |sort(reverse=true, attribute="age") %} ... {% endfor %} As a shortcut to chaining when the direction is the same for all attributes, pass a comma separate list of attributes. .. sourcecode:: jinja {% for user in users|sort(attribute="age,name") %} ... {% endfor %} .. versionchanged:: 2.11.0 The ``attribute`` parameter can be a comma separated list of attributes, e.g. ``"age,name"``. .. versionchanged:: 2.6 The ``attribute`` parameter was added. """ key_func = make_multi_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return sorted(value, key=key_func, reverse=reverse)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L357-L409
42
[ 0, 48, 49, 50, 51, 52 ]
11.320755
[]
0
false
88.768606
53
1
100
41
def do_sort( environment: "Environment", value: "t.Iterable[V]", reverse: bool = False, case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.List[V]": key_func = make_multi_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return sorted(value, key=key_func, reverse=reverse)
27,518
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_unique
( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, )
Returns a list of unique items from the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute.
Returns a list of unique items from the given iterable.
413
442
def do_unique( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.Iterator[V]": """Returns a list of unique items from the given iterable. .. sourcecode:: jinja {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }} -> ['foo', 'bar', 'foobar'] The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter. :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Filter objects with unique values for this attribute. """ getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L413-L442
42
[ 0, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]
43.333333
[]
0
false
88.768606
30
3
100
12
def do_unique( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.Iterator[V]": getter = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) seen = set() for item in value: key = getter(item) if key not in seen: seen.add(key) yield item
27,519
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
_min_or_max
( environment: "Environment", value: "t.Iterable[V]", func: "t.Callable[..., V]", case_sensitive: bool, attribute: t.Optional[t.Union[str, int]], )
return func(chain([first], it), key=key_func)
445
462
def _min_or_max( environment: "Environment", value: "t.Iterable[V]", func: "t.Callable[..., V]", case_sensitive: bool, attribute: t.Optional[t.Union[str, int]], ) -> "t.Union[V, Undefined]": it = iter(value) try: first = next(it) except StopIteration: return environment.undefined("No aggregated item, sequence was empty.") key_func = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return func(chain([first], it), key=key_func)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L445-L462
42
[ 0, 7, 8, 9, 10, 11, 12, 13, 14, 17 ]
55.555556
[]
0
false
88.768606
18
2
100
0
def _min_or_max( environment: "Environment", value: "t.Iterable[V]", func: "t.Callable[..., V]", case_sensitive: bool, attribute: t.Optional[t.Union[str, int]], ) -> "t.Union[V, Undefined]": it = iter(value) try: first = next(it) except StopIteration: return environment.undefined("No aggregated item, sequence was empty.") key_func = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None ) return func(chain([first], it), key=key_func)
27,520
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_min
( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, )
return _min_or_max(environment, value, min, case_sensitive, attribute)
Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the min value of this attribute.
Return the smallest item from the sequence.
466
482
def do_min( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.Union[V, Undefined]": """Return the smallest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|min }} -> 1 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the min value of this attribute. """ return _min_or_max(environment, value, min, case_sensitive, attribute)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L466-L482
42
[ 0, 15, 16 ]
17.647059
[]
0
false
88.768606
17
1
100
9
def do_min( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.Union[V, Undefined]": return _min_or_max(environment, value, min, case_sensitive, attribute)
27,521
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_max
( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, )
return _min_or_max(environment, value, max, case_sensitive, attribute)
Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute.
Return the largest item from the sequence.
486
502
def do_max( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.Union[V, Undefined]": """Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max value of this attribute. """ return _min_or_max(environment, value, max, case_sensitive, attribute)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L486-L502
42
[ 0, 15, 16 ]
17.647059
[]
0
false
88.768606
17
1
100
9
def do_max( environment: "Environment", value: "t.Iterable[V]", case_sensitive: bool = False, attribute: t.Optional[t.Union[str, int]] = None, ) -> "t.Union[V, Undefined]": return _min_or_max(environment, value, max, case_sensitive, attribute)
27,522
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_default
( value: V, default_value: V = "", # type: ignore boolean: bool = False, )
return value
If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if the variable was defined, otherwise ``'my_variable is not defined'``. If you want to use default with variables that evaluate to false you have to set the second parameter to `true`: .. sourcecode:: jinja {{ ''|default('the string was empty', true) }} .. versionchanged:: 2.11 It's now possible to configure the :class:`~jinja2.Environment` with :class:`~jinja2.ChainableUndefined` to make the `default` filter work on nested elements and attributes that may contain undefined values in the chain without getting an :exc:`~jinja2.UndefinedError`.
If the value is undefined it will return the passed default value, otherwise the value of the variable:
505
535
def do_default( value: V, default_value: V = "", # type: ignore boolean: bool = False, ) -> V: """If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if the variable was defined, otherwise ``'my_variable is not defined'``. If you want to use default with variables that evaluate to false you have to set the second parameter to `true`: .. sourcecode:: jinja {{ ''|default('the string was empty', true) }} .. versionchanged:: 2.11 It's now possible to configure the :class:`~jinja2.Environment` with :class:`~jinja2.ChainableUndefined` to make the `default` filter work on nested elements and attributes that may contain undefined values in the chain without getting an :exc:`~jinja2.UndefinedError`. """ if isinstance(value, Undefined) or (boolean and not value): return default_value return value
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L505-L535
42
[ 0, 26, 27, 28, 29, 30 ]
19.354839
[]
0
false
88.768606
31
4
100
21
def do_default( value: V, default_value: V = "", # type: ignore boolean: bool = False, ) -> V: if isinstance(value, Undefined) or (boolean and not value): return default_value return value
27,523
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_join
( eval_ctx: "EvalContext", value: t.Iterable, d: str = "", attribute: t.Optional[t.Union[str, int]] = None, )
return soft_str(d).join(map(soft_str, value))
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added.
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter:
539
593
def sync_do_join( eval_ctx: "EvalContext", value: t.Iterable, d: str = "", attribute: t.Optional[t.Union[str, int]] = None, ) -> str: """Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} -> 123 It is also possible to join certain attributes of an object: .. sourcecode:: jinja {{ users|join(', ', attribute='username') }} .. versionadded:: 2.6 The `attribute` parameter was added. """ if attribute is not None: value = map(make_attrgetter(eval_ctx.environment, attribute), value) # no automatic escaping? joining is a lot easier then if not eval_ctx.autoescape: return str(d).join(map(str, value)) # if the delimiter doesn't have an html representation we check # if any of the items has. If yes we do a coercion to Markup if not hasattr(d, "__html__"): value = list(value) do_escape = False for idx, item in enumerate(value): if hasattr(item, "__html__"): do_escape = True else: value[idx] = str(item) if do_escape: d = escape(d) else: d = str(d) return d.join(value) # no html involved, to normal joining return soft_str(d).join(map(soft_str, value))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L539-L593
42
[ 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53 ]
50.909091
[ 49, 54 ]
3.636364
false
88.768606
55
7
96.363636
20
def sync_do_join( eval_ctx: "EvalContext", value: t.Iterable, d: str = "", attribute: t.Optional[t.Union[str, int]] = None, ) -> str: if attribute is not None: value = map(make_attrgetter(eval_ctx.environment, attribute), value) # no automatic escaping? joining is a lot easier then if not eval_ctx.autoescape: return str(d).join(map(str, value)) # if the delimiter doesn't have an html representation we check # if any of the items has. If yes we do a coercion to Markup if not hasattr(d, "__html__"): value = list(value) do_escape = False for idx, item in enumerate(value): if hasattr(item, "__html__"): do_escape = True else: value[idx] = str(item) if do_escape: d = escape(d) else: d = str(d) return d.join(value) # no html involved, to normal joining return soft_str(d).join(map(soft_str, value))
27,524
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_join
( eval_ctx: "EvalContext", value: t.Union[t.AsyncIterable, t.Iterable], d: str = "", attribute: t.Optional[t.Union[str, int]] = None, )
return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
597
603
async def do_join( eval_ctx: "EvalContext", value: t.Union[t.AsyncIterable, t.Iterable], d: str = "", attribute: t.Optional[t.Union[str, int]] = None, ) -> str: return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L597-L603
42
[ 0, 6 ]
28.571429
[]
0
false
88.768606
7
1
100
0
async def do_join( eval_ctx: "EvalContext", value: t.Union[t.AsyncIterable, t.Iterable], d: str = "", attribute: t.Optional[t.Union[str, int]] = None, ) -> str: return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
27,525
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_center
(value: str, width: int = 80)
return soft_str(value).center(width)
Centers the value in a field of a given width.
Centers the value in a field of a given width.
606
608
def do_center(value: str, width: int = 80) -> str: """Centers the value in a field of a given width.""" return soft_str(value).center(width)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L606-L608
42
[ 0, 1, 2 ]
100
[]
0
true
88.768606
3
1
100
1
def do_center(value: str, width: int = 80) -> str: return soft_str(value).center(width)
27,526
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_first
( environment: "Environment", seq: "t.Iterable[V]" )
Return the first item of a sequence.
Return the first item of a sequence.
612
619
def sync_do_first( environment: "Environment", seq: "t.Iterable[V]" ) -> "t.Union[V, Undefined]": """Return the first item of a sequence.""" try: return next(iter(seq)) except StopIteration: return environment.undefined("No first item, sequence was empty.")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L612-L619
42
[ 0, 3, 4, 5 ]
50
[ 6, 7 ]
25
false
88.768606
8
2
75
1
def sync_do_first( environment: "Environment", seq: "t.Iterable[V]" ) -> "t.Union[V, Undefined]": try: return next(iter(seq)) except StopIteration: return environment.undefined("No first item, sequence was empty.")
27,527
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_first
( environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]" )
623
629
async def do_first( environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]" ) -> "t.Union[V, Undefined]": try: return await auto_aiter(seq).__anext__() except StopAsyncIteration: return environment.undefined("No first item, sequence was empty.")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L623-L629
42
[ 0, 3, 4 ]
42.857143
[ 5, 6 ]
28.571429
false
88.768606
7
2
71.428571
0
async def do_first( environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]" ) -> "t.Union[V, Undefined]": try: return await auto_aiter(seq).__anext__() except StopAsyncIteration: return environment.undefined("No first item, sequence was empty.")
27,528
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_last
( environment: "Environment", seq: "t.Reversible[V]" )
Return the last item of a sequence. Note: Does not work with generators. You may want to explicitly convert it to a list: .. sourcecode:: jinja {{ data | selectattr('name', '==', 'Jinja') | list | last }}
Return the last item of a sequence.
633
648
def do_last( environment: "Environment", seq: "t.Reversible[V]" ) -> "t.Union[V, Undefined]": """Return the last item of a sequence. Note: Does not work with generators. You may want to explicitly convert it to a list: .. sourcecode:: jinja {{ data | selectattr('name', '==', 'Jinja') | list | last }} """ try: return next(iter(reversed(seq))) except StopIteration: return environment.undefined("No last item, sequence was empty.")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L633-L648
42
[ 0, 11, 12, 13 ]
25
[ 14, 15 ]
12.5
false
88.768606
16
2
87.5
8
def do_last( environment: "Environment", seq: "t.Reversible[V]" ) -> "t.Union[V, Undefined]": try: return next(iter(reversed(seq))) except StopIteration: return environment.undefined("No last item, sequence was empty.")
27,529
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_random
(context: "Context", seq: "t.Sequence[V]")
Return a random item from the sequence.
Return a random item from the sequence.
655
660
def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]": """Return a random item from the sequence.""" try: return random.choice(seq) except IndexError: return context.environment.undefined("No random item, sequence was empty.")
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L655-L660
42
[ 0, 1, 2, 3 ]
66.666667
[ 4, 5 ]
33.333333
false
88.768606
6
2
66.666667
1
def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]": try: return random.choice(seq) except IndexError: return context.environment.undefined("No random item, sequence was empty.")
27,530
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_filesizeformat
(value: t.Union[str, float, int], binary: bool = False)
Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi).
Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi).
663
693
def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str: """Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi). """ bytes = float(value) base = 1024 if binary else 1000 prefixes = [ ("KiB" if binary else "kB"), ("MiB" if binary else "MB"), ("GiB" if binary else "GB"), ("TiB" if binary else "TB"), ("PiB" if binary else "PB"), ("EiB" if binary else "EB"), ("ZiB" if binary else "ZB"), ("YiB" if binary else "YB"), ] if bytes == 1: return "1 Byte" elif bytes < base: return f"{int(bytes)} Bytes" else: for i, prefix in enumerate(prefixes): unit = base ** (i + 2) if bytes < unit: return f"{base * bytes / unit:.1f} {prefix}" return f"{base * bytes / unit:.1f} {prefix}"
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L663-L693
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]
93.548387
[ 20, 30 ]
6.451613
false
88.768606
31
5
93.548387
4
def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str: bytes = float(value) base = 1024 if binary else 1000 prefixes = [ ("KiB" if binary else "kB"), ("MiB" if binary else "MB"), ("GiB" if binary else "GB"), ("TiB" if binary else "TB"), ("PiB" if binary else "PB"), ("EiB" if binary else "EB"), ("ZiB" if binary else "ZB"), ("YiB" if binary else "YB"), ] if bytes == 1: return "1 Byte" elif bytes < base: return f"{int(bytes)} Bytes" else: for i, prefix in enumerate(prefixes): unit = base ** (i + 2) if bytes < unit: return f"{base * bytes / unit:.1f} {prefix}" return f"{base * bytes / unit:.1f} {prefix}"
27,531
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_pprint
(value: t.Any)
return pformat(value)
Pretty print a variable. Useful for debugging.
Pretty print a variable. Useful for debugging.
696
698
def do_pprint(value: t.Any) -> str: """Pretty print a variable. Useful for debugging.""" return pformat(value)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L696-L698
42
[ 0, 1, 2 ]
100
[]
0
true
88.768606
3
1
100
1
def do_pprint(value: t.Any) -> str: return pformat(value)
27,532
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_urlize
( eval_ctx: "EvalContext", value: str, trim_url_limit: t.Optional[int] = None, nofollow: bool = False, target: t.Optional[str] = None, rel: t.Optional[str] = None, extra_schemes: t.Optional[t.Iterable[str]] = None, )
return rv
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 value: Original text containing URLs to link. :param trim_url_limit: Shorten displayed URL values to this length. :param nofollow: Add the ``rel=nofollow`` attribute to links. :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. Defaults to ``env.policies["urlize.extra_schemes"]``, which defaults to no extra schemes. .. 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. .. versionchanged:: 2.8 The ``target`` parameter was added.
Convert URLs in text into clickable links.
705
781
def do_urlize( eval_ctx: "EvalContext", value: str, trim_url_limit: t.Optional[int] = None, nofollow: bool = False, target: t.Optional[str] = None, rel: 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 value: Original text containing URLs to link. :param trim_url_limit: Shorten displayed URL values to this length. :param nofollow: Add the ``rel=nofollow`` attribute to links. :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. Defaults to ``env.policies["urlize.extra_schemes"]``, which defaults to no extra schemes. .. 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. .. versionchanged:: 2.8 The ``target`` parameter was added. """ policies = eval_ctx.environment.policies rel_parts = set((rel or "").split()) if nofollow: rel_parts.add("nofollow") rel_parts.update((policies["urlize.rel"] or "").split()) rel = " ".join(sorted(rel_parts)) or None if target is None: target = policies["urlize.target"] if extra_schemes is None: extra_schemes = policies["urlize.extra_schemes"] or () for scheme in extra_schemes: if _uri_scheme_re.fullmatch(scheme) is None: raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.") rv = urlize( value, trim_url_limit=trim_url_limit, rel=rel, target=target, extra_schemes=extra_schemes, ) if eval_ctx.autoescape: rv = Markup(rv) return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L705-L781
42
[ 0, 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 75, 76 ]
38.961039
[ 50, 63, 74 ]
3.896104
false
88.768606
77
11
96.103896
36
def do_urlize( eval_ctx: "EvalContext", value: str, trim_url_limit: t.Optional[int] = None, nofollow: bool = False, target: t.Optional[str] = None, rel: t.Optional[str] = None, extra_schemes: t.Optional[t.Iterable[str]] = None, ) -> str: policies = eval_ctx.environment.policies rel_parts = set((rel or "").split()) if nofollow: rel_parts.add("nofollow") rel_parts.update((policies["urlize.rel"] or "").split()) rel = " ".join(sorted(rel_parts)) or None if target is None: target = policies["urlize.target"] if extra_schemes is None: extra_schemes = policies["urlize.extra_schemes"] or () for scheme in extra_schemes: if _uri_scheme_re.fullmatch(scheme) is None: raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.") rv = urlize( value, trim_url_limit=trim_url_limit, rel=rel, target=target, extra_schemes=extra_schemes, ) if eval_ctx.autoescape: rv = Markup(rv) return rv
27,533
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_indent
( s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False )
return rv
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces, or a string, to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 3.0 ``width`` can be a string. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``.
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.
784
829
def do_indent( s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False ) -> str: """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces, or a string, to indent by. :param first: Don't skip indenting the first line. :param blank: Don't skip indenting empty lines. .. versionchanged:: 3.0 ``width`` can be a string. .. versionchanged:: 2.10 Blank lines are not indented by default. Rename the ``indentfirst`` argument to ``first``. """ if isinstance(width, str): indention = width else: indention = " " * width newline = "\n" if isinstance(s, Markup): indention = Markup(indention) newline = Markup(newline) s += newline # this quirk is necessary for splitlines method if blank: rv = (newline + indention).join(s.splitlines()) else: lines = s.splitlines() rv = lines.pop(0) if lines: rv += newline + newline.join( indention + line if line else line for line in lines ) if first: rv = indention + rv return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L784-L829
42
[ 0, 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 ]
65.217391
[]
0
false
88.768606
46
6
100
14
def do_indent( s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False ) -> str: if isinstance(width, str): indention = width else: indention = " " * width newline = "\n" if isinstance(s, Markup): indention = Markup(indention) newline = Markup(newline) s += newline # this quirk is necessary for splitlines method if blank: rv = (newline + indention).join(s.splitlines()) else: lines = s.splitlines() rv = lines.pop(0) if lines: rv += newline + newline.join( indention + line if line else line for line in lines ) if first: rv = indention + rv return rv
27,534
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_truncate
( env: "Environment", s: str, length: int = 255, killwords: bool = False, end: str = "...", leeway: t.Optional[int] = None, )
return result + end
Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally.
Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.
833
877
def do_truncate( env: "Environment", s: str, length: int = 255, killwords: bool = False, end: str = "...", leeway: t.Optional[int] = None, ) -> str: """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign (``"..."``). If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated. .. sourcecode:: jinja {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." {{ "foo bar baz qux"|truncate(11) }} -> "foo bar baz qux" {{ "foo bar baz qux"|truncate(11, False, '...', 0) }} -> "foo bar..." The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally. """ if leeway is None: leeway = env.policies["truncate.leeway"] assert length >= len(end), f"expected length >= {len(end)}, got {length}" assert leeway >= 0, f"expected leeway >= 0, got {leeway}" if len(s) <= length + leeway: return s if killwords: return s[: length - len(end)] + end result = s[: length - len(end)].rsplit(" ", 1)[0] return result + end
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L833-L877
42
[ 0, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44 ]
35.555556
[]
0
false
88.768606
45
6
100
22
def do_truncate( env: "Environment", s: str, length: int = 255, killwords: bool = False, end: str = "...", leeway: t.Optional[int] = None, ) -> str: if leeway is None: leeway = env.policies["truncate.leeway"] assert length >= len(end), f"expected length >= {len(end)}, got {length}" assert leeway >= 0, f"expected leeway >= 0, got {leeway}" if len(s) <= length + leeway: return s if killwords: return s[: length - len(end)] + end result = s[: length - len(end)].rsplit(" ", 1)[0] return result + end
27,535
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_wordwrap
( environment: "Environment", s: str, width: int = 79, break_long_words: bool = True, wrapstring: t.Optional[str] = None, break_on_hyphens: bool = True, )
return wrapstring.join( [ wrapstring.join( textwrap.wrap( line, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens, ) ) for line in s.splitlines() ] )
Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately. :param s: Original text to wrap. :param width: Maximum length of wrapped lines. :param break_long_words: If a word is longer than ``width``, break it across lines. :param break_on_hyphens: If a word contains hyphens, it may be split across lines. :param wrapstring: String to join each wrapped line. Defaults to :attr:`Environment.newline_sequence`. .. versionchanged:: 2.11 Existing newlines are treated as paragraphs wrapped separately. .. versionchanged:: 2.11 Added the ``break_on_hyphens`` parameter. .. versionchanged:: 2.7 Added the ``wrapstring`` parameter.
Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately.
881
933
def do_wordwrap( environment: "Environment", s: str, width: int = 79, break_long_words: bool = True, wrapstring: t.Optional[str] = None, break_on_hyphens: bool = True, ) -> str: """Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately. :param s: Original text to wrap. :param width: Maximum length of wrapped lines. :param break_long_words: If a word is longer than ``width``, break it across lines. :param break_on_hyphens: If a word contains hyphens, it may be split across lines. :param wrapstring: String to join each wrapped line. Defaults to :attr:`Environment.newline_sequence`. .. versionchanged:: 2.11 Existing newlines are treated as paragraphs wrapped separately. .. versionchanged:: 2.11 Added the ``break_on_hyphens`` parameter. .. versionchanged:: 2.7 Added the ``wrapstring`` parameter. """ import textwrap if wrapstring is None: wrapstring = environment.newline_sequence # textwrap.wrap doesn't consider existing newlines when wrapping. # If the string has a newline before width, wrap will still insert # a newline at width, resulting in a short line. Instead, split and # wrap each paragraph individually. return wrapstring.join( [ wrapstring.join( textwrap.wrap( line, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens, ) ) for line in s.splitlines() ] )
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L881-L933
42
[ 0, 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 ]
49.056604
[]
0
false
88.768606
53
3
100
20
def do_wordwrap( environment: "Environment", s: str, width: int = 79, break_long_words: bool = True, wrapstring: t.Optional[str] = None, break_on_hyphens: bool = True, ) -> str: import textwrap if wrapstring is None: wrapstring = environment.newline_sequence # textwrap.wrap doesn't consider existing newlines when wrapping. # If the string has a newline before width, wrap will still insert # a newline at width, resulting in a short line. Instead, split and # wrap each paragraph individually. return wrapstring.join( [ wrapstring.join( textwrap.wrap( line, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens, ) ) for line in s.splitlines() ] )
27,536
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_wordcount
(s: str)
return len(_word_re.findall(soft_str(s)))
Count the words in that string.
Count the words in that string.
939
941
def do_wordcount(s: str) -> int: """Count the words in that string.""" return len(_word_re.findall(soft_str(s)))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L939-L941
42
[ 0, 1, 2 ]
100
[]
0
true
88.768606
3
1
100
1
def do_wordcount(s: str) -> int: return len(_word_re.findall(soft_str(s)))
27,537
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_int
(value: t.Any, default: int = 0, base: int = 10)
Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values.
Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values.
944
963
def do_int(value: t.Any, default: int = 0, base: int = 10) -> int: """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values. """ try: if isinstance(value, str): return int(value, base) return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|int gives 42. try: return int(float(value)) except (TypeError, ValueError): return default
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L944-L963
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
88.768606
20
4
100
7
def do_int(value: t.Any, default: int = 0, base: int = 10) -> int: try: if isinstance(value, str): return int(value, base) return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|int gives 42. try: return int(float(value)) except (TypeError, ValueError): return default
27,538
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_float
(value: t.Any, default: float = 0.0)
Convert the value into a floating point number. If the conversion doesn't work it will return ``0.0``. You can override this default using the first parameter.
Convert the value into a floating point number. If the conversion doesn't work it will return ``0.0``. You can override this default using the first parameter.
966
974
def do_float(value: t.Any, default: float = 0.0) -> float: """Convert the value into a floating point number. If the conversion doesn't work it will return ``0.0``. You can override this default using the first parameter. """ try: return float(value) except (TypeError, ValueError): return default
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L966-L974
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
88.768606
9
2
100
3
def do_float(value: t.Any, default: float = 0.0) -> float: try: return float(value) except (TypeError, ValueError): return default
27,539
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_format
(value: str, *args: t.Any, **kwargs: t.Any)
return soft_str(value) % (kwargs or args)
Apply the given values to a `printf-style`_ format string, like ``string % values``. .. sourcecode:: jinja {{ "%s, %s!"|format(greeting, name) }} Hello, World! In most cases it should be more convenient and efficient to use the ``%`` operator or :meth:`str.format`. .. code-block:: text {{ "%s, %s!" % (greeting, name) }} {{ "{}, {}!".format(greeting, name) }} .. _printf-style: https://docs.python.org/library/stdtypes.html #printf-style-string-formatting
Apply the given values to a `printf-style`_ format string, like ``string % values``.
977
1,002
def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str: """Apply the given values to a `printf-style`_ format string, like ``string % values``. .. sourcecode:: jinja {{ "%s, %s!"|format(greeting, name) }} Hello, World! In most cases it should be more convenient and efficient to use the ``%`` operator or :meth:`str.format`. .. code-block:: text {{ "%s, %s!" % (greeting, name) }} {{ "{}, {}!".format(greeting, name) }} .. _printf-style: https://docs.python.org/library/stdtypes.html #printf-style-string-formatting """ if args and kwargs: raise FilterArgumentError( "can't handle positional and keyword arguments at the same time" ) return soft_str(value) % (kwargs or args)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L977-L1002
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 25 ]
88.461538
[ 21 ]
3.846154
false
88.768606
26
4
96.153846
18
def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str: if args and kwargs: raise FilterArgumentError( "can't handle positional and keyword arguments at the same time" ) return soft_str(value) % (kwargs or args)
27,540
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_trim
(value: str, chars: t.Optional[str] = None)
return soft_str(value).strip(chars)
Strip leading and trailing characters, by default whitespace.
Strip leading and trailing characters, by default whitespace.
1,005
1,007
def do_trim(value: str, chars: t.Optional[str] = None) -> str: """Strip leading and trailing characters, by default whitespace.""" return soft_str(value).strip(chars)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1005-L1007
42
[ 0, 1, 2 ]
100
[]
0
true
88.768606
3
1
100
1
def do_trim(value: str, chars: t.Optional[str] = None) -> str: return soft_str(value).strip(chars)
27,541
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_striptags
(value: "t.Union[str, HasHTML]")
return Markup(str(value)).striptags()
Strip SGML/XML tags and replace adjacent whitespace by one space.
Strip SGML/XML tags and replace adjacent whitespace by one space.
1,010
1,015
def do_striptags(value: "t.Union[str, HasHTML]") -> str: """Strip SGML/XML tags and replace adjacent whitespace by one space.""" if hasattr(value, "__html__"): value = t.cast("HasHTML", value).__html__() return Markup(str(value)).striptags()
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1010-L1015
42
[ 0, 1, 2, 4, 5 ]
83.333333
[ 3 ]
16.666667
false
88.768606
6
2
83.333333
1
def do_striptags(value: "t.Union[str, HasHTML]") -> str: if hasattr(value, "__html__"): value = t.cast("HasHTML", value).__html__() return Markup(str(value)).striptags()
27,542
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_slice
( value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None )
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columnwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration.
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns:
1,018
1,058
def sync_do_slice( value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None ) -> "t.Iterator[t.List[V]]": """Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columnwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration. """ seq = list(value) length = len(seq) items_per_slice = length // slices slices_with_extra = length % slices offset = 0 for slice_number in range(slices): start = offset + slice_number * items_per_slice if slice_number < slices_with_extra: offset += 1 end = offset + (slice_number + 1) * items_per_slice tmp = seq[start:end] if fill_with is not None and slice_number >= slices_with_extra: tmp.append(fill_with) yield tmp
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1018-L1058
42
[ 0, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 ]
51.219512
[]
0
false
88.768606
41
5
100
18
def sync_do_slice( value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None ) -> "t.Iterator[t.List[V]]": seq = list(value) length = len(seq) items_per_slice = length // slices slices_with_extra = length % slices offset = 0 for slice_number in range(slices): start = offset + slice_number * items_per_slice if slice_number < slices_with_extra: offset += 1 end = offset + (slice_number + 1) * items_per_slice tmp = seq[start:end] if fill_with is not None and slice_number >= slices_with_extra: tmp.append(fill_with) yield tmp
27,543
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_slice
( value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", slices: int, fill_with: t.Optional[t.Any] = None, )
return sync_do_slice(await auto_to_list(value), slices, fill_with)
1,062
1,067
async def do_slice( value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", slices: int, fill_with: t.Optional[t.Any] = None, ) -> "t.Iterator[t.List[V]]": return sync_do_slice(await auto_to_list(value), slices, fill_with)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1062-L1067
42
[ 0, 5 ]
33.333333
[]
0
false
88.768606
6
1
100
0
async def do_slice( value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", slices: int, fill_with: t.Optional[t.Any] = None, ) -> "t.Iterator[t.List[V]]": return sync_do_slice(await auto_to_list(value), slices, fill_with)
27,544
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_batch
( value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None )
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table>
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:
1,070
1,104
def do_batch( value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None ) -> "t.Iterator[t.List[V]]": """ A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table> """ tmp: "t.List[V]" = [] for item in value: if len(tmp) == linecount: yield tmp tmp = [] tmp.append(item) if tmp: if fill_with is not None and len(tmp) < linecount: tmp += [fill_with] * (linecount - len(tmp)) yield tmp
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1070-L1104
42
[ 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 ]
45.714286
[]
0
false
88.768606
35
6
100
16
def do_batch( value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None ) -> "t.Iterator[t.List[V]]": tmp: "t.List[V]" = [] for item in value: if len(tmp) == linecount: yield tmp tmp = [] tmp.append(item) if tmp: if fill_with is not None and len(tmp) < linecount: tmp += [fill_with] * (linecount - len(tmp)) yield tmp
27,545
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_round
( value: float, precision: int = 0, method: 'te.Literal["common", "ceil", "floor"]' = "common", )
return t.cast(float, func(value * (10**precision)) / (10**precision))
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method:
1,107
1,144
def do_round( value: float, precision: int = 0, method: 'te.Literal["common", "ceil", "floor"]' = "common", ) -> float: """Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 """ if method not in {"common", "ceil", "floor"}: raise FilterArgumentError("method must be common, ceil or floor") if method == "common": return round(value, precision) func = getattr(math, method) return t.cast(float, func(value * (10**precision)) / (10**precision))
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1107-L1144
42
[ 0, 29, 30, 32, 33, 34, 35, 36, 37 ]
23.684211
[ 31 ]
2.631579
false
88.768606
38
3
97.368421
24
def do_round( value: float, precision: int = 0, method: 'te.Literal["common", "ceil", "floor"]' = "common", ) -> float: if method not in {"common", "ceil", "floor"}: raise FilterArgumentError("method must be common, ceil or floor") if method == "common": return round(value, precision) func = getattr(math, method) return t.cast(float, func(value * (10**precision)) / (10**precision))
27,546
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_groupby
( environment: "Environment", value: "t.Iterable[V]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, )
return out
Group a sequence of objects by an attribute using Python's :func:`itertools.groupby`. The attribute can use dot notation for nested access, like ``"address.city"``. Unlike Python's ``groupby``, the values are sorted first so only one group is returned for each unique value. For example, a list of ``User`` objects with a ``city`` attribute can be rendered in groups. In this example, ``grouper`` refers to the ``city`` value of the group. .. sourcecode:: html+jinja <ul>{% for city, items in users|groupby("city") %} <li>{{ city }} <ul>{% for user in items %} <li>{{ user.name }} {% endfor %}</ul> </li> {% endfor %}</ul> ``groupby`` yields namedtuples of ``(grouper, list)``, which can be used instead of the tuple unpacking above. ``grouper`` is the value of the attribute, and ``list`` is the items with that value. .. sourcecode:: html+jinja <ul>{% for group in users|groupby("city") %} <li>{{ group.grouper }}: {{ group.list|join(", ") }} {% endfor %}</ul> You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja <ul>{% for city, items in users|groupby("city", default="NY") %} <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li> {% endfor %}</ul> Like the :func:`~jinja-filters.sort` filter, sorting and grouping is case-insensitive by default. The ``key`` for each group will have the case of the first item in that group of values. For example, if a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group will have two values. This can be disabled by passing ``case_sensitive=True``. .. versionchanged:: 3.1 Added the ``case_sensitive`` parameter. Sorting and grouping is case-insensitive by default, matching other filters that do comparisons. .. versionchanged:: 3.0 Added the ``default`` parameter. .. versionchanged:: 2.6 The attribute supports dot notation for nested access.
Group a sequence of objects by an attribute using Python's :func:`itertools.groupby`. The attribute can use dot notation for nested access, like ``"address.city"``. Unlike Python's ``groupby``, the values are sorted first so only one group is returned for each unique value.
1,161
1,241
def sync_do_groupby( environment: "Environment", value: "t.Iterable[V]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, ) -> "t.List[_GroupTuple]": """Group a sequence of objects by an attribute using Python's :func:`itertools.groupby`. The attribute can use dot notation for nested access, like ``"address.city"``. Unlike Python's ``groupby``, the values are sorted first so only one group is returned for each unique value. For example, a list of ``User`` objects with a ``city`` attribute can be rendered in groups. In this example, ``grouper`` refers to the ``city`` value of the group. .. sourcecode:: html+jinja <ul>{% for city, items in users|groupby("city") %} <li>{{ city }} <ul>{% for user in items %} <li>{{ user.name }} {% endfor %}</ul> </li> {% endfor %}</ul> ``groupby`` yields namedtuples of ``(grouper, list)``, which can be used instead of the tuple unpacking above. ``grouper`` is the value of the attribute, and ``list`` is the items with that value. .. sourcecode:: html+jinja <ul>{% for group in users|groupby("city") %} <li>{{ group.grouper }}: {{ group.list|join(", ") }} {% endfor %}</ul> You can specify a ``default`` value to use if an object in the list does not have the given attribute. .. sourcecode:: jinja <ul>{% for city, items in users|groupby("city", default="NY") %} <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li> {% endfor %}</ul> Like the :func:`~jinja-filters.sort` filter, sorting and grouping is case-insensitive by default. The ``key`` for each group will have the case of the first item in that group of values. For example, if a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group will have two values. This can be disabled by passing ``case_sensitive=True``. .. versionchanged:: 3.1 Added the ``case_sensitive`` parameter. Sorting and grouping is case-insensitive by default, matching other filters that do comparisons. .. versionchanged:: 3.0 Added the ``default`` parameter. .. versionchanged:: 2.6 The attribute supports dot notation for nested access. """ expr = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None, default=default, ) out = [ _GroupTuple(key, list(values)) for key, values in groupby(sorted(value, key=expr), expr) ] if not case_sensitive: # Return the real key from the first value instead of the lowercase key. output_expr = make_attrgetter(environment, attribute, default=default) out = [_GroupTuple(output_expr(values[0]), values) for _, values in out] return out
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1161-L1241
42
[ 0, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 ]
23.45679
[]
0
false
88.768606
81
4
100
56
def sync_do_groupby( environment: "Environment", value: "t.Iterable[V]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, ) -> "t.List[_GroupTuple]": expr = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None, default=default, ) out = [ _GroupTuple(key, list(values)) for key, values in groupby(sorted(value, key=expr), expr) ] if not case_sensitive: # Return the real key from the first value instead of the lowercase key. output_expr = make_attrgetter(environment, attribute, default=default) out = [_GroupTuple(output_expr(values[0]), values) for _, values in out] return out
27,547
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_groupby
( environment: "Environment", value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, )
return out
1,245
1,268
async def do_groupby( environment: "Environment", value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, ) -> "t.List[_GroupTuple]": expr = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None, default=default, ) out = [ _GroupTuple(key, await auto_to_list(values)) for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr) ] if not case_sensitive: # Return the real key from the first value instead of the lowercase key. output_expr = make_attrgetter(environment, attribute, default=default) out = [_GroupTuple(output_expr(values[0]), values) for _, values in out] return out
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1245-L1268
42
[ 0, 7, 13, 17, 18, 19, 20, 21, 22, 23 ]
41.666667
[]
0
false
88.768606
24
4
100
0
async def do_groupby( environment: "Environment", value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", attribute: t.Union[str, int], default: t.Optional[t.Any] = None, case_sensitive: bool = False, ) -> "t.List[_GroupTuple]": expr = make_attrgetter( environment, attribute, postprocess=ignore_case if not case_sensitive else None, default=default, ) out = [ _GroupTuple(key, await auto_to_list(values)) for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr) ] if not case_sensitive: # Return the real key from the first value instead of the lowercase key. output_expr = make_attrgetter(environment, attribute, default=default) out = [_GroupTuple(output_expr(values[0]), values) for _, values in out] return out
27,548
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_sum
( environment: "Environment", iterable: "t.Iterable[V]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore )
return sum(iterable, start)
Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The ``attribute`` parameter was added to allow summing up over attributes. Also the ``start`` parameter was moved on to the right.
Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start.
1,272
1,295
def sync_do_sum( environment: "Environment", iterable: "t.Iterable[V]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore ) -> V: """Returns the sum of a sequence of numbers plus the value of parameter 'start' (which defaults to 0). When the sequence is empty it returns start. It is also possible to sum up only certain attributes: .. sourcecode:: jinja Total: {{ items|sum(attribute='price') }} .. versionchanged:: 2.6 The ``attribute`` parameter was added to allow summing up over attributes. Also the ``start`` parameter was moved on to the right. """ if attribute is not None: iterable = map(make_attrgetter(environment, attribute), iterable) return sum(iterable, start)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1272-L1295
42
[ 0, 19, 20, 21, 22, 23 ]
25
[]
0
false
88.768606
24
2
100
13
def sync_do_sum( environment: "Environment", iterable: "t.Iterable[V]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore ) -> V: if attribute is not None: iterable = map(make_attrgetter(environment, attribute), iterable) return sum(iterable, start)
27,549
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_sum
( environment: "Environment", iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore )
return rv
1,299
1,317
async def do_sum( environment: "Environment", iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore ) -> V: rv = start if attribute is not None: func = make_attrgetter(environment, attribute) else: def func(x: V) -> V: return x async for item in auto_aiter(iterable): rv += func(item) return rv
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1299-L1317
42
[ 0, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18 ]
68.421053
[]
0
false
88.768606
19
4
100
0
async def do_sum( environment: "Environment", iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", attribute: t.Optional[t.Union[str, int]] = None, start: V = 0, # type: ignore ) -> V: rv = start if attribute is not None: func = make_attrgetter(environment, attribute) else: def func(x: V) -> V: return x async for item in auto_aiter(iterable): rv += func(item) return rv
27,550
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_list
(value: "t.Iterable[V]")
return list(value)
Convert the value into a list. If it was a string the returned list will be a list of characters.
Convert the value into a list. If it was a string the returned list will be a list of characters.
1,320
1,324
def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]": """Convert the value into a list. If it was a string the returned list will be a list of characters. """ return list(value)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1320-L1324
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
88.768606
5
1
100
2
def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]": return list(value)
27,551
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_list
(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]")
return await auto_to_list(value)
1,328
1,329
async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]": return await auto_to_list(value)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1328-L1329
42
[ 0, 1 ]
100
[]
0
true
88.768606
2
1
100
0
async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]": return await auto_to_list(value)
27,552
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_mark_safe
(value: str)
return Markup(value)
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
1,332
1,336
def do_mark_safe(value: str) -> Markup: """Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped. """ return Markup(value)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1332-L1336
42
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
88.768606
5
1
100
2
def do_mark_safe(value: str) -> Markup: return Markup(value)
27,553
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_mark_unsafe
(value: str)
return str(value)
Mark a value as unsafe. This is the reverse operation for :func:`safe`.
Mark a value as unsafe. This is the reverse operation for :func:`safe`.
1,339
1,341
def do_mark_unsafe(value: str) -> str: """Mark a value as unsafe. This is the reverse operation for :func:`safe`.""" return str(value)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1339-L1341
42
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
88.768606
3
1
66.666667
1
def do_mark_unsafe(value: str) -> str: return str(value)
27,554
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_reverse
(value: str)
1,345
1,346
def do_reverse(value: str) -> str: ...
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1345-L1346
42
[ 0 ]
50
[ 1 ]
50
false
88.768606
2
1
50
0
def do_reverse(value: str) -> str: ...
27,555
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_reverse
(value: "t.Iterable[V]")
1,350
1,351
def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1350-L1351
42
[ 0 ]
50
[ 1 ]
50
false
88.768606
2
1
50
0
def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...
27,556
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_reverse
(value: t.Union[str, t.Iterable[V]])
Reverse the object or return an iterator that iterates over it the other way round.
Reverse the object or return an iterator that iterates over it the other way round.
1,354
1,369
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]: """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, str): return value[::-1] try: return reversed(value) # type: ignore except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError as e: raise FilterArgumentError("argument must be iterable") from e
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1354-L1369
42
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
56.25
[ 9, 10, 11, 12, 13, 14, 15 ]
43.75
false
88.768606
16
4
56.25
2
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]: if isinstance(value, str): return value[::-1] try: return reversed(value) # type: ignore except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError as e: raise FilterArgumentError("argument must be iterable") from e
27,557
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
do_attr
( environment: "Environment", obj: t.Any, name: str )
return environment.undefined(obj=obj, name=name)
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up.
1,373
1,400
def do_attr( environment: "Environment", obj: t.Any, name: str ) -> t.Union[Undefined, t.Any]: """Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. """ try: name = str(name) except UnicodeError: pass else: try: value = getattr(obj, name) except AttributeError: pass else: if environment.sandboxed: environment = t.cast("SandboxedEnvironment", environment) if not environment.is_safe_attribute(obj, name, value): return environment.unsafe_undefined(obj, name) return value return environment.undefined(obj=obj, name=name)
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1373-L1400
42
[ 0, 8, 9, 10, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
57.142857
[ 11, 12, 16, 17, 27 ]
17.857143
false
88.768606
28
5
82.142857
5
def do_attr( environment: "Environment", obj: t.Any, name: str ) -> t.Union[Undefined, t.Any]: try: name = str(name) except UnicodeError: pass else: try: value = getattr(obj, name) except AttributeError: pass else: if environment.sandboxed: environment = t.cast("SandboxedEnvironment", environment) if not environment.is_safe_attribute(obj, name, value): return environment.unsafe_undefined(obj, name) return value return environment.undefined(obj=obj, name=name)
27,558
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_map
( context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any )
1,404
1,407
def sync_do_map( context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any ) -> t.Iterable: ...
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1404-L1407
42
[ 0 ]
25
[ 3 ]
25
false
88.768606
4
1
75
0
def sync_do_map( context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any ) -> t.Iterable: ...
27,559
pallets/jinja
89eec1c5ee5022342f05c121dccb0e7b8b0ac523
src/jinja2/filters.py
sync_do_map
( context: "Context", value: t.Iterable, *, attribute: str = ..., default: t.Optional[t.Any] = None, )
1,411
1,418
def sync_do_map( context: "Context", value: t.Iterable, *, attribute: str = ..., default: t.Optional[t.Any] = None, ) -> t.Iterable: ...
https://github.com/pallets/jinja/blob/89eec1c5ee5022342f05c121dccb0e7b8b0ac523/project42/src/jinja2/filters.py#L1411-L1418
42
[ 0 ]
12.5
[ 7 ]
12.5
false
88.768606
8
1
87.5
0
def sync_do_map( context: "Context", value: t.Iterable, *, attribute: str = ..., default: t.Optional[t.Any] = None, ) -> t.Iterable: ...
27,560