nodes.py
This file
Path
src/jinja2/nodes.py
1,200 lines · 33.4 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1–4why, one step back1"""AST nodes generated by the parser for the compiler. Also provides2some node tree helper functions used by the parser and compiler in order3to normalize nodes.4"""Merge branch '3.1.x'David Lordbefore adoptionde61312
line 5why, one step back5update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 6–7why, one step back6import inspect7import operatorMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 8why, one step back8import typing as tupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 9–12why, one step back9from collections import deque1011from markupsafe import Markup12Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 13–14why, one step back13from .utils import _PassArg14Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 15why, one step back15if t.TYPE_CHECKING:Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 16why, one step back16 import typing_extensions as teMerge branch '3.1.x'David Lordbefore adoptionde61312
line 17why, one step back17Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 18–21why, one step back18 from .environment import Environment1920_NodeBound = t.TypeVar("_NodeBound", bound="Node")21Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 22why, one step back22_binop_to_func: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 23–31why, one step back23 "*": operator.mul,24 "/": operator.truediv,25 "//": operator.floordiv,26 "**": operator.pow,27 "%": operator.mod,28 "+": operator.add,29 "-": operator.sub,30}31Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 32why, one step back32_uaop_to_func: dict[str, t.Callable[[t.Any], t.Any]] = {update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 33–37why, one step back33 "not": operator.not_,34 "+": operator.pos,35 "-": operator.neg,36}37Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 38why, one step back38_cmpop_to_func: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 39–58why, one step back39 "eq": operator.eq,40 "ne": operator.ne,41 "gt": operator.gt,42 "gteq": operator.ge,43 "lt": operator.lt,44 "lteq": operator.le,45 "in": lambda a, b: a in b,46 "notin": lambda a, b: a not in b,47}484950class Impossible(Exception):51 """Raised if the node could not perform a requested action."""525354class NodeType(type):55 """A metaclass for nodes that handles the field and attribute56 inheritance. fields and attributes from the parent class are57 automatically forwarded to the child."""58Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 59why, one step back59 def __new__(mcs, name, bases, d): # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 60why, one step back60 for attr in "fields", "attributes":Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 61why, one step back61 storage: list[tuple[str, ...]] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 62–75why, one step back62 storage.extend(getattr(bases[0] if bases else object, attr, ()))63 storage.extend(d.get(attr, ()))64 assert len(bases) <= 1, "multiple inheritance not allowed"65 assert len(storage) == len(set(storage)), "layout conflict"66 d[attr] = tuple(storage)67 d.setdefault("abstract", False)68 return type.__new__(mcs, name, bases, d)697071class EvalContext:72 """Holds evaluation time information. Custom attributes can be attached73 to it in extensions.74 """75Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 76why, one step back76 def __init__(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 77why, one step back77 self, environment: "Environment", template_name: str | None = NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 78why, one step back78 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 79–85why, one step back79 self.environment = environment80 if callable(environment.autoescape):81 self.autoescape = environment.autoescape(template_name)82 else:83 self.autoescape = environment.autoescape84 self.volatile = False85Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 86why, one step back86 def save(self) -> t.Mapping[str, t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 87–88why, one step back87 return self.__dict__.copy()88Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 89why, one step back89 def revert(self, old: t.Mapping[str, t.Any]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 90–93why, one step back90 self.__dict__.clear()91 self.__dict__.update(old)9293drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 94why, one step back94def get_eval_context(node: "Node", ctx: EvalContext | None) -> EvalContext:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 95–121why, one step back95 if ctx is None:96 if node.environment is None:97 raise RuntimeError(98 "if no eval context is passed, the node must have an"99 " attached environment."100 )101 return EvalContext(node.environment)102 return ctx103104105class Node(metaclass=NodeType):106 """Baseclass for all Jinja nodes. There are a number of nodes available107 of different types. There are four major types:108109 - :class:`Stmt`: statements110 - :class:`Expr`: expressions111 - :class:`Helper`: helper nodes112 - :class:`Template`: the outermost wrapper node113114 All nodes have fields and attributes. Fields may be other nodes, lists,115 or arbitrary values. Fields are passed to the constructor as regular116 positional arguments, attributes as keyword arguments. Each node has117 two attributes: `lineno` (the line number of the node) and `environment`.118 The `environment` attribute is set at the end of the parsing process for119 all nodes automatically.120 """121Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 122–123why, one step back122 fields: tuple[str, ...] = ()123 attributes: tuple[str, ...] = ("lineno", "environment")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 124–125why, one step back124 abstract = True125Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 126–129why, one step back126 lineno: int127 environment: t.Optional["Environment"]128129 def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 130–134why, one step back130 if self.abstract:131 raise TypeError("abstract nodes are not instantiable")132 if fields:133 if len(fields) != len(self.fields):134 if not self.fields:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 135why, one step back135 raise TypeError(f"{type(self).__name__!r} takes 0 arguments")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 136why, one step back136 raise TypeError(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 137why, one step back137 f"{type(self).__name__!r} takes 0 or {len(self.fields)}"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 138–139why, one step back138 f" argument{'s' if len(self.fields) != 1 else ''}"139 )drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 140why, one step back140 for name, arg in zip(self.fields, fields, strict=False):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 141–146why, one step back141 setattr(self, name, arg)142 for attr in self.attributes:143 setattr(self, attr, attributes.pop(attr, None))144 if attributes:145 raise TypeError(f"unknown attribute {next(iter(attributes))!r}")146Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 147–148why, one step back147 def iter_fields(148 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 149–150why, one step back149 exclude: t.Container[str] | None = None,150 only: t.Container[str] | None = None,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 151why, one step back151 ) -> t.Iterator[tuple[str, t.Any]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 152–159why, one step back152 """This method iterates over all fields that are defined and yields153 ``(key, value)`` tuples. Per default all fields are returned, but154 it's possible to limit that to some fields by providing the `only`155 parameter or to exclude some using the `exclude` parameter. Both156 should be sets or tuples of field names.157 """158 for name in self.fields:159 if (Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 160why, one step back160 (exclude is None and only is None)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 161–168why, one step back161 or (exclude is not None and name not in exclude)162 or (only is not None and name in only)163 ):164 try:165 yield name, getattr(self, name)166 except AttributeError:167 pass168Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 169–170why, one step back169 def iter_child_nodes(170 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 171–172why, one step back171 exclude: t.Container[str] | None = None,172 only: t.Container[str] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 173why, one step back173 ) -> t.Iterator["Node"]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 174–185why, one step back174 """Iterates over all direct child nodes of the node. This iterates175 over all fields and yields the values of they are nodes. If the value176 of a field is a list all the nodes in that list are returned.177 """178 for _, item in self.iter_fields(exclude, only):179 if isinstance(item, list):180 for n in item:181 if isinstance(n, Node):182 yield n183 elif isinstance(item, Node):184 yield item185drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 186why, one step back186 def find(self, node_type: type[_NodeBound]) -> _NodeBound | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 187–192why, one step back187 """Find the first node of a given type. If no such node exists the188 return value is `None`.189 """190 for result in self.find_all(node_type):191 return result192Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 193–195why, one step back193 return None194195 def find_all(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 196why, one step back196 self, node_type: type[_NodeBound] | tuple[type[_NodeBound], ...]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 197why, one step back197 ) -> t.Iterator[_NodeBound]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 198–202why, one step back198 """Find all the nodes of a given type. If the type is a tuple,199 the check is performed for any of the tuple items.200 """201 for child in self.iter_child_nodes():202 if isinstance(child, node_type):Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 203why, one step back203 yield child # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 204–205why, one step back204 yield from child.find_all(node_type)205Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 206why, one step back206 def set_ctx(self, ctx: str) -> "Node":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 207–215why, one step back207 """Reset the context of a node and all child nodes. Per default the208 parser will all generate nodes that have a 'load' context as it's the209 most common one. This method is used in the parser to set assignment210 targets and other nodes to a store context.211 """212 todo = deque([self])213 while todo:214 node = todo.popleft()215 if "ctx" in node.fields:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 216why, one step back216 node.ctx = ctx # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 217–219why, one step back217 todo.extend(node.iter_child_nodes())218 return self219Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 220why, one step back220 def set_lineno(self, lineno: int, override: bool = False) -> "Node":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 221–230why, one step back221 """Set the line numbers of the node and children."""222 todo = deque([self])223 while todo:224 node = todo.popleft()225 if "lineno" in node.attributes:226 if node.lineno is None or override:227 node.lineno = lineno228 todo.extend(node.iter_child_nodes())229 return self230Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 231why, one step back231 def set_environment(self, environment: "Environment") -> "Node":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 232–239why, one step back232 """Set the environment for all nodes."""233 todo = deque([self])234 while todo:235 node = todo.popleft()236 node.environment = environment237 todo.extend(node.iter_child_nodes())238 return self239Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 240why, one step back240 def __eq__(self, other: t.Any) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 241–245why, one step back241 if type(self) is not type(other):242 return NotImplemented243244 return tuple(self.iter_fields()) == tuple(other.iter_fields())245Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 246why, one step back246 __hash__ = object.__hash__update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 247why, one step back247Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 248why, one step back248 def __repr__(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 249why, one step back249 args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 250why, one step back250 return f"{type(self).__name__}({args_str})"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 251why, one step back251Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 252why, one step back252 def dump(self) -> str:drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 253why, one step back253 def _dump(node: Node | t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 254–257why, one step back254 if not isinstance(node, Node):255 buf.append(repr(node))256 return257Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 258why, one step back258 buf.append(f"nodes.{type(node).__name__}(")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 259–276why, one step back259 if not node.fields:260 buf.append(")")261 return262 for idx, field in enumerate(node.fields):263 if idx:264 buf.append(", ")265 value = getattr(node, field)266 if isinstance(value, list):267 buf.append("[")268 for idx, item in enumerate(value):269 if idx:270 buf.append(", ")271 _dump(item)272 buf.append("]")273 else:274 _dump(value)275 buf.append(")")276Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 277why, one step back277 buf: list[str] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 278–299why, one step back278 _dump(self)279 return "".join(buf)280281282class Stmt(Node):283 """Base node for all statements."""284285 abstract = True286287288class Helper(Node):289 """Nodes that exist in a specific context only."""290291 abstract = True292293294class Template(Node):295 """Node that represents a template. This must be the outermost node that296 is passed to the compiler.297 """298299 fields = ("body",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 300why, one step back300 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 301–308why, one step back301302303class Output(Stmt):304 """A node that holds multiple expressions which are then printed out.305 This is used both for the `print` statement and the regular template data.306 """307308 fields = ("nodes",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 309why, one step back309 nodes: list["Expr"]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 310–315why, one step back310311312class Extends(Stmt):313 """Represents an extends statement."""314315 fields = ("template",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 316why, one step back316 template: "Expr"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 317–328why, one step back317318319class For(Stmt):320 """The for loop. `target` is the target for the iteration (usually a321 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list322 of nodes that are used as loop-body, and `else_` a list of nodes for the323 `else` block. If no else node exists it has to be an empty list.324325 For filtered nodes an expression can be stored as `test`, otherwise `None`.326 """327328 fields = ("target", "iter", "body", "else_", "test", "recursive")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 329–330why, one step back329 target: Node330 iter: NodeUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 331–332why, one step back331 body: list[Node]332 else_: list[Node]drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 333why, one step back333 test: Node | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 334why, one step back334 recursive: boolupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 335–340why, one step back335336337class If(Stmt):338 """If `test` is true, `body` is rendered, else `else_`."""339340 fields = ("test", "body", "elif_", "else_")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 341why, one step back341 test: NodeUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 342–344why, one step back342 body: list[Node]343 elif_: list["If"]344 else_: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 345–353why, one step back345346347class Macro(Stmt):348 """A macro definition. `name` is the name of the macro, `args` a list of349 arguments and `defaults` a list of defaults if there are any. `body` is350 a list of nodes for the macro body.351 """352353 fields = ("name", "args", "defaults", "body")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 354why, one step back354 name: strUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 355–357why, one step back355 args: list["Name"]356 defaults: list["Expr"]357 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 358–365why, one step back358359360class CallBlock(Stmt):361 """Like a macro without a name but a call instead. `call` is called with362 the unnamed macro as `caller` argument this node holds.363 """364365 fields = ("call", "args", "defaults", "body")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 366why, one step back366 call: "Call"Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 367–369why, one step back367 args: list["Name"]368 defaults: list["Expr"]369 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 370–375why, one step back370371372class FilterBlock(Stmt):373 """Node for filter sections."""374375 fields = ("body", "filter")Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 376why, one step back376 body: list[Node]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 377why, one step back377 filter: "Filter"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 378–387why, one step back378379380class With(Stmt):381 """Specific node for with statements. In older versions of Jinja the382 with statement was implemented on the base of the `Scope` node instead.383384 .. versionadded:: 2.9.3385 """386387 fields = ("targets", "values", "body")Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 388–390why, one step back388 targets: list["Expr"]389 values: list["Expr"]390 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 391–400why, one step back391392393class Block(Stmt):394 """A node that represents a block.395396 .. versionchanged:: 3.0.0397 the `required` field was added.398 """399400 fields = ("name", "body", "scoped", "required")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 401why, one step back401 name: strUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 402why, one step back402 body: list[Node]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 403–404why, one step back403 scoped: bool404 required: boolupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 405–410why, one step back405406407class Include(Stmt):408 """A node that represents the include tag."""409410 fields = ("template", "with_context", "ignore_missing")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 411–413why, one step back411 template: "Expr"412 with_context: bool413 ignore_missing: boolupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 414–419why, one step back414415416class Import(Stmt):417 """A node that represents the import tag."""418419 fields = ("template", "target", "with_context")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 420–422why, one step back420 template: "Expr"421 target: str422 with_context: boolupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 423–437why, one step back423424425class FromImport(Stmt):426 """A node that represents the from import tag. It's important to not427 pass unsafe names to the name attribute. The compiler translates the428 attribute lookups directly into getattr calls and does *not* use the429 subscript callback of the interface. As exported variables may not430 start with double underscores (which the parser asserts) this is not a431 problem for regular Jinja code, but if this node is used in an extension432 extra care must be taken.433434 The list of names may contain tuples if aliases are wanted.435 """436437 fields = ("template", "names", "with_context")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 438why, one step back438 template: "Expr"drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 439why, one step back439 names: list[str | tuple[str, str]]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 440why, one step back440 with_context: boolupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 441–446why, one step back441442443class ExprStmt(Stmt):444 """A statement that evaluates an expression and discards the result."""445446 fields = ("node",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 447why, one step back447 node: Nodeupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 448–453why, one step back448449450class Assign(Stmt):451 """Assigns an expression to a target."""452453 fields = ("target", "node")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 454–455why, one step back454 target: "Expr"455 node: Nodeupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 456–461why, one step back456457458class AssignBlock(Stmt):459 """Assigns a block to a target."""460461 fields = ("target", "filter", "body")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 462–463why, one step back462 target: "Expr"463 filter: t.Optional["Filter"]Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 464why, one step back464 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 465–471why, one step back465466467class Expr(Node):468 """Baseclass for all expressions."""469470 abstract = True471drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 472why, one step back472 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 473–484why, one step back473 """Return the value of the expression as constant or raise474 :exc:`Impossible` if this was not possible.475476 An :class:`EvalContext` can be provided, if none is given477 a default context is created which requires the nodes to have478 an attached environment.479480 .. versionchanged:: 2.4481 the `eval_ctx` parameter was added.482 """483 raise Impossible()484Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 485why, one step back485 def can_assign(self) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 486–493why, one step back486 """Check if it's possible to assign something to this node."""487 return False488489490class BinExpr(Expr):491 """Baseclass for all binary expressions."""492493 fields = ("left", "right")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 494–496why, one step back494 left: Expr495 right: Expr496 operator: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 497–498why, one step back497 abstract = True498drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 499why, one step back499 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 500why, one step back500 eval_ctx = get_eval_context(self, eval_ctx)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 501why, one step back501update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 502–503why, one step back502 # intercepted operators cannot be folded at compile time503 if (Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 504–505why, one step back504 eval_ctx.environment.sandboxed505 and self.operator in eval_ctx.environment.intercepted_binops # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 506–510why, one step back506 ):507 raise Impossible()508 f = _binop_to_func[self.operator]509 try:510 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 511–512why, one step back511 except Exception as e:512 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 513–518why, one step back513514515class UnaryExpr(Expr):516 """Baseclass for all unary expressions."""517518 fields = ("node",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 519–520why, one step back519 node: Expr520 operator: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 521–522why, one step back521 abstract = True522drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 523why, one step back523 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 524why, one step back524 eval_ctx = get_eval_context(self, eval_ctx)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 525why, one step back525update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 526–527why, one step back526 # intercepted operators cannot be folded at compile time527 if (Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 528–529why, one step back528 eval_ctx.environment.sandboxed529 and self.operator in eval_ctx.environment.intercepted_unops # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 530–534why, one step back530 ):531 raise Impossible()532 f = _uaop_to_func[self.operator]533 try:534 return f(self.node.as_const(eval_ctx))Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 535–536why, one step back535 except Exception as e:536 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 537–548why, one step back537538539class Name(Expr):540 """Looks up a name or stores a value in a name.541 The `ctx` of the node can be one of the following values:542543 - `store`: store a value in the name544 - `load`: load that name545 - `param`: like `store` but if the name was defined as function parameter.546 """547548 fields = ("name", "ctx")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 549–550why, one step back549 name: str550 ctx: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 551why, one step back551Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 552–553why, one step back552 def can_assign(self) -> bool:553 return self.name not in {"true", "false", "none", "True", "False", "None"}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 554–559why, one step back554555556class NSRef(Expr):557 """Reference to a namespace value assignment"""558559 fields = ("name", "attr")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 560–561why, one step back560 name: str561 attr: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 562why, one step back562Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 563why, one step back563 def can_assign(self) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 564–584why, one step back564 # We don't need any special checks here; NSRef assignments have a565 # runtime check to ensure the target is a namespace object which will566 # have been checked already as it is created using a normal assignment567 # which goes through a `Name` node.568 return True569570571class Literal(Expr):572 """Baseclass for literals."""573574 abstract = True575576577class Const(Literal):578 """All constant values. The parser will return this node for simple579 constants such as ``42`` or ``"foo"`` but it can be used to store more580 complex values such as lists too. Only constants with a safe581 representation (objects where ``eval(repr(x)) == x`` is true).582 """583584 fields = ("value",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 585why, one step back585 value: t.Anyupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 586why, one step back586drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 587why, one step back587 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 588–590why, one step back588 return self.value589590 @classmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 591–593why, one step back591 def from_untrusted(592 cls,593 value: t.Any,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 594–595why, one step back594 lineno: int | None = None,595 environment: "Environment | None" = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 596why, one step back596 ) -> "Const":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 597–611why, one step back597 """Return a const object if the value is representable as598 constant value in the generated code, otherwise it will raise599 an `Impossible` exception.600 """601 from .compiler import has_safe_repr602603 if not has_safe_repr(value):604 raise Impossible()605 return cls(value, lineno=lineno, environment=environment)606607608class TemplateData(Literal):609 """A constant template string."""610611 fields = ("data",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 612why, one step back612 data: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 613why, one step back613drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 614why, one step back614 def as_const(self, eval_ctx: EvalContext | None = None) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 615–629why, one step back615 eval_ctx = get_eval_context(self, eval_ctx)616 if eval_ctx.volatile:617 raise Impossible()618 if eval_ctx.autoescape:619 return Markup(self.data)620 return self.data621622623class Tuple(Literal):624 """For loop unpacking and some other things like multiple arguments625 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple626 is used for loading the names or storing.627 """628629 fields = ("items", "ctx")Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 630why, one step back630 items: list[Expr]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 631why, one step back631 ctx: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 632why, one step back632drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 633why, one step back633 def as_const(self, eval_ctx: EvalContext | None = None) -> tuple[t.Any, ...]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 634–636why, one step back634 eval_ctx = get_eval_context(self, eval_ctx)635 return tuple(x.as_const(eval_ctx) for x in self.items)636Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 637why, one step back637 def can_assign(self) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 638–647why, one step back638 for item in self.items:639 if not item.can_assign():640 return False641 return True642643644class List(Literal):645 """Any list literal such as ``[1, 2, 3]``"""646647 fields = ("items",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 648why, one step back648 items: list[Expr]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 649why, one step back649drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 650why, one step back650 def as_const(self, eval_ctx: EvalContext | None = None) -> list[t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 651–660why, one step back651 eval_ctx = get_eval_context(self, eval_ctx)652 return [x.as_const(eval_ctx) for x in self.items]653654655class Dict(Literal):656 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of657 :class:`Pair` nodes.658 """659660 fields = ("items",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 661why, one step back661 items: list["Pair"]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 662why, one step back662drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 663why, one step back663 def as_const(self, eval_ctx: EvalContext | None = None) -> dict[t.Any, t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 664–671why, one step back664 eval_ctx = get_eval_context(self, eval_ctx)665 return dict(x.as_const(eval_ctx) for x in self.items)666667668class Pair(Helper):669 """A key, value pair for dicts."""670671 fields = ("key", "value")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 672–673why, one step back672 key: Expr673 value: Exprupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 674why, one step back674drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 675why, one step back675 def as_const(self, eval_ctx: EvalContext | None = None) -> tuple[t.Any, t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 676–683why, one step back676 eval_ctx = get_eval_context(self, eval_ctx)677 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)678679680class Keyword(Helper):681 """A key, value pair for keyword arguments where key is a string."""682683 fields = ("key", "value")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 684–685why, one step back684 key: str685 value: Exprupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 686why, one step back686drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 687why, one step back687 def as_const(self, eval_ctx: EvalContext | None = None) -> tuple[str, t.Any]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 688–697why, one step back688 eval_ctx = get_eval_context(self, eval_ctx)689 return self.key, self.value.as_const(eval_ctx)690691692class CondExpr(Expr):693 """A conditional expression (inline if expression). (``{{694 foo if bar else baz }}``)695 """696697 fields = ("test", "expr1", "expr2")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 698–699why, one step back698 test: Expr699 expr1: Exprdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 700why, one step back700 expr2: Expr | Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 701why, one step back701drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 702why, one step back702 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 703–713why, one step back703 eval_ctx = get_eval_context(self, eval_ctx)704 if self.test.as_const(eval_ctx):705 return self.expr1.as_const(eval_ctx)706707 # if we evaluate to an undefined object, we better do that at runtime708 if self.expr2 is None:709 raise Impossible()710711 return self.expr2.as_const(eval_ctx)712713Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 714why, one step back714def args_as_const(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 715why, one step back715 node: t.Union["_FilterTestCommon", "Call"], eval_ctx: EvalContext | NoneUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 716why, one step back716) -> tuple[list[t.Any], dict[t.Any, t.Any]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 717–722why, one step back717 args = [x.as_const(eval_ctx) for x in node.args]718 kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)719720 if node.dyn_args is not None:721 try:722 args.extend(node.dyn_args.as_const(eval_ctx))Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 723–724why, one step back723 except Exception as e:724 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 725–728why, one step back725726 if node.dyn_kwargs is not None:727 try:728 kwargs.update(node.dyn_kwargs.as_const(eval_ctx))Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 729–730why, one step back729 except Exception as e:730 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 731–734why, one step back731732 return args, kwargs733734Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 735why, one step back735class _FilterTestCommon(Expr):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 736why, one step back736 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 737–738why, one step back737 node: Expr738 name: strUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 739–740why, one step back739 args: list[Expr]740 kwargs: list[Pair]drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 741–742why, one step back741 dyn_args: Expr | None742 dyn_kwargs: Expr | NoneMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 743–744why, one step back743 abstract = True744 _is_filter = Trueupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 745why, one step back745drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 746why, one step back746 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 747–748why, one step back747 eval_ctx = get_eval_context(self, eval_ctx)748Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 749why, one step back749 if eval_ctx.volatile:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 750–751why, one step back750 raise Impossible()751Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 752–755why, one step back752 if self._is_filter:753 env_map = eval_ctx.environment.filters754 else:755 env_map = eval_ctx.environment.testsupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 756why, one step back756Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 757why, one step back757 func = env_map.get(self.name)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 758why, one step back758 pass_arg = _PassArg.from_obj(func) # type: ignoreMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 759why, one step back759Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 760why, one step back760 if func is None or pass_arg is _PassArg.context:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 761–763why, one step back761 raise Impossible()762763 if eval_ctx.environment.is_async and (Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 764why, one step back764 getattr(func, "jinja_async_variant", False) is TrueMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 765why, one step back765 or inspect.iscoroutinefunction(func)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 766–771why, one step back766 ):767 raise Impossible()768769 args, kwargs = args_as_const(self, eval_ctx)770 args.insert(0, self.node.as_const(eval_ctx))771Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 772why, one step back772 if pass_arg is _PassArg.eval_context:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 773why, one step back773 args.insert(0, eval_ctx)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 774why, one step back774 elif pass_arg is _PassArg.environment:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 775why, one step back775 args.insert(0, eval_ctx.environment)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 776–777why, one step back776777 try:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 778why, one step back778 return func(*args, **kwargs)Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 779–780why, one step back779 except Exception as e:780 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 781–782why, one step back781782Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 783–788why, one step back783class Filter(_FilterTestCommon):784 """Apply a filter to an expression. ``name`` is the name of the785 filter, the other fields are the same as :class:`Call`.786787 If ``node`` is ``None``, the filter is being used in a filter block788 and is applied to the content of the block.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 789–790why, one step back789 """790drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 791why, one step back791 node: Expr | None # type: ignoreMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 792why, one step back792drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 793why, one step back793 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 794why, one step back794 if self.node is None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 795–796why, one step back795 raise Impossible()796Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 797why, one step back797 return super().as_const(eval_ctx=eval_ctx)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 798why, one step back798Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 799–805why, one step back799800class Test(_FilterTestCommon):801 """Apply a test to an expression. ``name`` is the name of the test,802 the other field are the same as :class:`Call`.803804 .. versionchanged:: 3.0805 ``as_const`` shares the same logic for filters and tests. TestsMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 806why, one step back806 check for volatile, async, and ``@pass_context`` etc.Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 807–810why, one step back807 decorators.808 """809810 _is_filter = Falseupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 811–821why, one step back811812813class Call(Expr):814 """Calls an expression. `args` is a list of arguments, `kwargs` a list815 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`816 and `dyn_kwargs` has to be either `None` or a node that is used as817 node for dynamic positional (``*args``) or keyword (``**kwargs``)818 arguments.819 """820821 fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 822why, one step back822 node: ExprUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 823–824why, one step back823 args: list[Expr]824 kwargs: list[Keyword]drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 825–826why, one step back825 dyn_args: Expr | None826 dyn_kwargs: Expr | Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 827–832why, one step back827828829class Getitem(Expr):830 """Get an attribute or item from an expression and prefer the item."""831832 fields = ("node", "arg", "ctx")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 833–835why, one step back833 node: Expr834 arg: Expr835 ctx: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 836why, one step back836drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 837why, one step back837 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 838–839why, one step back838 if self.ctx != "load":839 raise Impossible()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 840–842why, one step back840841 eval_ctx = get_eval_context(self, eval_ctx)842update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 843why, one step back843 try:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 844why, one step back844 return eval_ctx.environment.getitem(update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 845–846why, one step back845 self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)846 )Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 847–848why, one step back847 except Exception as e:848 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 849–856why, one step back849850851class Getattr(Expr):852 """Get an attribute or item from an expression that is a ascii-only853 bytestring and prefer the attribute.854 """855856 fields = ("node", "attr", "ctx")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 857–859why, one step back857 node: Expr858 attr: str859 ctx: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 860why, one step back860drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 861why, one step back861 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 862–863why, one step back862 if self.ctx != "load":863 raise Impossible()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 864–866why, one step back864865 eval_ctx = get_eval_context(self, eval_ctx)866update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 867why, one step back867 try:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 868why, one step back868 return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 869–870why, one step back869 except Exception as e:870 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 871–878why, one step back871872873class Slice(Expr):874 """Represents a slice object. This must only be used as argument for875 :class:`Subscript`.876 """877878 fields = ("start", "stop", "step")drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 879–881why, one step back879 start: Expr | None880 stop: Expr | None881 step: Expr | Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 882why, one step back882drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 883why, one step back883 def as_const(self, eval_ctx: EvalContext | None = None) -> slice:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 884–885why, one step back884 eval_ctx = get_eval_context(self, eval_ctx)885drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 886why, one step back886 def const(obj: Expr | None) -> t.Any | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 887–899why, one step back887 if obj is None:888 return None889 return obj.as_const(eval_ctx)890891 return slice(const(self.start), const(self.stop), const(self.step))892893894class Concat(Expr):895 """Concatenates the list of expressions provided after converting896 them to strings.897 """898899 fields = ("nodes",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 900why, one step back900 nodes: list[Expr]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 901why, one step back901drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 902why, one step back902 def as_const(self, eval_ctx: EvalContext | None = None) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 903–912why, one step back903 eval_ctx = get_eval_context(self, eval_ctx)904 return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)905906907class Compare(Expr):908 """Compares an expression with some other expressions. `ops` must be a909 list of :class:`Operand`\\s.910 """911912 fields = ("expr", "ops")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 913why, one step back913 expr: ExprUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 914why, one step back914 ops: list["Operand"]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 915why, one step back915drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 916why, one step back916 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 917–928why, one step back917 eval_ctx = get_eval_context(self, eval_ctx)918 result = value = self.expr.as_const(eval_ctx)919920 try:921 for op in self.ops:922 new_value = op.expr.as_const(eval_ctx)923 result = _cmpop_to_func[op.op](value, new_value)924925 if not result:926 return False927928 value = new_valueMerge branch '3.0.x'David Lordbefore adoptione20a52e
lines 929–930why, one step back929 except Exception as e:930 raise Impossible() from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 931–938why, one step back931932 return result933934935class Operand(Helper):936 """Holds an operator and an expression."""937938 fields = ("op", "expr")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 939–940why, one step back939 op: str940 expr: Exprupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 941–955why, one step back941942943class Mul(BinExpr):944 """Multiplies the left with the right node."""945946 operator = "*"947948949class Div(BinExpr):950 """Divides the left by the right node."""951952 operator = "/"953954955class FloorDiv(BinExpr):Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 956why, one step back956 """Divides the left by the right node and converts theupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 957–991why, one step back957 result into an integer by truncating.958 """959960 operator = "//"961962963class Add(BinExpr):964 """Add the left to the right node."""965966 operator = "+"967968969class Sub(BinExpr):970 """Subtract the right from the left node."""971972 operator = "-"973974975class Mod(BinExpr):976 """Left modulo right."""977978 operator = "%"979980981class Pow(BinExpr):982 """Left to the power of right."""983984 operator = "**"985986987class And(BinExpr):988 """Short circuited AND."""989990 operator = "and"991drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 992why, one step back992 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 993–1001why, one step back993 eval_ctx = get_eval_context(self, eval_ctx)994 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)995996997class Or(BinExpr):998 """Short circuited OR."""9991000 operator = "or"1001drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1002why, one step back1002 def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1003–1033why, one step back1003 eval_ctx = get_eval_context(self, eval_ctx)1004 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)100510061007class Not(UnaryExpr):1008 """Negate the expression."""10091010 operator = "not"101110121013class Neg(UnaryExpr):1014 """Make the expression negative."""10151016 operator = "-"101710181019class Pos(UnaryExpr):1020 """Make the expression positive (noop for most expressions)"""10211022 operator = "+"102310241025# Helpers for extensions102610271028class EnvironmentAttribute(Expr):1029 """Loads an attribute from the environment object. This is useful for1030 extensions that want to call a callback stored on the environment.1031 """10321033 fields = ("name",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1034why, one step back1034 name: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1035–1045why, one step back103510361037class ExtensionAttribute(Expr):1038 """Returns the attribute of an extension bound to the environment.1039 The identifier is the identifier of the :class:`Extension`.10401041 This node is usually constructed by calling the1042 :meth:`~jinja2.ext.Extension.attr` method on an extension.1043 """10441045 fields = ("identifier", "name")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1046–1047why, one step back1046 identifier: str1047 name: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1048–1057why, one step back104810491050class ImportedName(Expr):1051 """If created with an import name the import name is returned on node1052 access. For example ``ImportedName('cgi.escape')`` returns the `escape`1053 function from the cgi module on evaluation. Imports are optimized by the1054 compiler so there is no need to assign them to local variables.1055 """10561057 fields = ("importname",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1058why, one step back1058 importname: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1059–1065why, one step back105910601061class InternalName(Expr):1062 """An internal name in the compiler. You cannot create these nodes1063 yourself but the parser provides a1064 :meth:`~jinja2.parser.Parser.free_identifier` method that creates1065 a new identifier for you. This identifier is not available from theMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1066why, one step back1066 template and is not treated specially by the compiler.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1067–1069why, one step back1067 """10681069 fields = ("name",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1070why, one step back1070 name: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1071why, one step back1071Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1072why, one step back1072 def __init__(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1073–1082why, one step back1073 raise TypeError(1074 "Can't create internal names. Use the "1075 "`free_identifier` method on a parser."1076 )107710781079class MarkSafe(Expr):1080 """Mark the wrapped expression as safe (wrap it as `Markup`)."""10811082 fields = ("expr",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1083why, one step back1083 expr: Exprupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1084why, one step back1084drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1085why, one step back1085 def as_const(self, eval_ctx: EvalContext | None = None) -> Markup:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1086–1097why, one step back1086 eval_ctx = get_eval_context(self, eval_ctx)1087 return Markup(self.expr.as_const(eval_ctx))108810891090class MarkSafeIfAutoescape(Expr):1091 """Mark the wrapped expression as safe (wrap it as `Markup`) but1092 only if autoescaping is active.10931094 .. versionadded:: 2.51095 """10961097 fields = ("expr",)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1098why, one step back1098 expr: Exprupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1099why, one step back1099drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1100why, one step back1100 def as_const(self, eval_ctx: EvalContext | None = None) -> Markup | t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1101–1121why, one step back1101 eval_ctx = get_eval_context(self, eval_ctx)1102 if eval_ctx.volatile:1103 raise Impossible()1104 expr = self.expr.as_const(eval_ctx)1105 if eval_ctx.autoescape:1106 return Markup(expr)1107 return expr110811091110class ContextReference(Expr):1111 """Returns the current template context. It can be used like a1112 :class:`Name` node, with a ``'load'`` ctx and will return the1113 current :class:`~jinja2.runtime.Context` object.11141115 Here an example that assigns the current template name to a1116 variable named `foo`::11171118 Assign(Name('foo', ctx='store'),1119 Getattr(ContextReference(), 'name'))11201121 This is basically equivalent to using theMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1122–1124why, one step back1122 :func:`~jinja2.pass_context` decorator when using the high-level1123 API, which causes a reference to the context to be passed as the1124 first argument to a function.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1125–1148why, one step back1125 """112611271128class DerivedContextReference(Expr):1129 """Return the current template context including locals. Behaves1130 exactly like :class:`ContextReference`, but includes local1131 variables, such as from a ``for`` loop.11321133 .. versionadded:: 2.111134 """113511361137class Continue(Stmt):1138 """Continue a loop."""113911401141class Break(Stmt):1142 """Break a loop."""114311441145class Scope(Stmt):1146 """An artificial scope."""11471148 fields = ("body",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1149why, one step back1149 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1150–1166why, one step back115011511152class OverlayScope(Stmt):1153 """An overlay scope for extensions. This is a largely unoptimized scope1154 that however can be used to introduce completely arbitrary variables into1155 a sub scope from a dictionary or dictionary like object. The `context`1156 field has to evaluate to a dictionary object.11571158 Example usage::11591160 OverlayScope(context=self.call_method('get_context'),1161 body=[...])11621163 .. versionadded:: 2.101164 """11651166 fields = ("context", "body")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1167why, one step back1167 context: ExprUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1168why, one step back1168 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1169–1180why, one step back116911701171class EvalContextModifier(Stmt):1172 """Modifies the eval context. For each option that should be modified,1173 a :class:`Keyword` has to be added to the :attr:`options` list.11741175 Example to change the `autoescape` setting::11761177 EvalContextModifier(options=[Keyword('autoescape', Const(True))])1178 """11791180 fields = ("options",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1181why, one step back1181 options: list[Keyword]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1182–1190why, one step back118211831184class ScopedEvalContextModifier(EvalContextModifier):1185 """Modifies the eval context and reverts it later. Works exactly like1186 :class:`EvalContextModifier` but will only modify the1187 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1188 """11891190 fields = ("body",)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1191why, one step back1191 body: list[Node]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1192–1194why, one step back119211931194# make sure nobody creates custom nodesMerge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 1195why, one step back1195def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1196–1200why, one step back1196 raise TypeError("can't create custom node types")119711981199NodeType.__new__ = staticmethod(_failing_new) # type: ignore1200del _failing_new