Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/__init__.py +38 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/_identifier.py +6 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/async_utils.py +84 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/bccache.py +408 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/compiler.py +1960 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/constants.py +20 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/debug.py +191 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/defaults.py +48 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/environment.py +1675 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/exceptions.py +166 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/ext.py +870 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/filters.py +1866 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/idtracking.py +318 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/loaders.py +667 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/meta.py +112 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/nativetypes.py +130 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/nodes.py +1206 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/optimizer.py +48 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/parser.py +1041 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/py.typed +0 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/runtime.py +1056 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/tests.py +256 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/utils.py +755 -0
- llmeval-env/lib/python3.10/site-packages/jinja2/visitor.py +92 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/__init__.py +13 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/coreviews.py +418 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/digraph.py +1334 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/filters.py +87 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/graph.py +2043 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/multidigraph.py +965 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_coreviews.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graph.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graphviews.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multidigraph.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_reportviews.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_special.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_subgraphviews.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py +194 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/historical_tests.py +474 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_coreviews.py +362 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_digraph.py +331 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_digraph_historical.py +110 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py +177 -0
- llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_function.py +787 -0
.gitattributes
CHANGED
@@ -68,3 +68,4 @@ llmeval-env/lib/python3.10/site-packages/scipy/misc/face.dat filter=lfs diff=lfs
|
|
68 |
llmeval-env/lib/python3.10/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
69 |
llmeval-env/lib/python3.10/site-packages/aiohttp/_http_parser.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
70 |
llmeval-env/lib/python3.10/site-packages/triton/third_party/cuda/bin/ptxas filter=lfs diff=lfs merge=lfs -text
|
|
|
|
68 |
llmeval-env/lib/python3.10/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
69 |
llmeval-env/lib/python3.10/site-packages/aiohttp/_http_parser.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
70 |
llmeval-env/lib/python3.10/site-packages/triton/third_party/cuda/bin/ptxas filter=lfs diff=lfs merge=lfs -text
|
71 |
+
llmeval-env/lib/python3.10/site-packages/triton/third_party/cuda/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
llmeval-env/lib/python3.10/site-packages/jinja2/__init__.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Jinja is a template engine written in pure Python. It provides a
|
2 |
+
non-XML syntax that supports inline expressions and an optional
|
3 |
+
sandboxed environment.
|
4 |
+
"""
|
5 |
+
|
6 |
+
from .bccache import BytecodeCache as BytecodeCache
|
7 |
+
from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache
|
8 |
+
from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache
|
9 |
+
from .environment import Environment as Environment
|
10 |
+
from .environment import Template as Template
|
11 |
+
from .exceptions import TemplateAssertionError as TemplateAssertionError
|
12 |
+
from .exceptions import TemplateError as TemplateError
|
13 |
+
from .exceptions import TemplateNotFound as TemplateNotFound
|
14 |
+
from .exceptions import TemplateRuntimeError as TemplateRuntimeError
|
15 |
+
from .exceptions import TemplatesNotFound as TemplatesNotFound
|
16 |
+
from .exceptions import TemplateSyntaxError as TemplateSyntaxError
|
17 |
+
from .exceptions import UndefinedError as UndefinedError
|
18 |
+
from .loaders import BaseLoader as BaseLoader
|
19 |
+
from .loaders import ChoiceLoader as ChoiceLoader
|
20 |
+
from .loaders import DictLoader as DictLoader
|
21 |
+
from .loaders import FileSystemLoader as FileSystemLoader
|
22 |
+
from .loaders import FunctionLoader as FunctionLoader
|
23 |
+
from .loaders import ModuleLoader as ModuleLoader
|
24 |
+
from .loaders import PackageLoader as PackageLoader
|
25 |
+
from .loaders import PrefixLoader as PrefixLoader
|
26 |
+
from .runtime import ChainableUndefined as ChainableUndefined
|
27 |
+
from .runtime import DebugUndefined as DebugUndefined
|
28 |
+
from .runtime import make_logging_undefined as make_logging_undefined
|
29 |
+
from .runtime import StrictUndefined as StrictUndefined
|
30 |
+
from .runtime import Undefined as Undefined
|
31 |
+
from .utils import clear_caches as clear_caches
|
32 |
+
from .utils import is_undefined as is_undefined
|
33 |
+
from .utils import pass_context as pass_context
|
34 |
+
from .utils import pass_environment as pass_environment
|
35 |
+
from .utils import pass_eval_context as pass_eval_context
|
36 |
+
from .utils import select_autoescape as select_autoescape
|
37 |
+
|
38 |
+
__version__ = "3.1.4"
|
llmeval-env/lib/python3.10/site-packages/jinja2/_identifier.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
# generated by scripts/generate_identifier_pattern.py
|
4 |
+
pattern = re.compile(
|
5 |
+
r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𐴤-𐽆𐴧-𐽐𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑅅𑅆𑅳𑆀-𑆂𑆳-𑇀𑇉-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌻𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑑞𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑠬-𑠺𑨁-𑨊𑨳-𑨹𑨻-𑨾𑩇𑩑-𑩛𑪊-𑪙𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𑴱-𑴶𑴺𑴼𑴽𑴿-𑵅𑵇𑶊-𑶎𑶐𑶑𑶓-𑶗𑻳-𑻶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B950
|
6 |
+
)
|
llmeval-env/lib/python3.10/site-packages/jinja2/async_utils.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import typing as t
|
3 |
+
from functools import WRAPPER_ASSIGNMENTS
|
4 |
+
from functools import wraps
|
5 |
+
|
6 |
+
from .utils import _PassArg
|
7 |
+
from .utils import pass_eval_context
|
8 |
+
|
9 |
+
V = t.TypeVar("V")
|
10 |
+
|
11 |
+
|
12 |
+
def async_variant(normal_func): # type: ignore
|
13 |
+
def decorator(async_func): # type: ignore
|
14 |
+
pass_arg = _PassArg.from_obj(normal_func)
|
15 |
+
need_eval_context = pass_arg is None
|
16 |
+
|
17 |
+
if pass_arg is _PassArg.environment:
|
18 |
+
|
19 |
+
def is_async(args: t.Any) -> bool:
|
20 |
+
return t.cast(bool, args[0].is_async)
|
21 |
+
|
22 |
+
else:
|
23 |
+
|
24 |
+
def is_async(args: t.Any) -> bool:
|
25 |
+
return t.cast(bool, args[0].environment.is_async)
|
26 |
+
|
27 |
+
# Take the doc and annotations from the sync function, but the
|
28 |
+
# name from the async function. Pallets-Sphinx-Themes
|
29 |
+
# build_function_directive expects __wrapped__ to point to the
|
30 |
+
# sync function.
|
31 |
+
async_func_attrs = ("__module__", "__name__", "__qualname__")
|
32 |
+
normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs))
|
33 |
+
|
34 |
+
@wraps(normal_func, assigned=normal_func_attrs)
|
35 |
+
@wraps(async_func, assigned=async_func_attrs, updated=())
|
36 |
+
def wrapper(*args, **kwargs): # type: ignore
|
37 |
+
b = is_async(args)
|
38 |
+
|
39 |
+
if need_eval_context:
|
40 |
+
args = args[1:]
|
41 |
+
|
42 |
+
if b:
|
43 |
+
return async_func(*args, **kwargs)
|
44 |
+
|
45 |
+
return normal_func(*args, **kwargs)
|
46 |
+
|
47 |
+
if need_eval_context:
|
48 |
+
wrapper = pass_eval_context(wrapper)
|
49 |
+
|
50 |
+
wrapper.jinja_async_variant = True # type: ignore[attr-defined]
|
51 |
+
return wrapper
|
52 |
+
|
53 |
+
return decorator
|
54 |
+
|
55 |
+
|
56 |
+
_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)}
|
57 |
+
|
58 |
+
|
59 |
+
async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
|
60 |
+
# Avoid a costly call to isawaitable
|
61 |
+
if type(value) in _common_primitives:
|
62 |
+
return t.cast("V", value)
|
63 |
+
|
64 |
+
if inspect.isawaitable(value):
|
65 |
+
return await t.cast("t.Awaitable[V]", value)
|
66 |
+
|
67 |
+
return t.cast("V", value)
|
68 |
+
|
69 |
+
|
70 |
+
async def auto_aiter(
|
71 |
+
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
72 |
+
) -> "t.AsyncIterator[V]":
|
73 |
+
if hasattr(iterable, "__aiter__"):
|
74 |
+
async for item in t.cast("t.AsyncIterable[V]", iterable):
|
75 |
+
yield item
|
76 |
+
else:
|
77 |
+
for item in iterable:
|
78 |
+
yield item
|
79 |
+
|
80 |
+
|
81 |
+
async def auto_to_list(
|
82 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
83 |
+
) -> t.List["V"]:
|
84 |
+
return [x async for x in auto_aiter(value)]
|
llmeval-env/lib/python3.10/site-packages/jinja2/bccache.py
ADDED
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The optional bytecode cache system. This is useful if you have very
|
2 |
+
complex template situations and the compilation of all those templates
|
3 |
+
slows down your application too much.
|
4 |
+
|
5 |
+
Situations where this is useful are often forking web applications that
|
6 |
+
are initialized on the first request.
|
7 |
+
"""
|
8 |
+
|
9 |
+
import errno
|
10 |
+
import fnmatch
|
11 |
+
import marshal
|
12 |
+
import os
|
13 |
+
import pickle
|
14 |
+
import stat
|
15 |
+
import sys
|
16 |
+
import tempfile
|
17 |
+
import typing as t
|
18 |
+
from hashlib import sha1
|
19 |
+
from io import BytesIO
|
20 |
+
from types import CodeType
|
21 |
+
|
22 |
+
if t.TYPE_CHECKING:
|
23 |
+
import typing_extensions as te
|
24 |
+
|
25 |
+
from .environment import Environment
|
26 |
+
|
27 |
+
class _MemcachedClient(te.Protocol):
|
28 |
+
def get(self, key: str) -> bytes: ...
|
29 |
+
|
30 |
+
def set(
|
31 |
+
self, key: str, value: bytes, timeout: t.Optional[int] = None
|
32 |
+
) -> None: ...
|
33 |
+
|
34 |
+
|
35 |
+
bc_version = 5
|
36 |
+
# Magic bytes to identify Jinja bytecode cache files. Contains the
|
37 |
+
# Python major and minor version to avoid loading incompatible bytecode
|
38 |
+
# if a project upgrades its Python version.
|
39 |
+
bc_magic = (
|
40 |
+
b"j2"
|
41 |
+
+ pickle.dumps(bc_version, 2)
|
42 |
+
+ pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)
|
43 |
+
)
|
44 |
+
|
45 |
+
|
46 |
+
class Bucket:
|
47 |
+
"""Buckets are used to store the bytecode for one template. It's created
|
48 |
+
and initialized by the bytecode cache and passed to the loading functions.
|
49 |
+
|
50 |
+
The buckets get an internal checksum from the cache assigned and use this
|
51 |
+
to automatically reject outdated cache material. Individual bytecode
|
52 |
+
cache subclasses don't have to care about cache invalidation.
|
53 |
+
"""
|
54 |
+
|
55 |
+
def __init__(self, environment: "Environment", key: str, checksum: str) -> None:
|
56 |
+
self.environment = environment
|
57 |
+
self.key = key
|
58 |
+
self.checksum = checksum
|
59 |
+
self.reset()
|
60 |
+
|
61 |
+
def reset(self) -> None:
|
62 |
+
"""Resets the bucket (unloads the bytecode)."""
|
63 |
+
self.code: t.Optional[CodeType] = None
|
64 |
+
|
65 |
+
def load_bytecode(self, f: t.BinaryIO) -> None:
|
66 |
+
"""Loads bytecode from a file or file like object."""
|
67 |
+
# make sure the magic header is correct
|
68 |
+
magic = f.read(len(bc_magic))
|
69 |
+
if magic != bc_magic:
|
70 |
+
self.reset()
|
71 |
+
return
|
72 |
+
# the source code of the file changed, we need to reload
|
73 |
+
checksum = pickle.load(f)
|
74 |
+
if self.checksum != checksum:
|
75 |
+
self.reset()
|
76 |
+
return
|
77 |
+
# if marshal_load fails then we need to reload
|
78 |
+
try:
|
79 |
+
self.code = marshal.load(f)
|
80 |
+
except (EOFError, ValueError, TypeError):
|
81 |
+
self.reset()
|
82 |
+
return
|
83 |
+
|
84 |
+
def write_bytecode(self, f: t.IO[bytes]) -> None:
|
85 |
+
"""Dump the bytecode into the file or file like object passed."""
|
86 |
+
if self.code is None:
|
87 |
+
raise TypeError("can't write empty bucket")
|
88 |
+
f.write(bc_magic)
|
89 |
+
pickle.dump(self.checksum, f, 2)
|
90 |
+
marshal.dump(self.code, f)
|
91 |
+
|
92 |
+
def bytecode_from_string(self, string: bytes) -> None:
|
93 |
+
"""Load bytecode from bytes."""
|
94 |
+
self.load_bytecode(BytesIO(string))
|
95 |
+
|
96 |
+
def bytecode_to_string(self) -> bytes:
|
97 |
+
"""Return the bytecode as bytes."""
|
98 |
+
out = BytesIO()
|
99 |
+
self.write_bytecode(out)
|
100 |
+
return out.getvalue()
|
101 |
+
|
102 |
+
|
103 |
+
class BytecodeCache:
|
104 |
+
"""To implement your own bytecode cache you have to subclass this class
|
105 |
+
and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of
|
106 |
+
these methods are passed a :class:`~jinja2.bccache.Bucket`.
|
107 |
+
|
108 |
+
A very basic bytecode cache that saves the bytecode on the file system::
|
109 |
+
|
110 |
+
from os import path
|
111 |
+
|
112 |
+
class MyCache(BytecodeCache):
|
113 |
+
|
114 |
+
def __init__(self, directory):
|
115 |
+
self.directory = directory
|
116 |
+
|
117 |
+
def load_bytecode(self, bucket):
|
118 |
+
filename = path.join(self.directory, bucket.key)
|
119 |
+
if path.exists(filename):
|
120 |
+
with open(filename, 'rb') as f:
|
121 |
+
bucket.load_bytecode(f)
|
122 |
+
|
123 |
+
def dump_bytecode(self, bucket):
|
124 |
+
filename = path.join(self.directory, bucket.key)
|
125 |
+
with open(filename, 'wb') as f:
|
126 |
+
bucket.write_bytecode(f)
|
127 |
+
|
128 |
+
A more advanced version of a filesystem based bytecode cache is part of
|
129 |
+
Jinja.
|
130 |
+
"""
|
131 |
+
|
132 |
+
def load_bytecode(self, bucket: Bucket) -> None:
|
133 |
+
"""Subclasses have to override this method to load bytecode into a
|
134 |
+
bucket. If they are not able to find code in the cache for the
|
135 |
+
bucket, it must not do anything.
|
136 |
+
"""
|
137 |
+
raise NotImplementedError()
|
138 |
+
|
139 |
+
def dump_bytecode(self, bucket: Bucket) -> None:
|
140 |
+
"""Subclasses have to override this method to write the bytecode
|
141 |
+
from a bucket back to the cache. If it unable to do so it must not
|
142 |
+
fail silently but raise an exception.
|
143 |
+
"""
|
144 |
+
raise NotImplementedError()
|
145 |
+
|
146 |
+
def clear(self) -> None:
|
147 |
+
"""Clears the cache. This method is not used by Jinja but should be
|
148 |
+
implemented to allow applications to clear the bytecode cache used
|
149 |
+
by a particular environment.
|
150 |
+
"""
|
151 |
+
|
152 |
+
def get_cache_key(
|
153 |
+
self, name: str, filename: t.Optional[t.Union[str]] = None
|
154 |
+
) -> str:
|
155 |
+
"""Returns the unique hash key for this template name."""
|
156 |
+
hash = sha1(name.encode("utf-8"))
|
157 |
+
|
158 |
+
if filename is not None:
|
159 |
+
hash.update(f"|{filename}".encode())
|
160 |
+
|
161 |
+
return hash.hexdigest()
|
162 |
+
|
163 |
+
def get_source_checksum(self, source: str) -> str:
|
164 |
+
"""Returns a checksum for the source."""
|
165 |
+
return sha1(source.encode("utf-8")).hexdigest()
|
166 |
+
|
167 |
+
def get_bucket(
|
168 |
+
self,
|
169 |
+
environment: "Environment",
|
170 |
+
name: str,
|
171 |
+
filename: t.Optional[str],
|
172 |
+
source: str,
|
173 |
+
) -> Bucket:
|
174 |
+
"""Return a cache bucket for the given template. All arguments are
|
175 |
+
mandatory but filename may be `None`.
|
176 |
+
"""
|
177 |
+
key = self.get_cache_key(name, filename)
|
178 |
+
checksum = self.get_source_checksum(source)
|
179 |
+
bucket = Bucket(environment, key, checksum)
|
180 |
+
self.load_bytecode(bucket)
|
181 |
+
return bucket
|
182 |
+
|
183 |
+
def set_bucket(self, bucket: Bucket) -> None:
|
184 |
+
"""Put the bucket into the cache."""
|
185 |
+
self.dump_bytecode(bucket)
|
186 |
+
|
187 |
+
|
188 |
+
class FileSystemBytecodeCache(BytecodeCache):
|
189 |
+
"""A bytecode cache that stores bytecode on the filesystem. It accepts
|
190 |
+
two arguments: The directory where the cache items are stored and a
|
191 |
+
pattern string that is used to build the filename.
|
192 |
+
|
193 |
+
If no directory is specified a default cache directory is selected. On
|
194 |
+
Windows the user's temp directory is used, on UNIX systems a directory
|
195 |
+
is created for the user in the system temp directory.
|
196 |
+
|
197 |
+
The pattern can be used to have multiple separate caches operate on the
|
198 |
+
same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``
|
199 |
+
is replaced with the cache key.
|
200 |
+
|
201 |
+
>>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
|
202 |
+
|
203 |
+
This bytecode cache supports clearing of the cache using the clear method.
|
204 |
+
"""
|
205 |
+
|
206 |
+
def __init__(
|
207 |
+
self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache"
|
208 |
+
) -> None:
|
209 |
+
if directory is None:
|
210 |
+
directory = self._get_default_cache_dir()
|
211 |
+
self.directory = directory
|
212 |
+
self.pattern = pattern
|
213 |
+
|
214 |
+
def _get_default_cache_dir(self) -> str:
|
215 |
+
def _unsafe_dir() -> "te.NoReturn":
|
216 |
+
raise RuntimeError(
|
217 |
+
"Cannot determine safe temp directory. You "
|
218 |
+
"need to explicitly provide one."
|
219 |
+
)
|
220 |
+
|
221 |
+
tmpdir = tempfile.gettempdir()
|
222 |
+
|
223 |
+
# On windows the temporary directory is used specific unless
|
224 |
+
# explicitly forced otherwise. We can just use that.
|
225 |
+
if os.name == "nt":
|
226 |
+
return tmpdir
|
227 |
+
if not hasattr(os, "getuid"):
|
228 |
+
_unsafe_dir()
|
229 |
+
|
230 |
+
dirname = f"_jinja2-cache-{os.getuid()}"
|
231 |
+
actual_dir = os.path.join(tmpdir, dirname)
|
232 |
+
|
233 |
+
try:
|
234 |
+
os.mkdir(actual_dir, stat.S_IRWXU)
|
235 |
+
except OSError as e:
|
236 |
+
if e.errno != errno.EEXIST:
|
237 |
+
raise
|
238 |
+
try:
|
239 |
+
os.chmod(actual_dir, stat.S_IRWXU)
|
240 |
+
actual_dir_stat = os.lstat(actual_dir)
|
241 |
+
if (
|
242 |
+
actual_dir_stat.st_uid != os.getuid()
|
243 |
+
or not stat.S_ISDIR(actual_dir_stat.st_mode)
|
244 |
+
or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU
|
245 |
+
):
|
246 |
+
_unsafe_dir()
|
247 |
+
except OSError as e:
|
248 |
+
if e.errno != errno.EEXIST:
|
249 |
+
raise
|
250 |
+
|
251 |
+
actual_dir_stat = os.lstat(actual_dir)
|
252 |
+
if (
|
253 |
+
actual_dir_stat.st_uid != os.getuid()
|
254 |
+
or not stat.S_ISDIR(actual_dir_stat.st_mode)
|
255 |
+
or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU
|
256 |
+
):
|
257 |
+
_unsafe_dir()
|
258 |
+
|
259 |
+
return actual_dir
|
260 |
+
|
261 |
+
def _get_cache_filename(self, bucket: Bucket) -> str:
|
262 |
+
return os.path.join(self.directory, self.pattern % (bucket.key,))
|
263 |
+
|
264 |
+
def load_bytecode(self, bucket: Bucket) -> None:
|
265 |
+
filename = self._get_cache_filename(bucket)
|
266 |
+
|
267 |
+
# Don't test for existence before opening the file, since the
|
268 |
+
# file could disappear after the test before the open.
|
269 |
+
try:
|
270 |
+
f = open(filename, "rb")
|
271 |
+
except (FileNotFoundError, IsADirectoryError, PermissionError):
|
272 |
+
# PermissionError can occur on Windows when an operation is
|
273 |
+
# in progress, such as calling clear().
|
274 |
+
return
|
275 |
+
|
276 |
+
with f:
|
277 |
+
bucket.load_bytecode(f)
|
278 |
+
|
279 |
+
def dump_bytecode(self, bucket: Bucket) -> None:
|
280 |
+
# Write to a temporary file, then rename to the real name after
|
281 |
+
# writing. This avoids another process reading the file before
|
282 |
+
# it is fully written.
|
283 |
+
name = self._get_cache_filename(bucket)
|
284 |
+
f = tempfile.NamedTemporaryFile(
|
285 |
+
mode="wb",
|
286 |
+
dir=os.path.dirname(name),
|
287 |
+
prefix=os.path.basename(name),
|
288 |
+
suffix=".tmp",
|
289 |
+
delete=False,
|
290 |
+
)
|
291 |
+
|
292 |
+
def remove_silent() -> None:
|
293 |
+
try:
|
294 |
+
os.remove(f.name)
|
295 |
+
except OSError:
|
296 |
+
# Another process may have called clear(). On Windows,
|
297 |
+
# another program may be holding the file open.
|
298 |
+
pass
|
299 |
+
|
300 |
+
try:
|
301 |
+
with f:
|
302 |
+
bucket.write_bytecode(f)
|
303 |
+
except BaseException:
|
304 |
+
remove_silent()
|
305 |
+
raise
|
306 |
+
|
307 |
+
try:
|
308 |
+
os.replace(f.name, name)
|
309 |
+
except OSError:
|
310 |
+
# Another process may have called clear(). On Windows,
|
311 |
+
# another program may be holding the file open.
|
312 |
+
remove_silent()
|
313 |
+
except BaseException:
|
314 |
+
remove_silent()
|
315 |
+
raise
|
316 |
+
|
317 |
+
def clear(self) -> None:
|
318 |
+
# imported lazily here because google app-engine doesn't support
|
319 |
+
# write access on the file system and the function does not exist
|
320 |
+
# normally.
|
321 |
+
from os import remove
|
322 |
+
|
323 |
+
files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))
|
324 |
+
for filename in files:
|
325 |
+
try:
|
326 |
+
remove(os.path.join(self.directory, filename))
|
327 |
+
except OSError:
|
328 |
+
pass
|
329 |
+
|
330 |
+
|
331 |
+
class MemcachedBytecodeCache(BytecodeCache):
|
332 |
+
"""This class implements a bytecode cache that uses a memcache cache for
|
333 |
+
storing the information. It does not enforce a specific memcache library
|
334 |
+
(tummy's memcache or cmemcache) but will accept any class that provides
|
335 |
+
the minimal interface required.
|
336 |
+
|
337 |
+
Libraries compatible with this class:
|
338 |
+
|
339 |
+
- `cachelib <https://github.com/pallets/cachelib>`_
|
340 |
+
- `python-memcached <https://pypi.org/project/python-memcached/>`_
|
341 |
+
|
342 |
+
(Unfortunately the django cache interface is not compatible because it
|
343 |
+
does not support storing binary data, only text. You can however pass
|
344 |
+
the underlying cache client to the bytecode cache which is available
|
345 |
+
as `django.core.cache.cache._client`.)
|
346 |
+
|
347 |
+
The minimal interface for the client passed to the constructor is this:
|
348 |
+
|
349 |
+
.. class:: MinimalClientInterface
|
350 |
+
|
351 |
+
.. method:: set(key, value[, timeout])
|
352 |
+
|
353 |
+
Stores the bytecode in the cache. `value` is a string and
|
354 |
+
`timeout` the timeout of the key. If timeout is not provided
|
355 |
+
a default timeout or no timeout should be assumed, if it's
|
356 |
+
provided it's an integer with the number of seconds the cache
|
357 |
+
item should exist.
|
358 |
+
|
359 |
+
.. method:: get(key)
|
360 |
+
|
361 |
+
Returns the value for the cache key. If the item does not
|
362 |
+
exist in the cache the return value must be `None`.
|
363 |
+
|
364 |
+
The other arguments to the constructor are the prefix for all keys that
|
365 |
+
is added before the actual cache key and the timeout for the bytecode in
|
366 |
+
the cache system. We recommend a high (or no) timeout.
|
367 |
+
|
368 |
+
This bytecode cache does not support clearing of used items in the cache.
|
369 |
+
The clear method is a no-operation function.
|
370 |
+
|
371 |
+
.. versionadded:: 2.7
|
372 |
+
Added support for ignoring memcache errors through the
|
373 |
+
`ignore_memcache_errors` parameter.
|
374 |
+
"""
|
375 |
+
|
376 |
+
def __init__(
|
377 |
+
self,
|
378 |
+
client: "_MemcachedClient",
|
379 |
+
prefix: str = "jinja2/bytecode/",
|
380 |
+
timeout: t.Optional[int] = None,
|
381 |
+
ignore_memcache_errors: bool = True,
|
382 |
+
):
|
383 |
+
self.client = client
|
384 |
+
self.prefix = prefix
|
385 |
+
self.timeout = timeout
|
386 |
+
self.ignore_memcache_errors = ignore_memcache_errors
|
387 |
+
|
388 |
+
def load_bytecode(self, bucket: Bucket) -> None:
|
389 |
+
try:
|
390 |
+
code = self.client.get(self.prefix + bucket.key)
|
391 |
+
except Exception:
|
392 |
+
if not self.ignore_memcache_errors:
|
393 |
+
raise
|
394 |
+
else:
|
395 |
+
bucket.bytecode_from_string(code)
|
396 |
+
|
397 |
+
def dump_bytecode(self, bucket: Bucket) -> None:
|
398 |
+
key = self.prefix + bucket.key
|
399 |
+
value = bucket.bytecode_to_string()
|
400 |
+
|
401 |
+
try:
|
402 |
+
if self.timeout is not None:
|
403 |
+
self.client.set(key, value, self.timeout)
|
404 |
+
else:
|
405 |
+
self.client.set(key, value)
|
406 |
+
except Exception:
|
407 |
+
if not self.ignore_memcache_errors:
|
408 |
+
raise
|
llmeval-env/lib/python3.10/site-packages/jinja2/compiler.py
ADDED
@@ -0,0 +1,1960 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Compiles nodes from the parser into Python code."""
|
2 |
+
|
3 |
+
import typing as t
|
4 |
+
from contextlib import contextmanager
|
5 |
+
from functools import update_wrapper
|
6 |
+
from io import StringIO
|
7 |
+
from itertools import chain
|
8 |
+
from keyword import iskeyword as is_python_keyword
|
9 |
+
|
10 |
+
from markupsafe import escape
|
11 |
+
from markupsafe import Markup
|
12 |
+
|
13 |
+
from . import nodes
|
14 |
+
from .exceptions import TemplateAssertionError
|
15 |
+
from .idtracking import Symbols
|
16 |
+
from .idtracking import VAR_LOAD_ALIAS
|
17 |
+
from .idtracking import VAR_LOAD_PARAMETER
|
18 |
+
from .idtracking import VAR_LOAD_RESOLVE
|
19 |
+
from .idtracking import VAR_LOAD_UNDEFINED
|
20 |
+
from .nodes import EvalContext
|
21 |
+
from .optimizer import Optimizer
|
22 |
+
from .utils import _PassArg
|
23 |
+
from .utils import concat
|
24 |
+
from .visitor import NodeVisitor
|
25 |
+
|
26 |
+
if t.TYPE_CHECKING:
|
27 |
+
import typing_extensions as te
|
28 |
+
|
29 |
+
from .environment import Environment
|
30 |
+
|
31 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
32 |
+
|
33 |
+
operators = {
|
34 |
+
"eq": "==",
|
35 |
+
"ne": "!=",
|
36 |
+
"gt": ">",
|
37 |
+
"gteq": ">=",
|
38 |
+
"lt": "<",
|
39 |
+
"lteq": "<=",
|
40 |
+
"in": "in",
|
41 |
+
"notin": "not in",
|
42 |
+
}
|
43 |
+
|
44 |
+
|
45 |
+
def optimizeconst(f: F) -> F:
|
46 |
+
def new_func(
|
47 |
+
self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any
|
48 |
+
) -> t.Any:
|
49 |
+
# Only optimize if the frame is not volatile
|
50 |
+
if self.optimizer is not None and not frame.eval_ctx.volatile:
|
51 |
+
new_node = self.optimizer.visit(node, frame.eval_ctx)
|
52 |
+
|
53 |
+
if new_node != node:
|
54 |
+
return self.visit(new_node, frame)
|
55 |
+
|
56 |
+
return f(self, node, frame, **kwargs)
|
57 |
+
|
58 |
+
return update_wrapper(t.cast(F, new_func), f)
|
59 |
+
|
60 |
+
|
61 |
+
def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:
|
62 |
+
@optimizeconst
|
63 |
+
def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:
|
64 |
+
if (
|
65 |
+
self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore
|
66 |
+
):
|
67 |
+
self.write(f"environment.call_binop(context, {op!r}, ")
|
68 |
+
self.visit(node.left, frame)
|
69 |
+
self.write(", ")
|
70 |
+
self.visit(node.right, frame)
|
71 |
+
else:
|
72 |
+
self.write("(")
|
73 |
+
self.visit(node.left, frame)
|
74 |
+
self.write(f" {op} ")
|
75 |
+
self.visit(node.right, frame)
|
76 |
+
|
77 |
+
self.write(")")
|
78 |
+
|
79 |
+
return visitor
|
80 |
+
|
81 |
+
|
82 |
+
def _make_unop(
|
83 |
+
op: str,
|
84 |
+
) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:
|
85 |
+
@optimizeconst
|
86 |
+
def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:
|
87 |
+
if (
|
88 |
+
self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore
|
89 |
+
):
|
90 |
+
self.write(f"environment.call_unop(context, {op!r}, ")
|
91 |
+
self.visit(node.node, frame)
|
92 |
+
else:
|
93 |
+
self.write("(" + op)
|
94 |
+
self.visit(node.node, frame)
|
95 |
+
|
96 |
+
self.write(")")
|
97 |
+
|
98 |
+
return visitor
|
99 |
+
|
100 |
+
|
101 |
+
def generate(
|
102 |
+
node: nodes.Template,
|
103 |
+
environment: "Environment",
|
104 |
+
name: t.Optional[str],
|
105 |
+
filename: t.Optional[str],
|
106 |
+
stream: t.Optional[t.TextIO] = None,
|
107 |
+
defer_init: bool = False,
|
108 |
+
optimized: bool = True,
|
109 |
+
) -> t.Optional[str]:
|
110 |
+
"""Generate the python source for a node tree."""
|
111 |
+
if not isinstance(node, nodes.Template):
|
112 |
+
raise TypeError("Can't compile non template nodes")
|
113 |
+
|
114 |
+
generator = environment.code_generator_class(
|
115 |
+
environment, name, filename, stream, defer_init, optimized
|
116 |
+
)
|
117 |
+
generator.visit(node)
|
118 |
+
|
119 |
+
if stream is None:
|
120 |
+
return generator.stream.getvalue() # type: ignore
|
121 |
+
|
122 |
+
return None
|
123 |
+
|
124 |
+
|
125 |
+
def has_safe_repr(value: t.Any) -> bool:
|
126 |
+
"""Does the node have a safe representation?"""
|
127 |
+
if value is None or value is NotImplemented or value is Ellipsis:
|
128 |
+
return True
|
129 |
+
|
130 |
+
if type(value) in {bool, int, float, complex, range, str, Markup}:
|
131 |
+
return True
|
132 |
+
|
133 |
+
if type(value) in {tuple, list, set, frozenset}:
|
134 |
+
return all(has_safe_repr(v) for v in value)
|
135 |
+
|
136 |
+
if type(value) is dict: # noqa E721
|
137 |
+
return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())
|
138 |
+
|
139 |
+
return False
|
140 |
+
|
141 |
+
|
142 |
+
def find_undeclared(
|
143 |
+
nodes: t.Iterable[nodes.Node], names: t.Iterable[str]
|
144 |
+
) -> t.Set[str]:
|
145 |
+
"""Check if the names passed are accessed undeclared. The return value
|
146 |
+
is a set of all the undeclared names from the sequence of names found.
|
147 |
+
"""
|
148 |
+
visitor = UndeclaredNameVisitor(names)
|
149 |
+
try:
|
150 |
+
for node in nodes:
|
151 |
+
visitor.visit(node)
|
152 |
+
except VisitorExit:
|
153 |
+
pass
|
154 |
+
return visitor.undeclared
|
155 |
+
|
156 |
+
|
157 |
+
class MacroRef:
|
158 |
+
def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None:
|
159 |
+
self.node = node
|
160 |
+
self.accesses_caller = False
|
161 |
+
self.accesses_kwargs = False
|
162 |
+
self.accesses_varargs = False
|
163 |
+
|
164 |
+
|
165 |
+
class Frame:
|
166 |
+
"""Holds compile time information for us."""
|
167 |
+
|
168 |
+
def __init__(
|
169 |
+
self,
|
170 |
+
eval_ctx: EvalContext,
|
171 |
+
parent: t.Optional["Frame"] = None,
|
172 |
+
level: t.Optional[int] = None,
|
173 |
+
) -> None:
|
174 |
+
self.eval_ctx = eval_ctx
|
175 |
+
|
176 |
+
# the parent of this frame
|
177 |
+
self.parent = parent
|
178 |
+
|
179 |
+
if parent is None:
|
180 |
+
self.symbols = Symbols(level=level)
|
181 |
+
|
182 |
+
# in some dynamic inheritance situations the compiler needs to add
|
183 |
+
# write tests around output statements.
|
184 |
+
self.require_output_check = False
|
185 |
+
|
186 |
+
# inside some tags we are using a buffer rather than yield statements.
|
187 |
+
# this for example affects {% filter %} or {% macro %}. If a frame
|
188 |
+
# is buffered this variable points to the name of the list used as
|
189 |
+
# buffer.
|
190 |
+
self.buffer: t.Optional[str] = None
|
191 |
+
|
192 |
+
# the name of the block we're in, otherwise None.
|
193 |
+
self.block: t.Optional[str] = None
|
194 |
+
|
195 |
+
else:
|
196 |
+
self.symbols = Symbols(parent.symbols, level=level)
|
197 |
+
self.require_output_check = parent.require_output_check
|
198 |
+
self.buffer = parent.buffer
|
199 |
+
self.block = parent.block
|
200 |
+
|
201 |
+
# a toplevel frame is the root + soft frames such as if conditions.
|
202 |
+
self.toplevel = False
|
203 |
+
|
204 |
+
# the root frame is basically just the outermost frame, so no if
|
205 |
+
# conditions. This information is used to optimize inheritance
|
206 |
+
# situations.
|
207 |
+
self.rootlevel = False
|
208 |
+
|
209 |
+
# variables set inside of loops and blocks should not affect outer frames,
|
210 |
+
# but they still needs to be kept track of as part of the active context.
|
211 |
+
self.loop_frame = False
|
212 |
+
self.block_frame = False
|
213 |
+
|
214 |
+
# track whether the frame is being used in an if-statement or conditional
|
215 |
+
# expression as it determines which errors should be raised during runtime
|
216 |
+
# or compile time.
|
217 |
+
self.soft_frame = False
|
218 |
+
|
219 |
+
def copy(self) -> "Frame":
|
220 |
+
"""Create a copy of the current one."""
|
221 |
+
rv = object.__new__(self.__class__)
|
222 |
+
rv.__dict__.update(self.__dict__)
|
223 |
+
rv.symbols = self.symbols.copy()
|
224 |
+
return rv
|
225 |
+
|
226 |
+
def inner(self, isolated: bool = False) -> "Frame":
|
227 |
+
"""Return an inner frame."""
|
228 |
+
if isolated:
|
229 |
+
return Frame(self.eval_ctx, level=self.symbols.level + 1)
|
230 |
+
return Frame(self.eval_ctx, self)
|
231 |
+
|
232 |
+
def soft(self) -> "Frame":
|
233 |
+
"""Return a soft frame. A soft frame may not be modified as
|
234 |
+
standalone thing as it shares the resources with the frame it
|
235 |
+
was created of, but it's not a rootlevel frame any longer.
|
236 |
+
|
237 |
+
This is only used to implement if-statements and conditional
|
238 |
+
expressions.
|
239 |
+
"""
|
240 |
+
rv = self.copy()
|
241 |
+
rv.rootlevel = False
|
242 |
+
rv.soft_frame = True
|
243 |
+
return rv
|
244 |
+
|
245 |
+
__copy__ = copy
|
246 |
+
|
247 |
+
|
248 |
+
class VisitorExit(RuntimeError):
|
249 |
+
"""Exception used by the `UndeclaredNameVisitor` to signal a stop."""
|
250 |
+
|
251 |
+
|
252 |
+
class DependencyFinderVisitor(NodeVisitor):
|
253 |
+
"""A visitor that collects filter and test calls."""
|
254 |
+
|
255 |
+
def __init__(self) -> None:
|
256 |
+
self.filters: t.Set[str] = set()
|
257 |
+
self.tests: t.Set[str] = set()
|
258 |
+
|
259 |
+
def visit_Filter(self, node: nodes.Filter) -> None:
|
260 |
+
self.generic_visit(node)
|
261 |
+
self.filters.add(node.name)
|
262 |
+
|
263 |
+
def visit_Test(self, node: nodes.Test) -> None:
|
264 |
+
self.generic_visit(node)
|
265 |
+
self.tests.add(node.name)
|
266 |
+
|
267 |
+
def visit_Block(self, node: nodes.Block) -> None:
|
268 |
+
"""Stop visiting at blocks."""
|
269 |
+
|
270 |
+
|
271 |
+
class UndeclaredNameVisitor(NodeVisitor):
|
272 |
+
"""A visitor that checks if a name is accessed without being
|
273 |
+
declared. This is different from the frame visitor as it will
|
274 |
+
not stop at closure frames.
|
275 |
+
"""
|
276 |
+
|
277 |
+
def __init__(self, names: t.Iterable[str]) -> None:
|
278 |
+
self.names = set(names)
|
279 |
+
self.undeclared: t.Set[str] = set()
|
280 |
+
|
281 |
+
def visit_Name(self, node: nodes.Name) -> None:
|
282 |
+
if node.ctx == "load" and node.name in self.names:
|
283 |
+
self.undeclared.add(node.name)
|
284 |
+
if self.undeclared == self.names:
|
285 |
+
raise VisitorExit()
|
286 |
+
else:
|
287 |
+
self.names.discard(node.name)
|
288 |
+
|
289 |
+
def visit_Block(self, node: nodes.Block) -> None:
|
290 |
+
"""Stop visiting a blocks."""
|
291 |
+
|
292 |
+
|
293 |
+
class CompilerExit(Exception):
|
294 |
+
"""Raised if the compiler encountered a situation where it just
|
295 |
+
doesn't make sense to further process the code. Any block that
|
296 |
+
raises such an exception is not further processed.
|
297 |
+
"""
|
298 |
+
|
299 |
+
|
300 |
+
class CodeGenerator(NodeVisitor):
|
301 |
+
def __init__(
|
302 |
+
self,
|
303 |
+
environment: "Environment",
|
304 |
+
name: t.Optional[str],
|
305 |
+
filename: t.Optional[str],
|
306 |
+
stream: t.Optional[t.TextIO] = None,
|
307 |
+
defer_init: bool = False,
|
308 |
+
optimized: bool = True,
|
309 |
+
) -> None:
|
310 |
+
if stream is None:
|
311 |
+
stream = StringIO()
|
312 |
+
self.environment = environment
|
313 |
+
self.name = name
|
314 |
+
self.filename = filename
|
315 |
+
self.stream = stream
|
316 |
+
self.created_block_context = False
|
317 |
+
self.defer_init = defer_init
|
318 |
+
self.optimizer: t.Optional[Optimizer] = None
|
319 |
+
|
320 |
+
if optimized:
|
321 |
+
self.optimizer = Optimizer(environment)
|
322 |
+
|
323 |
+
# aliases for imports
|
324 |
+
self.import_aliases: t.Dict[str, str] = {}
|
325 |
+
|
326 |
+
# a registry for all blocks. Because blocks are moved out
|
327 |
+
# into the global python scope they are registered here
|
328 |
+
self.blocks: t.Dict[str, nodes.Block] = {}
|
329 |
+
|
330 |
+
# the number of extends statements so far
|
331 |
+
self.extends_so_far = 0
|
332 |
+
|
333 |
+
# some templates have a rootlevel extends. In this case we
|
334 |
+
# can safely assume that we're a child template and do some
|
335 |
+
# more optimizations.
|
336 |
+
self.has_known_extends = False
|
337 |
+
|
338 |
+
# the current line number
|
339 |
+
self.code_lineno = 1
|
340 |
+
|
341 |
+
# registry of all filters and tests (global, not block local)
|
342 |
+
self.tests: t.Dict[str, str] = {}
|
343 |
+
self.filters: t.Dict[str, str] = {}
|
344 |
+
|
345 |
+
# the debug information
|
346 |
+
self.debug_info: t.List[t.Tuple[int, int]] = []
|
347 |
+
self._write_debug_info: t.Optional[int] = None
|
348 |
+
|
349 |
+
# the number of new lines before the next write()
|
350 |
+
self._new_lines = 0
|
351 |
+
|
352 |
+
# the line number of the last written statement
|
353 |
+
self._last_line = 0
|
354 |
+
|
355 |
+
# true if nothing was written so far.
|
356 |
+
self._first_write = True
|
357 |
+
|
358 |
+
# used by the `temporary_identifier` method to get new
|
359 |
+
# unique, temporary identifier
|
360 |
+
self._last_identifier = 0
|
361 |
+
|
362 |
+
# the current indentation
|
363 |
+
self._indentation = 0
|
364 |
+
|
365 |
+
# Tracks toplevel assignments
|
366 |
+
self._assign_stack: t.List[t.Set[str]] = []
|
367 |
+
|
368 |
+
# Tracks parameter definition blocks
|
369 |
+
self._param_def_block: t.List[t.Set[str]] = []
|
370 |
+
|
371 |
+
# Tracks the current context.
|
372 |
+
self._context_reference_stack = ["context"]
|
373 |
+
|
374 |
+
@property
|
375 |
+
def optimized(self) -> bool:
|
376 |
+
return self.optimizer is not None
|
377 |
+
|
378 |
+
# -- Various compilation helpers
|
379 |
+
|
380 |
+
def fail(self, msg: str, lineno: int) -> "te.NoReturn":
|
381 |
+
"""Fail with a :exc:`TemplateAssertionError`."""
|
382 |
+
raise TemplateAssertionError(msg, lineno, self.name, self.filename)
|
383 |
+
|
384 |
+
def temporary_identifier(self) -> str:
|
385 |
+
"""Get a new unique identifier."""
|
386 |
+
self._last_identifier += 1
|
387 |
+
return f"t_{self._last_identifier}"
|
388 |
+
|
389 |
+
def buffer(self, frame: Frame) -> None:
|
390 |
+
"""Enable buffering for the frame from that point onwards."""
|
391 |
+
frame.buffer = self.temporary_identifier()
|
392 |
+
self.writeline(f"{frame.buffer} = []")
|
393 |
+
|
394 |
+
def return_buffer_contents(
|
395 |
+
self, frame: Frame, force_unescaped: bool = False
|
396 |
+
) -> None:
|
397 |
+
"""Return the buffer contents of the frame."""
|
398 |
+
if not force_unescaped:
|
399 |
+
if frame.eval_ctx.volatile:
|
400 |
+
self.writeline("if context.eval_ctx.autoescape:")
|
401 |
+
self.indent()
|
402 |
+
self.writeline(f"return Markup(concat({frame.buffer}))")
|
403 |
+
self.outdent()
|
404 |
+
self.writeline("else:")
|
405 |
+
self.indent()
|
406 |
+
self.writeline(f"return concat({frame.buffer})")
|
407 |
+
self.outdent()
|
408 |
+
return
|
409 |
+
elif frame.eval_ctx.autoescape:
|
410 |
+
self.writeline(f"return Markup(concat({frame.buffer}))")
|
411 |
+
return
|
412 |
+
self.writeline(f"return concat({frame.buffer})")
|
413 |
+
|
414 |
+
def indent(self) -> None:
|
415 |
+
"""Indent by one."""
|
416 |
+
self._indentation += 1
|
417 |
+
|
418 |
+
def outdent(self, step: int = 1) -> None:
|
419 |
+
"""Outdent by step."""
|
420 |
+
self._indentation -= step
|
421 |
+
|
422 |
+
def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None:
|
423 |
+
"""Yield or write into the frame buffer."""
|
424 |
+
if frame.buffer is None:
|
425 |
+
self.writeline("yield ", node)
|
426 |
+
else:
|
427 |
+
self.writeline(f"{frame.buffer}.append(", node)
|
428 |
+
|
429 |
+
def end_write(self, frame: Frame) -> None:
|
430 |
+
"""End the writing process started by `start_write`."""
|
431 |
+
if frame.buffer is not None:
|
432 |
+
self.write(")")
|
433 |
+
|
434 |
+
def simple_write(
|
435 |
+
self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None
|
436 |
+
) -> None:
|
437 |
+
"""Simple shortcut for start_write + write + end_write."""
|
438 |
+
self.start_write(frame, node)
|
439 |
+
self.write(s)
|
440 |
+
self.end_write(frame)
|
441 |
+
|
442 |
+
def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None:
|
443 |
+
"""Visit a list of nodes as block in a frame. If the current frame
|
444 |
+
is no buffer a dummy ``if 0: yield None`` is written automatically.
|
445 |
+
"""
|
446 |
+
try:
|
447 |
+
self.writeline("pass")
|
448 |
+
for node in nodes:
|
449 |
+
self.visit(node, frame)
|
450 |
+
except CompilerExit:
|
451 |
+
pass
|
452 |
+
|
453 |
+
def write(self, x: str) -> None:
|
454 |
+
"""Write a string into the output stream."""
|
455 |
+
if self._new_lines:
|
456 |
+
if not self._first_write:
|
457 |
+
self.stream.write("\n" * self._new_lines)
|
458 |
+
self.code_lineno += self._new_lines
|
459 |
+
if self._write_debug_info is not None:
|
460 |
+
self.debug_info.append((self._write_debug_info, self.code_lineno))
|
461 |
+
self._write_debug_info = None
|
462 |
+
self._first_write = False
|
463 |
+
self.stream.write(" " * self._indentation)
|
464 |
+
self._new_lines = 0
|
465 |
+
self.stream.write(x)
|
466 |
+
|
467 |
+
def writeline(
|
468 |
+
self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0
|
469 |
+
) -> None:
|
470 |
+
"""Combination of newline and write."""
|
471 |
+
self.newline(node, extra)
|
472 |
+
self.write(x)
|
473 |
+
|
474 |
+
def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None:
|
475 |
+
"""Add one or more newlines before the next write."""
|
476 |
+
self._new_lines = max(self._new_lines, 1 + extra)
|
477 |
+
if node is not None and node.lineno != self._last_line:
|
478 |
+
self._write_debug_info = node.lineno
|
479 |
+
self._last_line = node.lineno
|
480 |
+
|
481 |
+
def signature(
|
482 |
+
self,
|
483 |
+
node: t.Union[nodes.Call, nodes.Filter, nodes.Test],
|
484 |
+
frame: Frame,
|
485 |
+
extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
|
486 |
+
) -> None:
|
487 |
+
"""Writes a function call to the stream for the current node.
|
488 |
+
A leading comma is added automatically. The extra keyword
|
489 |
+
arguments may not include python keywords otherwise a syntax
|
490 |
+
error could occur. The extra keyword arguments should be given
|
491 |
+
as python dict.
|
492 |
+
"""
|
493 |
+
# if any of the given keyword arguments is a python keyword
|
494 |
+
# we have to make sure that no invalid call is created.
|
495 |
+
kwarg_workaround = any(
|
496 |
+
is_python_keyword(t.cast(str, k))
|
497 |
+
for k in chain((x.key for x in node.kwargs), extra_kwargs or ())
|
498 |
+
)
|
499 |
+
|
500 |
+
for arg in node.args:
|
501 |
+
self.write(", ")
|
502 |
+
self.visit(arg, frame)
|
503 |
+
|
504 |
+
if not kwarg_workaround:
|
505 |
+
for kwarg in node.kwargs:
|
506 |
+
self.write(", ")
|
507 |
+
self.visit(kwarg, frame)
|
508 |
+
if extra_kwargs is not None:
|
509 |
+
for key, value in extra_kwargs.items():
|
510 |
+
self.write(f", {key}={value}")
|
511 |
+
if node.dyn_args:
|
512 |
+
self.write(", *")
|
513 |
+
self.visit(node.dyn_args, frame)
|
514 |
+
|
515 |
+
if kwarg_workaround:
|
516 |
+
if node.dyn_kwargs is not None:
|
517 |
+
self.write(", **dict({")
|
518 |
+
else:
|
519 |
+
self.write(", **{")
|
520 |
+
for kwarg in node.kwargs:
|
521 |
+
self.write(f"{kwarg.key!r}: ")
|
522 |
+
self.visit(kwarg.value, frame)
|
523 |
+
self.write(", ")
|
524 |
+
if extra_kwargs is not None:
|
525 |
+
for key, value in extra_kwargs.items():
|
526 |
+
self.write(f"{key!r}: {value}, ")
|
527 |
+
if node.dyn_kwargs is not None:
|
528 |
+
self.write("}, **")
|
529 |
+
self.visit(node.dyn_kwargs, frame)
|
530 |
+
self.write(")")
|
531 |
+
else:
|
532 |
+
self.write("}")
|
533 |
+
|
534 |
+
elif node.dyn_kwargs is not None:
|
535 |
+
self.write(", **")
|
536 |
+
self.visit(node.dyn_kwargs, frame)
|
537 |
+
|
538 |
+
def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None:
|
539 |
+
"""Find all filter and test names used in the template and
|
540 |
+
assign them to variables in the compiled namespace. Checking
|
541 |
+
that the names are registered with the environment is done when
|
542 |
+
compiling the Filter and Test nodes. If the node is in an If or
|
543 |
+
CondExpr node, the check is done at runtime instead.
|
544 |
+
|
545 |
+
.. versionchanged:: 3.0
|
546 |
+
Filters and tests in If and CondExpr nodes are checked at
|
547 |
+
runtime instead of compile time.
|
548 |
+
"""
|
549 |
+
visitor = DependencyFinderVisitor()
|
550 |
+
|
551 |
+
for node in nodes:
|
552 |
+
visitor.visit(node)
|
553 |
+
|
554 |
+
for id_map, names, dependency in (
|
555 |
+
(self.filters, visitor.filters, "filters"),
|
556 |
+
(
|
557 |
+
self.tests,
|
558 |
+
visitor.tests,
|
559 |
+
"tests",
|
560 |
+
),
|
561 |
+
):
|
562 |
+
for name in sorted(names):
|
563 |
+
if name not in id_map:
|
564 |
+
id_map[name] = self.temporary_identifier()
|
565 |
+
|
566 |
+
# add check during runtime that dependencies used inside of executed
|
567 |
+
# blocks are defined, as this step may be skipped during compile time
|
568 |
+
self.writeline("try:")
|
569 |
+
self.indent()
|
570 |
+
self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]")
|
571 |
+
self.outdent()
|
572 |
+
self.writeline("except KeyError:")
|
573 |
+
self.indent()
|
574 |
+
self.writeline("@internalcode")
|
575 |
+
self.writeline(f"def {id_map[name]}(*unused):")
|
576 |
+
self.indent()
|
577 |
+
self.writeline(
|
578 |
+
f'raise TemplateRuntimeError("No {dependency[:-1]}'
|
579 |
+
f' named {name!r} found.")'
|
580 |
+
)
|
581 |
+
self.outdent()
|
582 |
+
self.outdent()
|
583 |
+
|
584 |
+
def enter_frame(self, frame: Frame) -> None:
|
585 |
+
undefs = []
|
586 |
+
for target, (action, param) in frame.symbols.loads.items():
|
587 |
+
if action == VAR_LOAD_PARAMETER:
|
588 |
+
pass
|
589 |
+
elif action == VAR_LOAD_RESOLVE:
|
590 |
+
self.writeline(f"{target} = {self.get_resolve_func()}({param!r})")
|
591 |
+
elif action == VAR_LOAD_ALIAS:
|
592 |
+
self.writeline(f"{target} = {param}")
|
593 |
+
elif action == VAR_LOAD_UNDEFINED:
|
594 |
+
undefs.append(target)
|
595 |
+
else:
|
596 |
+
raise NotImplementedError("unknown load instruction")
|
597 |
+
if undefs:
|
598 |
+
self.writeline(f"{' = '.join(undefs)} = missing")
|
599 |
+
|
600 |
+
def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None:
|
601 |
+
if not with_python_scope:
|
602 |
+
undefs = []
|
603 |
+
for target in frame.symbols.loads:
|
604 |
+
undefs.append(target)
|
605 |
+
if undefs:
|
606 |
+
self.writeline(f"{' = '.join(undefs)} = missing")
|
607 |
+
|
608 |
+
def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str:
|
609 |
+
return async_value if self.environment.is_async else sync_value
|
610 |
+
|
611 |
+
def func(self, name: str) -> str:
|
612 |
+
return f"{self.choose_async()}def {name}"
|
613 |
+
|
614 |
+
def macro_body(
|
615 |
+
self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame
|
616 |
+
) -> t.Tuple[Frame, MacroRef]:
|
617 |
+
"""Dump the function def of a macro or call block."""
|
618 |
+
frame = frame.inner()
|
619 |
+
frame.symbols.analyze_node(node)
|
620 |
+
macro_ref = MacroRef(node)
|
621 |
+
|
622 |
+
explicit_caller = None
|
623 |
+
skip_special_params = set()
|
624 |
+
args = []
|
625 |
+
|
626 |
+
for idx, arg in enumerate(node.args):
|
627 |
+
if arg.name == "caller":
|
628 |
+
explicit_caller = idx
|
629 |
+
if arg.name in ("kwargs", "varargs"):
|
630 |
+
skip_special_params.add(arg.name)
|
631 |
+
args.append(frame.symbols.ref(arg.name))
|
632 |
+
|
633 |
+
undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))
|
634 |
+
|
635 |
+
if "caller" in undeclared:
|
636 |
+
# In older Jinja versions there was a bug that allowed caller
|
637 |
+
# to retain the special behavior even if it was mentioned in
|
638 |
+
# the argument list. However thankfully this was only really
|
639 |
+
# working if it was the last argument. So we are explicitly
|
640 |
+
# checking this now and error out if it is anywhere else in
|
641 |
+
# the argument list.
|
642 |
+
if explicit_caller is not None:
|
643 |
+
try:
|
644 |
+
node.defaults[explicit_caller - len(node.args)]
|
645 |
+
except IndexError:
|
646 |
+
self.fail(
|
647 |
+
"When defining macros or call blocks the "
|
648 |
+
'special "caller" argument must be omitted '
|
649 |
+
"or be given a default.",
|
650 |
+
node.lineno,
|
651 |
+
)
|
652 |
+
else:
|
653 |
+
args.append(frame.symbols.declare_parameter("caller"))
|
654 |
+
macro_ref.accesses_caller = True
|
655 |
+
if "kwargs" in undeclared and "kwargs" not in skip_special_params:
|
656 |
+
args.append(frame.symbols.declare_parameter("kwargs"))
|
657 |
+
macro_ref.accesses_kwargs = True
|
658 |
+
if "varargs" in undeclared and "varargs" not in skip_special_params:
|
659 |
+
args.append(frame.symbols.declare_parameter("varargs"))
|
660 |
+
macro_ref.accesses_varargs = True
|
661 |
+
|
662 |
+
# macros are delayed, they never require output checks
|
663 |
+
frame.require_output_check = False
|
664 |
+
frame.symbols.analyze_node(node)
|
665 |
+
self.writeline(f"{self.func('macro')}({', '.join(args)}):", node)
|
666 |
+
self.indent()
|
667 |
+
|
668 |
+
self.buffer(frame)
|
669 |
+
self.enter_frame(frame)
|
670 |
+
|
671 |
+
self.push_parameter_definitions(frame)
|
672 |
+
for idx, arg in enumerate(node.args):
|
673 |
+
ref = frame.symbols.ref(arg.name)
|
674 |
+
self.writeline(f"if {ref} is missing:")
|
675 |
+
self.indent()
|
676 |
+
try:
|
677 |
+
default = node.defaults[idx - len(node.args)]
|
678 |
+
except IndexError:
|
679 |
+
self.writeline(
|
680 |
+
f'{ref} = undefined("parameter {arg.name!r} was not provided",'
|
681 |
+
f" name={arg.name!r})"
|
682 |
+
)
|
683 |
+
else:
|
684 |
+
self.writeline(f"{ref} = ")
|
685 |
+
self.visit(default, frame)
|
686 |
+
self.mark_parameter_stored(ref)
|
687 |
+
self.outdent()
|
688 |
+
self.pop_parameter_definitions()
|
689 |
+
|
690 |
+
self.blockvisit(node.body, frame)
|
691 |
+
self.return_buffer_contents(frame, force_unescaped=True)
|
692 |
+
self.leave_frame(frame, with_python_scope=True)
|
693 |
+
self.outdent()
|
694 |
+
|
695 |
+
return frame, macro_ref
|
696 |
+
|
697 |
+
def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None:
|
698 |
+
"""Dump the macro definition for the def created by macro_body."""
|
699 |
+
arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)
|
700 |
+
name = getattr(macro_ref.node, "name", None)
|
701 |
+
if len(macro_ref.node.args) == 1:
|
702 |
+
arg_tuple += ","
|
703 |
+
self.write(
|
704 |
+
f"Macro(environment, macro, {name!r}, ({arg_tuple}),"
|
705 |
+
f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"
|
706 |
+
f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"
|
707 |
+
)
|
708 |
+
|
709 |
+
def position(self, node: nodes.Node) -> str:
|
710 |
+
"""Return a human readable position for the node."""
|
711 |
+
rv = f"line {node.lineno}"
|
712 |
+
if self.name is not None:
|
713 |
+
rv = f"{rv} in {self.name!r}"
|
714 |
+
return rv
|
715 |
+
|
716 |
+
def dump_local_context(self, frame: Frame) -> str:
|
717 |
+
items_kv = ", ".join(
|
718 |
+
f"{name!r}: {target}"
|
719 |
+
for name, target in frame.symbols.dump_stores().items()
|
720 |
+
)
|
721 |
+
return f"{{{items_kv}}}"
|
722 |
+
|
723 |
+
def write_commons(self) -> None:
|
724 |
+
"""Writes a common preamble that is used by root and block functions.
|
725 |
+
Primarily this sets up common local helpers and enforces a generator
|
726 |
+
through a dead branch.
|
727 |
+
"""
|
728 |
+
self.writeline("resolve = context.resolve_or_missing")
|
729 |
+
self.writeline("undefined = environment.undefined")
|
730 |
+
self.writeline("concat = environment.concat")
|
731 |
+
# always use the standard Undefined class for the implicit else of
|
732 |
+
# conditional expressions
|
733 |
+
self.writeline("cond_expr_undefined = Undefined")
|
734 |
+
self.writeline("if 0: yield None")
|
735 |
+
|
736 |
+
def push_parameter_definitions(self, frame: Frame) -> None:
|
737 |
+
"""Pushes all parameter targets from the given frame into a local
|
738 |
+
stack that permits tracking of yet to be assigned parameters. In
|
739 |
+
particular this enables the optimization from `visit_Name` to skip
|
740 |
+
undefined expressions for parameters in macros as macros can reference
|
741 |
+
otherwise unbound parameters.
|
742 |
+
"""
|
743 |
+
self._param_def_block.append(frame.symbols.dump_param_targets())
|
744 |
+
|
745 |
+
def pop_parameter_definitions(self) -> None:
|
746 |
+
"""Pops the current parameter definitions set."""
|
747 |
+
self._param_def_block.pop()
|
748 |
+
|
749 |
+
def mark_parameter_stored(self, target: str) -> None:
|
750 |
+
"""Marks a parameter in the current parameter definitions as stored.
|
751 |
+
This will skip the enforced undefined checks.
|
752 |
+
"""
|
753 |
+
if self._param_def_block:
|
754 |
+
self._param_def_block[-1].discard(target)
|
755 |
+
|
756 |
+
def push_context_reference(self, target: str) -> None:
|
757 |
+
self._context_reference_stack.append(target)
|
758 |
+
|
759 |
+
def pop_context_reference(self) -> None:
|
760 |
+
self._context_reference_stack.pop()
|
761 |
+
|
762 |
+
def get_context_ref(self) -> str:
|
763 |
+
return self._context_reference_stack[-1]
|
764 |
+
|
765 |
+
def get_resolve_func(self) -> str:
|
766 |
+
target = self._context_reference_stack[-1]
|
767 |
+
if target == "context":
|
768 |
+
return "resolve"
|
769 |
+
return f"{target}.resolve"
|
770 |
+
|
771 |
+
def derive_context(self, frame: Frame) -> str:
|
772 |
+
return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"
|
773 |
+
|
774 |
+
def parameter_is_undeclared(self, target: str) -> bool:
|
775 |
+
"""Checks if a given target is an undeclared parameter."""
|
776 |
+
if not self._param_def_block:
|
777 |
+
return False
|
778 |
+
return target in self._param_def_block[-1]
|
779 |
+
|
780 |
+
def push_assign_tracking(self) -> None:
|
781 |
+
"""Pushes a new layer for assignment tracking."""
|
782 |
+
self._assign_stack.append(set())
|
783 |
+
|
784 |
+
def pop_assign_tracking(self, frame: Frame) -> None:
|
785 |
+
"""Pops the topmost level for assignment tracking and updates the
|
786 |
+
context variables if necessary.
|
787 |
+
"""
|
788 |
+
vars = self._assign_stack.pop()
|
789 |
+
if (
|
790 |
+
not frame.block_frame
|
791 |
+
and not frame.loop_frame
|
792 |
+
and not frame.toplevel
|
793 |
+
or not vars
|
794 |
+
):
|
795 |
+
return
|
796 |
+
public_names = [x for x in vars if x[:1] != "_"]
|
797 |
+
if len(vars) == 1:
|
798 |
+
name = next(iter(vars))
|
799 |
+
ref = frame.symbols.ref(name)
|
800 |
+
if frame.loop_frame:
|
801 |
+
self.writeline(f"_loop_vars[{name!r}] = {ref}")
|
802 |
+
return
|
803 |
+
if frame.block_frame:
|
804 |
+
self.writeline(f"_block_vars[{name!r}] = {ref}")
|
805 |
+
return
|
806 |
+
self.writeline(f"context.vars[{name!r}] = {ref}")
|
807 |
+
else:
|
808 |
+
if frame.loop_frame:
|
809 |
+
self.writeline("_loop_vars.update({")
|
810 |
+
elif frame.block_frame:
|
811 |
+
self.writeline("_block_vars.update({")
|
812 |
+
else:
|
813 |
+
self.writeline("context.vars.update({")
|
814 |
+
for idx, name in enumerate(vars):
|
815 |
+
if idx:
|
816 |
+
self.write(", ")
|
817 |
+
ref = frame.symbols.ref(name)
|
818 |
+
self.write(f"{name!r}: {ref}")
|
819 |
+
self.write("})")
|
820 |
+
if not frame.block_frame and not frame.loop_frame and public_names:
|
821 |
+
if len(public_names) == 1:
|
822 |
+
self.writeline(f"context.exported_vars.add({public_names[0]!r})")
|
823 |
+
else:
|
824 |
+
names_str = ", ".join(map(repr, public_names))
|
825 |
+
self.writeline(f"context.exported_vars.update(({names_str}))")
|
826 |
+
|
827 |
+
# -- Statement Visitors
|
828 |
+
|
829 |
+
def visit_Template(
|
830 |
+
self, node: nodes.Template, frame: t.Optional[Frame] = None
|
831 |
+
) -> None:
|
832 |
+
assert frame is None, "no root frame allowed"
|
833 |
+
eval_ctx = EvalContext(self.environment, self.name)
|
834 |
+
|
835 |
+
from .runtime import async_exported
|
836 |
+
from .runtime import exported
|
837 |
+
|
838 |
+
if self.environment.is_async:
|
839 |
+
exported_names = sorted(exported + async_exported)
|
840 |
+
else:
|
841 |
+
exported_names = sorted(exported)
|
842 |
+
|
843 |
+
self.writeline("from jinja2.runtime import " + ", ".join(exported_names))
|
844 |
+
|
845 |
+
# if we want a deferred initialization we cannot move the
|
846 |
+
# environment into a local name
|
847 |
+
envenv = "" if self.defer_init else ", environment=environment"
|
848 |
+
|
849 |
+
# do we have an extends tag at all? If not, we can save some
|
850 |
+
# overhead by just not processing any inheritance code.
|
851 |
+
have_extends = node.find(nodes.Extends) is not None
|
852 |
+
|
853 |
+
# find all blocks
|
854 |
+
for block in node.find_all(nodes.Block):
|
855 |
+
if block.name in self.blocks:
|
856 |
+
self.fail(f"block {block.name!r} defined twice", block.lineno)
|
857 |
+
self.blocks[block.name] = block
|
858 |
+
|
859 |
+
# find all imports and import them
|
860 |
+
for import_ in node.find_all(nodes.ImportedName):
|
861 |
+
if import_.importname not in self.import_aliases:
|
862 |
+
imp = import_.importname
|
863 |
+
self.import_aliases[imp] = alias = self.temporary_identifier()
|
864 |
+
if "." in imp:
|
865 |
+
module, obj = imp.rsplit(".", 1)
|
866 |
+
self.writeline(f"from {module} import {obj} as {alias}")
|
867 |
+
else:
|
868 |
+
self.writeline(f"import {imp} as {alias}")
|
869 |
+
|
870 |
+
# add the load name
|
871 |
+
self.writeline(f"name = {self.name!r}")
|
872 |
+
|
873 |
+
# generate the root render function.
|
874 |
+
self.writeline(
|
875 |
+
f"{self.func('root')}(context, missing=missing{envenv}):", extra=1
|
876 |
+
)
|
877 |
+
self.indent()
|
878 |
+
self.write_commons()
|
879 |
+
|
880 |
+
# process the root
|
881 |
+
frame = Frame(eval_ctx)
|
882 |
+
if "self" in find_undeclared(node.body, ("self",)):
|
883 |
+
ref = frame.symbols.declare_parameter("self")
|
884 |
+
self.writeline(f"{ref} = TemplateReference(context)")
|
885 |
+
frame.symbols.analyze_node(node)
|
886 |
+
frame.toplevel = frame.rootlevel = True
|
887 |
+
frame.require_output_check = have_extends and not self.has_known_extends
|
888 |
+
if have_extends:
|
889 |
+
self.writeline("parent_template = None")
|
890 |
+
self.enter_frame(frame)
|
891 |
+
self.pull_dependencies(node.body)
|
892 |
+
self.blockvisit(node.body, frame)
|
893 |
+
self.leave_frame(frame, with_python_scope=True)
|
894 |
+
self.outdent()
|
895 |
+
|
896 |
+
# make sure that the parent root is called.
|
897 |
+
if have_extends:
|
898 |
+
if not self.has_known_extends:
|
899 |
+
self.indent()
|
900 |
+
self.writeline("if parent_template is not None:")
|
901 |
+
self.indent()
|
902 |
+
if not self.environment.is_async:
|
903 |
+
self.writeline("yield from parent_template.root_render_func(context)")
|
904 |
+
else:
|
905 |
+
self.writeline(
|
906 |
+
"async for event in parent_template.root_render_func(context):"
|
907 |
+
)
|
908 |
+
self.indent()
|
909 |
+
self.writeline("yield event")
|
910 |
+
self.outdent()
|
911 |
+
self.outdent(1 + (not self.has_known_extends))
|
912 |
+
|
913 |
+
# at this point we now have the blocks collected and can visit them too.
|
914 |
+
for name, block in self.blocks.items():
|
915 |
+
self.writeline(
|
916 |
+
f"{self.func('block_' + name)}(context, missing=missing{envenv}):",
|
917 |
+
block,
|
918 |
+
1,
|
919 |
+
)
|
920 |
+
self.indent()
|
921 |
+
self.write_commons()
|
922 |
+
# It's important that we do not make this frame a child of the
|
923 |
+
# toplevel template. This would cause a variety of
|
924 |
+
# interesting issues with identifier tracking.
|
925 |
+
block_frame = Frame(eval_ctx)
|
926 |
+
block_frame.block_frame = True
|
927 |
+
undeclared = find_undeclared(block.body, ("self", "super"))
|
928 |
+
if "self" in undeclared:
|
929 |
+
ref = block_frame.symbols.declare_parameter("self")
|
930 |
+
self.writeline(f"{ref} = TemplateReference(context)")
|
931 |
+
if "super" in undeclared:
|
932 |
+
ref = block_frame.symbols.declare_parameter("super")
|
933 |
+
self.writeline(f"{ref} = context.super({name!r}, block_{name})")
|
934 |
+
block_frame.symbols.analyze_node(block)
|
935 |
+
block_frame.block = name
|
936 |
+
self.writeline("_block_vars = {}")
|
937 |
+
self.enter_frame(block_frame)
|
938 |
+
self.pull_dependencies(block.body)
|
939 |
+
self.blockvisit(block.body, block_frame)
|
940 |
+
self.leave_frame(block_frame, with_python_scope=True)
|
941 |
+
self.outdent()
|
942 |
+
|
943 |
+
blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks)
|
944 |
+
self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)
|
945 |
+
debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)
|
946 |
+
self.writeline(f"debug_info = {debug_kv_str!r}")
|
947 |
+
|
948 |
+
def visit_Block(self, node: nodes.Block, frame: Frame) -> None:
|
949 |
+
"""Call a block and register it for the template."""
|
950 |
+
level = 0
|
951 |
+
if frame.toplevel:
|
952 |
+
# if we know that we are a child template, there is no need to
|
953 |
+
# check if we are one
|
954 |
+
if self.has_known_extends:
|
955 |
+
return
|
956 |
+
if self.extends_so_far > 0:
|
957 |
+
self.writeline("if parent_template is None:")
|
958 |
+
self.indent()
|
959 |
+
level += 1
|
960 |
+
|
961 |
+
if node.scoped:
|
962 |
+
context = self.derive_context(frame)
|
963 |
+
else:
|
964 |
+
context = self.get_context_ref()
|
965 |
+
|
966 |
+
if node.required:
|
967 |
+
self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node)
|
968 |
+
self.indent()
|
969 |
+
self.writeline(
|
970 |
+
f'raise TemplateRuntimeError("Required block {node.name!r} not found")',
|
971 |
+
node,
|
972 |
+
)
|
973 |
+
self.outdent()
|
974 |
+
|
975 |
+
if not self.environment.is_async and frame.buffer is None:
|
976 |
+
self.writeline(
|
977 |
+
f"yield from context.blocks[{node.name!r}][0]({context})", node
|
978 |
+
)
|
979 |
+
else:
|
980 |
+
self.writeline(
|
981 |
+
f"{self.choose_async()}for event in"
|
982 |
+
f" context.blocks[{node.name!r}][0]({context}):",
|
983 |
+
node,
|
984 |
+
)
|
985 |
+
self.indent()
|
986 |
+
self.simple_write("event", frame)
|
987 |
+
self.outdent()
|
988 |
+
|
989 |
+
self.outdent(level)
|
990 |
+
|
991 |
+
def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:
|
992 |
+
"""Calls the extender."""
|
993 |
+
if not frame.toplevel:
|
994 |
+
self.fail("cannot use extend from a non top-level scope", node.lineno)
|
995 |
+
|
996 |
+
# if the number of extends statements in general is zero so
|
997 |
+
# far, we don't have to add a check if something extended
|
998 |
+
# the template before this one.
|
999 |
+
if self.extends_so_far > 0:
|
1000 |
+
# if we have a known extends we just add a template runtime
|
1001 |
+
# error into the generated code. We could catch that at compile
|
1002 |
+
# time too, but i welcome it not to confuse users by throwing the
|
1003 |
+
# same error at different times just "because we can".
|
1004 |
+
if not self.has_known_extends:
|
1005 |
+
self.writeline("if parent_template is not None:")
|
1006 |
+
self.indent()
|
1007 |
+
self.writeline('raise TemplateRuntimeError("extended multiple times")')
|
1008 |
+
|
1009 |
+
# if we have a known extends already we don't need that code here
|
1010 |
+
# as we know that the template execution will end here.
|
1011 |
+
if self.has_known_extends:
|
1012 |
+
raise CompilerExit()
|
1013 |
+
else:
|
1014 |
+
self.outdent()
|
1015 |
+
|
1016 |
+
self.writeline("parent_template = environment.get_template(", node)
|
1017 |
+
self.visit(node.template, frame)
|
1018 |
+
self.write(f", {self.name!r})")
|
1019 |
+
self.writeline("for name, parent_block in parent_template.blocks.items():")
|
1020 |
+
self.indent()
|
1021 |
+
self.writeline("context.blocks.setdefault(name, []).append(parent_block)")
|
1022 |
+
self.outdent()
|
1023 |
+
|
1024 |
+
# if this extends statement was in the root level we can take
|
1025 |
+
# advantage of that information and simplify the generated code
|
1026 |
+
# in the top level from this point onwards
|
1027 |
+
if frame.rootlevel:
|
1028 |
+
self.has_known_extends = True
|
1029 |
+
|
1030 |
+
# and now we have one more
|
1031 |
+
self.extends_so_far += 1
|
1032 |
+
|
1033 |
+
def visit_Include(self, node: nodes.Include, frame: Frame) -> None:
|
1034 |
+
"""Handles includes."""
|
1035 |
+
if node.ignore_missing:
|
1036 |
+
self.writeline("try:")
|
1037 |
+
self.indent()
|
1038 |
+
|
1039 |
+
func_name = "get_or_select_template"
|
1040 |
+
if isinstance(node.template, nodes.Const):
|
1041 |
+
if isinstance(node.template.value, str):
|
1042 |
+
func_name = "get_template"
|
1043 |
+
elif isinstance(node.template.value, (tuple, list)):
|
1044 |
+
func_name = "select_template"
|
1045 |
+
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
|
1046 |
+
func_name = "select_template"
|
1047 |
+
|
1048 |
+
self.writeline(f"template = environment.{func_name}(", node)
|
1049 |
+
self.visit(node.template, frame)
|
1050 |
+
self.write(f", {self.name!r})")
|
1051 |
+
if node.ignore_missing:
|
1052 |
+
self.outdent()
|
1053 |
+
self.writeline("except TemplateNotFound:")
|
1054 |
+
self.indent()
|
1055 |
+
self.writeline("pass")
|
1056 |
+
self.outdent()
|
1057 |
+
self.writeline("else:")
|
1058 |
+
self.indent()
|
1059 |
+
|
1060 |
+
skip_event_yield = False
|
1061 |
+
if node.with_context:
|
1062 |
+
self.writeline(
|
1063 |
+
f"{self.choose_async()}for event in template.root_render_func("
|
1064 |
+
"template.new_context(context.get_all(), True,"
|
1065 |
+
f" {self.dump_local_context(frame)})):"
|
1066 |
+
)
|
1067 |
+
elif self.environment.is_async:
|
1068 |
+
self.writeline(
|
1069 |
+
"for event in (await template._get_default_module_async())"
|
1070 |
+
"._body_stream:"
|
1071 |
+
)
|
1072 |
+
else:
|
1073 |
+
self.writeline("yield from template._get_default_module()._body_stream")
|
1074 |
+
skip_event_yield = True
|
1075 |
+
|
1076 |
+
if not skip_event_yield:
|
1077 |
+
self.indent()
|
1078 |
+
self.simple_write("event", frame)
|
1079 |
+
self.outdent()
|
1080 |
+
|
1081 |
+
if node.ignore_missing:
|
1082 |
+
self.outdent()
|
1083 |
+
|
1084 |
+
def _import_common(
|
1085 |
+
self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame
|
1086 |
+
) -> None:
|
1087 |
+
self.write(f"{self.choose_async('await ')}environment.get_template(")
|
1088 |
+
self.visit(node.template, frame)
|
1089 |
+
self.write(f", {self.name!r}).")
|
1090 |
+
|
1091 |
+
if node.with_context:
|
1092 |
+
f_name = f"make_module{self.choose_async('_async')}"
|
1093 |
+
self.write(
|
1094 |
+
f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})"
|
1095 |
+
)
|
1096 |
+
else:
|
1097 |
+
self.write(f"_get_default_module{self.choose_async('_async')}(context)")
|
1098 |
+
|
1099 |
+
def visit_Import(self, node: nodes.Import, frame: Frame) -> None:
|
1100 |
+
"""Visit regular imports."""
|
1101 |
+
self.writeline(f"{frame.symbols.ref(node.target)} = ", node)
|
1102 |
+
if frame.toplevel:
|
1103 |
+
self.write(f"context.vars[{node.target!r}] = ")
|
1104 |
+
|
1105 |
+
self._import_common(node, frame)
|
1106 |
+
|
1107 |
+
if frame.toplevel and not node.target.startswith("_"):
|
1108 |
+
self.writeline(f"context.exported_vars.discard({node.target!r})")
|
1109 |
+
|
1110 |
+
def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None:
|
1111 |
+
"""Visit named imports."""
|
1112 |
+
self.newline(node)
|
1113 |
+
self.write("included_template = ")
|
1114 |
+
self._import_common(node, frame)
|
1115 |
+
var_names = []
|
1116 |
+
discarded_names = []
|
1117 |
+
for name in node.names:
|
1118 |
+
if isinstance(name, tuple):
|
1119 |
+
name, alias = name
|
1120 |
+
else:
|
1121 |
+
alias = name
|
1122 |
+
self.writeline(
|
1123 |
+
f"{frame.symbols.ref(alias)} ="
|
1124 |
+
f" getattr(included_template, {name!r}, missing)"
|
1125 |
+
)
|
1126 |
+
self.writeline(f"if {frame.symbols.ref(alias)} is missing:")
|
1127 |
+
self.indent()
|
1128 |
+
message = (
|
1129 |
+
"the template {included_template.__name__!r}"
|
1130 |
+
f" (imported on {self.position(node)})"
|
1131 |
+
f" does not export the requested name {name!r}"
|
1132 |
+
)
|
1133 |
+
self.writeline(
|
1134 |
+
f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"
|
1135 |
+
)
|
1136 |
+
self.outdent()
|
1137 |
+
if frame.toplevel:
|
1138 |
+
var_names.append(alias)
|
1139 |
+
if not alias.startswith("_"):
|
1140 |
+
discarded_names.append(alias)
|
1141 |
+
|
1142 |
+
if var_names:
|
1143 |
+
if len(var_names) == 1:
|
1144 |
+
name = var_names[0]
|
1145 |
+
self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")
|
1146 |
+
else:
|
1147 |
+
names_kv = ", ".join(
|
1148 |
+
f"{name!r}: {frame.symbols.ref(name)}" for name in var_names
|
1149 |
+
)
|
1150 |
+
self.writeline(f"context.vars.update({{{names_kv}}})")
|
1151 |
+
if discarded_names:
|
1152 |
+
if len(discarded_names) == 1:
|
1153 |
+
self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})")
|
1154 |
+
else:
|
1155 |
+
names_str = ", ".join(map(repr, discarded_names))
|
1156 |
+
self.writeline(
|
1157 |
+
f"context.exported_vars.difference_update(({names_str}))"
|
1158 |
+
)
|
1159 |
+
|
1160 |
+
def visit_For(self, node: nodes.For, frame: Frame) -> None:
|
1161 |
+
loop_frame = frame.inner()
|
1162 |
+
loop_frame.loop_frame = True
|
1163 |
+
test_frame = frame.inner()
|
1164 |
+
else_frame = frame.inner()
|
1165 |
+
|
1166 |
+
# try to figure out if we have an extended loop. An extended loop
|
1167 |
+
# is necessary if the loop is in recursive mode if the special loop
|
1168 |
+
# variable is accessed in the body if the body is a scoped block.
|
1169 |
+
extended_loop = (
|
1170 |
+
node.recursive
|
1171 |
+
or "loop"
|
1172 |
+
in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",))
|
1173 |
+
or any(block.scoped for block in node.find_all(nodes.Block))
|
1174 |
+
)
|
1175 |
+
|
1176 |
+
loop_ref = None
|
1177 |
+
if extended_loop:
|
1178 |
+
loop_ref = loop_frame.symbols.declare_parameter("loop")
|
1179 |
+
|
1180 |
+
loop_frame.symbols.analyze_node(node, for_branch="body")
|
1181 |
+
if node.else_:
|
1182 |
+
else_frame.symbols.analyze_node(node, for_branch="else")
|
1183 |
+
|
1184 |
+
if node.test:
|
1185 |
+
loop_filter_func = self.temporary_identifier()
|
1186 |
+
test_frame.symbols.analyze_node(node, for_branch="test")
|
1187 |
+
self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test)
|
1188 |
+
self.indent()
|
1189 |
+
self.enter_frame(test_frame)
|
1190 |
+
self.writeline(self.choose_async("async for ", "for "))
|
1191 |
+
self.visit(node.target, loop_frame)
|
1192 |
+
self.write(" in ")
|
1193 |
+
self.write(self.choose_async("auto_aiter(fiter)", "fiter"))
|
1194 |
+
self.write(":")
|
1195 |
+
self.indent()
|
1196 |
+
self.writeline("if ", node.test)
|
1197 |
+
self.visit(node.test, test_frame)
|
1198 |
+
self.write(":")
|
1199 |
+
self.indent()
|
1200 |
+
self.writeline("yield ")
|
1201 |
+
self.visit(node.target, loop_frame)
|
1202 |
+
self.outdent(3)
|
1203 |
+
self.leave_frame(test_frame, with_python_scope=True)
|
1204 |
+
|
1205 |
+
# if we don't have an recursive loop we have to find the shadowed
|
1206 |
+
# variables at that point. Because loops can be nested but the loop
|
1207 |
+
# variable is a special one we have to enforce aliasing for it.
|
1208 |
+
if node.recursive:
|
1209 |
+
self.writeline(
|
1210 |
+
f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node
|
1211 |
+
)
|
1212 |
+
self.indent()
|
1213 |
+
self.buffer(loop_frame)
|
1214 |
+
|
1215 |
+
# Use the same buffer for the else frame
|
1216 |
+
else_frame.buffer = loop_frame.buffer
|
1217 |
+
|
1218 |
+
# make sure the loop variable is a special one and raise a template
|
1219 |
+
# assertion error if a loop tries to write to loop
|
1220 |
+
if extended_loop:
|
1221 |
+
self.writeline(f"{loop_ref} = missing")
|
1222 |
+
|
1223 |
+
for name in node.find_all(nodes.Name):
|
1224 |
+
if name.ctx == "store" and name.name == "loop":
|
1225 |
+
self.fail(
|
1226 |
+
"Can't assign to special loop variable in for-loop target",
|
1227 |
+
name.lineno,
|
1228 |
+
)
|
1229 |
+
|
1230 |
+
if node.else_:
|
1231 |
+
iteration_indicator = self.temporary_identifier()
|
1232 |
+
self.writeline(f"{iteration_indicator} = 1")
|
1233 |
+
|
1234 |
+
self.writeline(self.choose_async("async for ", "for "), node)
|
1235 |
+
self.visit(node.target, loop_frame)
|
1236 |
+
if extended_loop:
|
1237 |
+
self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(")
|
1238 |
+
else:
|
1239 |
+
self.write(" in ")
|
1240 |
+
|
1241 |
+
if node.test:
|
1242 |
+
self.write(f"{loop_filter_func}(")
|
1243 |
+
if node.recursive:
|
1244 |
+
self.write("reciter")
|
1245 |
+
else:
|
1246 |
+
if self.environment.is_async and not extended_loop:
|
1247 |
+
self.write("auto_aiter(")
|
1248 |
+
self.visit(node.iter, frame)
|
1249 |
+
if self.environment.is_async and not extended_loop:
|
1250 |
+
self.write(")")
|
1251 |
+
if node.test:
|
1252 |
+
self.write(")")
|
1253 |
+
|
1254 |
+
if node.recursive:
|
1255 |
+
self.write(", undefined, loop_render_func, depth):")
|
1256 |
+
else:
|
1257 |
+
self.write(", undefined):" if extended_loop else ":")
|
1258 |
+
|
1259 |
+
self.indent()
|
1260 |
+
self.enter_frame(loop_frame)
|
1261 |
+
|
1262 |
+
self.writeline("_loop_vars = {}")
|
1263 |
+
self.blockvisit(node.body, loop_frame)
|
1264 |
+
if node.else_:
|
1265 |
+
self.writeline(f"{iteration_indicator} = 0")
|
1266 |
+
self.outdent()
|
1267 |
+
self.leave_frame(
|
1268 |
+
loop_frame, with_python_scope=node.recursive and not node.else_
|
1269 |
+
)
|
1270 |
+
|
1271 |
+
if node.else_:
|
1272 |
+
self.writeline(f"if {iteration_indicator}:")
|
1273 |
+
self.indent()
|
1274 |
+
self.enter_frame(else_frame)
|
1275 |
+
self.blockvisit(node.else_, else_frame)
|
1276 |
+
self.leave_frame(else_frame)
|
1277 |
+
self.outdent()
|
1278 |
+
|
1279 |
+
# if the node was recursive we have to return the buffer contents
|
1280 |
+
# and start the iteration code
|
1281 |
+
if node.recursive:
|
1282 |
+
self.return_buffer_contents(loop_frame)
|
1283 |
+
self.outdent()
|
1284 |
+
self.start_write(frame, node)
|
1285 |
+
self.write(f"{self.choose_async('await ')}loop(")
|
1286 |
+
if self.environment.is_async:
|
1287 |
+
self.write("auto_aiter(")
|
1288 |
+
self.visit(node.iter, frame)
|
1289 |
+
if self.environment.is_async:
|
1290 |
+
self.write(")")
|
1291 |
+
self.write(", loop)")
|
1292 |
+
self.end_write(frame)
|
1293 |
+
|
1294 |
+
# at the end of the iteration, clear any assignments made in the
|
1295 |
+
# loop from the top level
|
1296 |
+
if self._assign_stack:
|
1297 |
+
self._assign_stack[-1].difference_update(loop_frame.symbols.stores)
|
1298 |
+
|
1299 |
+
def visit_If(self, node: nodes.If, frame: Frame) -> None:
|
1300 |
+
if_frame = frame.soft()
|
1301 |
+
self.writeline("if ", node)
|
1302 |
+
self.visit(node.test, if_frame)
|
1303 |
+
self.write(":")
|
1304 |
+
self.indent()
|
1305 |
+
self.blockvisit(node.body, if_frame)
|
1306 |
+
self.outdent()
|
1307 |
+
for elif_ in node.elif_:
|
1308 |
+
self.writeline("elif ", elif_)
|
1309 |
+
self.visit(elif_.test, if_frame)
|
1310 |
+
self.write(":")
|
1311 |
+
self.indent()
|
1312 |
+
self.blockvisit(elif_.body, if_frame)
|
1313 |
+
self.outdent()
|
1314 |
+
if node.else_:
|
1315 |
+
self.writeline("else:")
|
1316 |
+
self.indent()
|
1317 |
+
self.blockvisit(node.else_, if_frame)
|
1318 |
+
self.outdent()
|
1319 |
+
|
1320 |
+
def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None:
|
1321 |
+
macro_frame, macro_ref = self.macro_body(node, frame)
|
1322 |
+
self.newline()
|
1323 |
+
if frame.toplevel:
|
1324 |
+
if not node.name.startswith("_"):
|
1325 |
+
self.write(f"context.exported_vars.add({node.name!r})")
|
1326 |
+
self.writeline(f"context.vars[{node.name!r}] = ")
|
1327 |
+
self.write(f"{frame.symbols.ref(node.name)} = ")
|
1328 |
+
self.macro_def(macro_ref, macro_frame)
|
1329 |
+
|
1330 |
+
def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None:
|
1331 |
+
call_frame, macro_ref = self.macro_body(node, frame)
|
1332 |
+
self.writeline("caller = ")
|
1333 |
+
self.macro_def(macro_ref, call_frame)
|
1334 |
+
self.start_write(frame, node)
|
1335 |
+
self.visit_Call(node.call, frame, forward_caller=True)
|
1336 |
+
self.end_write(frame)
|
1337 |
+
|
1338 |
+
def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None:
|
1339 |
+
filter_frame = frame.inner()
|
1340 |
+
filter_frame.symbols.analyze_node(node)
|
1341 |
+
self.enter_frame(filter_frame)
|
1342 |
+
self.buffer(filter_frame)
|
1343 |
+
self.blockvisit(node.body, filter_frame)
|
1344 |
+
self.start_write(frame, node)
|
1345 |
+
self.visit_Filter(node.filter, filter_frame)
|
1346 |
+
self.end_write(frame)
|
1347 |
+
self.leave_frame(filter_frame)
|
1348 |
+
|
1349 |
+
def visit_With(self, node: nodes.With, frame: Frame) -> None:
|
1350 |
+
with_frame = frame.inner()
|
1351 |
+
with_frame.symbols.analyze_node(node)
|
1352 |
+
self.enter_frame(with_frame)
|
1353 |
+
for target, expr in zip(node.targets, node.values):
|
1354 |
+
self.newline()
|
1355 |
+
self.visit(target, with_frame)
|
1356 |
+
self.write(" = ")
|
1357 |
+
self.visit(expr, frame)
|
1358 |
+
self.blockvisit(node.body, with_frame)
|
1359 |
+
self.leave_frame(with_frame)
|
1360 |
+
|
1361 |
+
def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None:
|
1362 |
+
self.newline(node)
|
1363 |
+
self.visit(node.node, frame)
|
1364 |
+
|
1365 |
+
class _FinalizeInfo(t.NamedTuple):
|
1366 |
+
const: t.Optional[t.Callable[..., str]]
|
1367 |
+
src: t.Optional[str]
|
1368 |
+
|
1369 |
+
@staticmethod
|
1370 |
+
def _default_finalize(value: t.Any) -> t.Any:
|
1371 |
+
"""The default finalize function if the environment isn't
|
1372 |
+
configured with one. Or, if the environment has one, this is
|
1373 |
+
called on that function's output for constants.
|
1374 |
+
"""
|
1375 |
+
return str(value)
|
1376 |
+
|
1377 |
+
_finalize: t.Optional[_FinalizeInfo] = None
|
1378 |
+
|
1379 |
+
def _make_finalize(self) -> _FinalizeInfo:
|
1380 |
+
"""Build the finalize function to be used on constants and at
|
1381 |
+
runtime. Cached so it's only created once for all output nodes.
|
1382 |
+
|
1383 |
+
Returns a ``namedtuple`` with the following attributes:
|
1384 |
+
|
1385 |
+
``const``
|
1386 |
+
A function to finalize constant data at compile time.
|
1387 |
+
|
1388 |
+
``src``
|
1389 |
+
Source code to output around nodes to be evaluated at
|
1390 |
+
runtime.
|
1391 |
+
"""
|
1392 |
+
if self._finalize is not None:
|
1393 |
+
return self._finalize
|
1394 |
+
|
1395 |
+
finalize: t.Optional[t.Callable[..., t.Any]]
|
1396 |
+
finalize = default = self._default_finalize
|
1397 |
+
src = None
|
1398 |
+
|
1399 |
+
if self.environment.finalize:
|
1400 |
+
src = "environment.finalize("
|
1401 |
+
env_finalize = self.environment.finalize
|
1402 |
+
pass_arg = {
|
1403 |
+
_PassArg.context: "context",
|
1404 |
+
_PassArg.eval_context: "context.eval_ctx",
|
1405 |
+
_PassArg.environment: "environment",
|
1406 |
+
}.get(
|
1407 |
+
_PassArg.from_obj(env_finalize) # type: ignore
|
1408 |
+
)
|
1409 |
+
finalize = None
|
1410 |
+
|
1411 |
+
if pass_arg is None:
|
1412 |
+
|
1413 |
+
def finalize(value: t.Any) -> t.Any: # noqa: F811
|
1414 |
+
return default(env_finalize(value))
|
1415 |
+
|
1416 |
+
else:
|
1417 |
+
src = f"{src}{pass_arg}, "
|
1418 |
+
|
1419 |
+
if pass_arg == "environment":
|
1420 |
+
|
1421 |
+
def finalize(value: t.Any) -> t.Any: # noqa: F811
|
1422 |
+
return default(env_finalize(self.environment, value))
|
1423 |
+
|
1424 |
+
self._finalize = self._FinalizeInfo(finalize, src)
|
1425 |
+
return self._finalize
|
1426 |
+
|
1427 |
+
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
|
1428 |
+
"""Given a group of constant values converted from ``Output``
|
1429 |
+
child nodes, produce a string to write to the template module
|
1430 |
+
source.
|
1431 |
+
"""
|
1432 |
+
return repr(concat(group))
|
1433 |
+
|
1434 |
+
def _output_child_to_const(
|
1435 |
+
self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
|
1436 |
+
) -> str:
|
1437 |
+
"""Try to optimize a child of an ``Output`` node by trying to
|
1438 |
+
convert it to constant, finalized data at compile time.
|
1439 |
+
|
1440 |
+
If :exc:`Impossible` is raised, the node is not constant and
|
1441 |
+
will be evaluated at runtime. Any other exception will also be
|
1442 |
+
evaluated at runtime for easier debugging.
|
1443 |
+
"""
|
1444 |
+
const = node.as_const(frame.eval_ctx)
|
1445 |
+
|
1446 |
+
if frame.eval_ctx.autoescape:
|
1447 |
+
const = escape(const)
|
1448 |
+
|
1449 |
+
# Template data doesn't go through finalize.
|
1450 |
+
if isinstance(node, nodes.TemplateData):
|
1451 |
+
return str(const)
|
1452 |
+
|
1453 |
+
return finalize.const(const) # type: ignore
|
1454 |
+
|
1455 |
+
def _output_child_pre(
|
1456 |
+
self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
|
1457 |
+
) -> None:
|
1458 |
+
"""Output extra source code before visiting a child of an
|
1459 |
+
``Output`` node.
|
1460 |
+
"""
|
1461 |
+
if frame.eval_ctx.volatile:
|
1462 |
+
self.write("(escape if context.eval_ctx.autoescape else str)(")
|
1463 |
+
elif frame.eval_ctx.autoescape:
|
1464 |
+
self.write("escape(")
|
1465 |
+
else:
|
1466 |
+
self.write("str(")
|
1467 |
+
|
1468 |
+
if finalize.src is not None:
|
1469 |
+
self.write(finalize.src)
|
1470 |
+
|
1471 |
+
def _output_child_post(
|
1472 |
+
self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
|
1473 |
+
) -> None:
|
1474 |
+
"""Output extra source code after visiting a child of an
|
1475 |
+
``Output`` node.
|
1476 |
+
"""
|
1477 |
+
self.write(")")
|
1478 |
+
|
1479 |
+
if finalize.src is not None:
|
1480 |
+
self.write(")")
|
1481 |
+
|
1482 |
+
def visit_Output(self, node: nodes.Output, frame: Frame) -> None:
|
1483 |
+
# If an extends is active, don't render outside a block.
|
1484 |
+
if frame.require_output_check:
|
1485 |
+
# A top-level extends is known to exist at compile time.
|
1486 |
+
if self.has_known_extends:
|
1487 |
+
return
|
1488 |
+
|
1489 |
+
self.writeline("if parent_template is None:")
|
1490 |
+
self.indent()
|
1491 |
+
|
1492 |
+
finalize = self._make_finalize()
|
1493 |
+
body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = []
|
1494 |
+
|
1495 |
+
# Evaluate constants at compile time if possible. Each item in
|
1496 |
+
# body will be either a list of static data or a node to be
|
1497 |
+
# evaluated at runtime.
|
1498 |
+
for child in node.nodes:
|
1499 |
+
try:
|
1500 |
+
if not (
|
1501 |
+
# If the finalize function requires runtime context,
|
1502 |
+
# constants can't be evaluated at compile time.
|
1503 |
+
finalize.const
|
1504 |
+
# Unless it's basic template data that won't be
|
1505 |
+
# finalized anyway.
|
1506 |
+
or isinstance(child, nodes.TemplateData)
|
1507 |
+
):
|
1508 |
+
raise nodes.Impossible()
|
1509 |
+
|
1510 |
+
const = self._output_child_to_const(child, frame, finalize)
|
1511 |
+
except (nodes.Impossible, Exception):
|
1512 |
+
# The node was not constant and needs to be evaluated at
|
1513 |
+
# runtime. Or another error was raised, which is easier
|
1514 |
+
# to debug at runtime.
|
1515 |
+
body.append(child)
|
1516 |
+
continue
|
1517 |
+
|
1518 |
+
if body and isinstance(body[-1], list):
|
1519 |
+
body[-1].append(const)
|
1520 |
+
else:
|
1521 |
+
body.append([const])
|
1522 |
+
|
1523 |
+
if frame.buffer is not None:
|
1524 |
+
if len(body) == 1:
|
1525 |
+
self.writeline(f"{frame.buffer}.append(")
|
1526 |
+
else:
|
1527 |
+
self.writeline(f"{frame.buffer}.extend((")
|
1528 |
+
|
1529 |
+
self.indent()
|
1530 |
+
|
1531 |
+
for item in body:
|
1532 |
+
if isinstance(item, list):
|
1533 |
+
# A group of constant data to join and output.
|
1534 |
+
val = self._output_const_repr(item)
|
1535 |
+
|
1536 |
+
if frame.buffer is None:
|
1537 |
+
self.writeline("yield " + val)
|
1538 |
+
else:
|
1539 |
+
self.writeline(val + ",")
|
1540 |
+
else:
|
1541 |
+
if frame.buffer is None:
|
1542 |
+
self.writeline("yield ", item)
|
1543 |
+
else:
|
1544 |
+
self.newline(item)
|
1545 |
+
|
1546 |
+
# A node to be evaluated at runtime.
|
1547 |
+
self._output_child_pre(item, frame, finalize)
|
1548 |
+
self.visit(item, frame)
|
1549 |
+
self._output_child_post(item, frame, finalize)
|
1550 |
+
|
1551 |
+
if frame.buffer is not None:
|
1552 |
+
self.write(",")
|
1553 |
+
|
1554 |
+
if frame.buffer is not None:
|
1555 |
+
self.outdent()
|
1556 |
+
self.writeline(")" if len(body) == 1 else "))")
|
1557 |
+
|
1558 |
+
if frame.require_output_check:
|
1559 |
+
self.outdent()
|
1560 |
+
|
1561 |
+
def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:
|
1562 |
+
self.push_assign_tracking()
|
1563 |
+
self.newline(node)
|
1564 |
+
self.visit(node.target, frame)
|
1565 |
+
self.write(" = ")
|
1566 |
+
self.visit(node.node, frame)
|
1567 |
+
self.pop_assign_tracking(frame)
|
1568 |
+
|
1569 |
+
def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None:
|
1570 |
+
self.push_assign_tracking()
|
1571 |
+
block_frame = frame.inner()
|
1572 |
+
# This is a special case. Since a set block always captures we
|
1573 |
+
# will disable output checks. This way one can use set blocks
|
1574 |
+
# toplevel even in extended templates.
|
1575 |
+
block_frame.require_output_check = False
|
1576 |
+
block_frame.symbols.analyze_node(node)
|
1577 |
+
self.enter_frame(block_frame)
|
1578 |
+
self.buffer(block_frame)
|
1579 |
+
self.blockvisit(node.body, block_frame)
|
1580 |
+
self.newline(node)
|
1581 |
+
self.visit(node.target, frame)
|
1582 |
+
self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")
|
1583 |
+
if node.filter is not None:
|
1584 |
+
self.visit_Filter(node.filter, block_frame)
|
1585 |
+
else:
|
1586 |
+
self.write(f"concat({block_frame.buffer})")
|
1587 |
+
self.write(")")
|
1588 |
+
self.pop_assign_tracking(frame)
|
1589 |
+
self.leave_frame(block_frame)
|
1590 |
+
|
1591 |
+
# -- Expression Visitors
|
1592 |
+
|
1593 |
+
def visit_Name(self, node: nodes.Name, frame: Frame) -> None:
|
1594 |
+
if node.ctx == "store" and (
|
1595 |
+
frame.toplevel or frame.loop_frame or frame.block_frame
|
1596 |
+
):
|
1597 |
+
if self._assign_stack:
|
1598 |
+
self._assign_stack[-1].add(node.name)
|
1599 |
+
ref = frame.symbols.ref(node.name)
|
1600 |
+
|
1601 |
+
# If we are looking up a variable we might have to deal with the
|
1602 |
+
# case where it's undefined. We can skip that case if the load
|
1603 |
+
# instruction indicates a parameter which are always defined.
|
1604 |
+
if node.ctx == "load":
|
1605 |
+
load = frame.symbols.find_load(ref)
|
1606 |
+
if not (
|
1607 |
+
load is not None
|
1608 |
+
and load[0] == VAR_LOAD_PARAMETER
|
1609 |
+
and not self.parameter_is_undeclared(ref)
|
1610 |
+
):
|
1611 |
+
self.write(
|
1612 |
+
f"(undefined(name={node.name!r}) if {ref} is missing else {ref})"
|
1613 |
+
)
|
1614 |
+
return
|
1615 |
+
|
1616 |
+
self.write(ref)
|
1617 |
+
|
1618 |
+
def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:
|
1619 |
+
# NSRefs can only be used to store values; since they use the normal
|
1620 |
+
# `foo.bar` notation they will be parsed as a normal attribute access
|
1621 |
+
# when used anywhere but in a `set` context
|
1622 |
+
ref = frame.symbols.ref(node.name)
|
1623 |
+
self.writeline(f"if not isinstance({ref}, Namespace):")
|
1624 |
+
self.indent()
|
1625 |
+
self.writeline(
|
1626 |
+
"raise TemplateRuntimeError"
|
1627 |
+
'("cannot assign attribute on non-namespace object")'
|
1628 |
+
)
|
1629 |
+
self.outdent()
|
1630 |
+
self.writeline(f"{ref}[{node.attr!r}]")
|
1631 |
+
|
1632 |
+
def visit_Const(self, node: nodes.Const, frame: Frame) -> None:
|
1633 |
+
val = node.as_const(frame.eval_ctx)
|
1634 |
+
if isinstance(val, float):
|
1635 |
+
self.write(str(val))
|
1636 |
+
else:
|
1637 |
+
self.write(repr(val))
|
1638 |
+
|
1639 |
+
def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None:
|
1640 |
+
try:
|
1641 |
+
self.write(repr(node.as_const(frame.eval_ctx)))
|
1642 |
+
except nodes.Impossible:
|
1643 |
+
self.write(
|
1644 |
+
f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"
|
1645 |
+
)
|
1646 |
+
|
1647 |
+
def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None:
|
1648 |
+
self.write("(")
|
1649 |
+
idx = -1
|
1650 |
+
for idx, item in enumerate(node.items):
|
1651 |
+
if idx:
|
1652 |
+
self.write(", ")
|
1653 |
+
self.visit(item, frame)
|
1654 |
+
self.write(",)" if idx == 0 else ")")
|
1655 |
+
|
1656 |
+
def visit_List(self, node: nodes.List, frame: Frame) -> None:
|
1657 |
+
self.write("[")
|
1658 |
+
for idx, item in enumerate(node.items):
|
1659 |
+
if idx:
|
1660 |
+
self.write(", ")
|
1661 |
+
self.visit(item, frame)
|
1662 |
+
self.write("]")
|
1663 |
+
|
1664 |
+
def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None:
|
1665 |
+
self.write("{")
|
1666 |
+
for idx, item in enumerate(node.items):
|
1667 |
+
if idx:
|
1668 |
+
self.write(", ")
|
1669 |
+
self.visit(item.key, frame)
|
1670 |
+
self.write(": ")
|
1671 |
+
self.visit(item.value, frame)
|
1672 |
+
self.write("}")
|
1673 |
+
|
1674 |
+
visit_Add = _make_binop("+")
|
1675 |
+
visit_Sub = _make_binop("-")
|
1676 |
+
visit_Mul = _make_binop("*")
|
1677 |
+
visit_Div = _make_binop("/")
|
1678 |
+
visit_FloorDiv = _make_binop("//")
|
1679 |
+
visit_Pow = _make_binop("**")
|
1680 |
+
visit_Mod = _make_binop("%")
|
1681 |
+
visit_And = _make_binop("and")
|
1682 |
+
visit_Or = _make_binop("or")
|
1683 |
+
visit_Pos = _make_unop("+")
|
1684 |
+
visit_Neg = _make_unop("-")
|
1685 |
+
visit_Not = _make_unop("not ")
|
1686 |
+
|
1687 |
+
@optimizeconst
|
1688 |
+
def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None:
|
1689 |
+
if frame.eval_ctx.volatile:
|
1690 |
+
func_name = "(markup_join if context.eval_ctx.volatile else str_join)"
|
1691 |
+
elif frame.eval_ctx.autoescape:
|
1692 |
+
func_name = "markup_join"
|
1693 |
+
else:
|
1694 |
+
func_name = "str_join"
|
1695 |
+
self.write(f"{func_name}((")
|
1696 |
+
for arg in node.nodes:
|
1697 |
+
self.visit(arg, frame)
|
1698 |
+
self.write(", ")
|
1699 |
+
self.write("))")
|
1700 |
+
|
1701 |
+
@optimizeconst
|
1702 |
+
def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None:
|
1703 |
+
self.write("(")
|
1704 |
+
self.visit(node.expr, frame)
|
1705 |
+
for op in node.ops:
|
1706 |
+
self.visit(op, frame)
|
1707 |
+
self.write(")")
|
1708 |
+
|
1709 |
+
def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None:
|
1710 |
+
self.write(f" {operators[node.op]} ")
|
1711 |
+
self.visit(node.expr, frame)
|
1712 |
+
|
1713 |
+
@optimizeconst
|
1714 |
+
def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None:
|
1715 |
+
if self.environment.is_async:
|
1716 |
+
self.write("(await auto_await(")
|
1717 |
+
|
1718 |
+
self.write("environment.getattr(")
|
1719 |
+
self.visit(node.node, frame)
|
1720 |
+
self.write(f", {node.attr!r})")
|
1721 |
+
|
1722 |
+
if self.environment.is_async:
|
1723 |
+
self.write("))")
|
1724 |
+
|
1725 |
+
@optimizeconst
|
1726 |
+
def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None:
|
1727 |
+
# slices bypass the environment getitem method.
|
1728 |
+
if isinstance(node.arg, nodes.Slice):
|
1729 |
+
self.visit(node.node, frame)
|
1730 |
+
self.write("[")
|
1731 |
+
self.visit(node.arg, frame)
|
1732 |
+
self.write("]")
|
1733 |
+
else:
|
1734 |
+
if self.environment.is_async:
|
1735 |
+
self.write("(await auto_await(")
|
1736 |
+
|
1737 |
+
self.write("environment.getitem(")
|
1738 |
+
self.visit(node.node, frame)
|
1739 |
+
self.write(", ")
|
1740 |
+
self.visit(node.arg, frame)
|
1741 |
+
self.write(")")
|
1742 |
+
|
1743 |
+
if self.environment.is_async:
|
1744 |
+
self.write("))")
|
1745 |
+
|
1746 |
+
def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None:
|
1747 |
+
if node.start is not None:
|
1748 |
+
self.visit(node.start, frame)
|
1749 |
+
self.write(":")
|
1750 |
+
if node.stop is not None:
|
1751 |
+
self.visit(node.stop, frame)
|
1752 |
+
if node.step is not None:
|
1753 |
+
self.write(":")
|
1754 |
+
self.visit(node.step, frame)
|
1755 |
+
|
1756 |
+
@contextmanager
|
1757 |
+
def _filter_test_common(
|
1758 |
+
self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool
|
1759 |
+
) -> t.Iterator[None]:
|
1760 |
+
if self.environment.is_async:
|
1761 |
+
self.write("(await auto_await(")
|
1762 |
+
|
1763 |
+
if is_filter:
|
1764 |
+
self.write(f"{self.filters[node.name]}(")
|
1765 |
+
func = self.environment.filters.get(node.name)
|
1766 |
+
else:
|
1767 |
+
self.write(f"{self.tests[node.name]}(")
|
1768 |
+
func = self.environment.tests.get(node.name)
|
1769 |
+
|
1770 |
+
# When inside an If or CondExpr frame, allow the filter to be
|
1771 |
+
# undefined at compile time and only raise an error if it's
|
1772 |
+
# actually called at runtime. See pull_dependencies.
|
1773 |
+
if func is None and not frame.soft_frame:
|
1774 |
+
type_name = "filter" if is_filter else "test"
|
1775 |
+
self.fail(f"No {type_name} named {node.name!r}.", node.lineno)
|
1776 |
+
|
1777 |
+
pass_arg = {
|
1778 |
+
_PassArg.context: "context",
|
1779 |
+
_PassArg.eval_context: "context.eval_ctx",
|
1780 |
+
_PassArg.environment: "environment",
|
1781 |
+
}.get(
|
1782 |
+
_PassArg.from_obj(func) # type: ignore
|
1783 |
+
)
|
1784 |
+
|
1785 |
+
if pass_arg is not None:
|
1786 |
+
self.write(f"{pass_arg}, ")
|
1787 |
+
|
1788 |
+
# Back to the visitor function to handle visiting the target of
|
1789 |
+
# the filter or test.
|
1790 |
+
yield
|
1791 |
+
|
1792 |
+
self.signature(node, frame)
|
1793 |
+
self.write(")")
|
1794 |
+
|
1795 |
+
if self.environment.is_async:
|
1796 |
+
self.write("))")
|
1797 |
+
|
1798 |
+
@optimizeconst
|
1799 |
+
def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None:
|
1800 |
+
with self._filter_test_common(node, frame, True):
|
1801 |
+
# if the filter node is None we are inside a filter block
|
1802 |
+
# and want to write to the current buffer
|
1803 |
+
if node.node is not None:
|
1804 |
+
self.visit(node.node, frame)
|
1805 |
+
elif frame.eval_ctx.volatile:
|
1806 |
+
self.write(
|
1807 |
+
f"(Markup(concat({frame.buffer}))"
|
1808 |
+
f" if context.eval_ctx.autoescape else concat({frame.buffer}))"
|
1809 |
+
)
|
1810 |
+
elif frame.eval_ctx.autoescape:
|
1811 |
+
self.write(f"Markup(concat({frame.buffer}))")
|
1812 |
+
else:
|
1813 |
+
self.write(f"concat({frame.buffer})")
|
1814 |
+
|
1815 |
+
@optimizeconst
|
1816 |
+
def visit_Test(self, node: nodes.Test, frame: Frame) -> None:
|
1817 |
+
with self._filter_test_common(node, frame, False):
|
1818 |
+
self.visit(node.node, frame)
|
1819 |
+
|
1820 |
+
@optimizeconst
|
1821 |
+
def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None:
|
1822 |
+
frame = frame.soft()
|
1823 |
+
|
1824 |
+
def write_expr2() -> None:
|
1825 |
+
if node.expr2 is not None:
|
1826 |
+
self.visit(node.expr2, frame)
|
1827 |
+
return
|
1828 |
+
|
1829 |
+
self.write(
|
1830 |
+
f'cond_expr_undefined("the inline if-expression on'
|
1831 |
+
f" {self.position(node)} evaluated to false and no else"
|
1832 |
+
f' section was defined.")'
|
1833 |
+
)
|
1834 |
+
|
1835 |
+
self.write("(")
|
1836 |
+
self.visit(node.expr1, frame)
|
1837 |
+
self.write(" if ")
|
1838 |
+
self.visit(node.test, frame)
|
1839 |
+
self.write(" else ")
|
1840 |
+
write_expr2()
|
1841 |
+
self.write(")")
|
1842 |
+
|
1843 |
+
@optimizeconst
|
1844 |
+
def visit_Call(
|
1845 |
+
self, node: nodes.Call, frame: Frame, forward_caller: bool = False
|
1846 |
+
) -> None:
|
1847 |
+
if self.environment.is_async:
|
1848 |
+
self.write("(await auto_await(")
|
1849 |
+
if self.environment.sandboxed:
|
1850 |
+
self.write("environment.call(context, ")
|
1851 |
+
else:
|
1852 |
+
self.write("context.call(")
|
1853 |
+
self.visit(node.node, frame)
|
1854 |
+
extra_kwargs = {"caller": "caller"} if forward_caller else None
|
1855 |
+
loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {}
|
1856 |
+
block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {}
|
1857 |
+
if extra_kwargs:
|
1858 |
+
extra_kwargs.update(loop_kwargs, **block_kwargs)
|
1859 |
+
elif loop_kwargs or block_kwargs:
|
1860 |
+
extra_kwargs = dict(loop_kwargs, **block_kwargs)
|
1861 |
+
self.signature(node, frame, extra_kwargs)
|
1862 |
+
self.write(")")
|
1863 |
+
if self.environment.is_async:
|
1864 |
+
self.write("))")
|
1865 |
+
|
1866 |
+
def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None:
|
1867 |
+
self.write(node.key + "=")
|
1868 |
+
self.visit(node.value, frame)
|
1869 |
+
|
1870 |
+
# -- Unused nodes for extensions
|
1871 |
+
|
1872 |
+
def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None:
|
1873 |
+
self.write("Markup(")
|
1874 |
+
self.visit(node.expr, frame)
|
1875 |
+
self.write(")")
|
1876 |
+
|
1877 |
+
def visit_MarkSafeIfAutoescape(
|
1878 |
+
self, node: nodes.MarkSafeIfAutoescape, frame: Frame
|
1879 |
+
) -> None:
|
1880 |
+
self.write("(Markup if context.eval_ctx.autoescape else identity)(")
|
1881 |
+
self.visit(node.expr, frame)
|
1882 |
+
self.write(")")
|
1883 |
+
|
1884 |
+
def visit_EnvironmentAttribute(
|
1885 |
+
self, node: nodes.EnvironmentAttribute, frame: Frame
|
1886 |
+
) -> None:
|
1887 |
+
self.write("environment." + node.name)
|
1888 |
+
|
1889 |
+
def visit_ExtensionAttribute(
|
1890 |
+
self, node: nodes.ExtensionAttribute, frame: Frame
|
1891 |
+
) -> None:
|
1892 |
+
self.write(f"environment.extensions[{node.identifier!r}].{node.name}")
|
1893 |
+
|
1894 |
+
def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None:
|
1895 |
+
self.write(self.import_aliases[node.importname])
|
1896 |
+
|
1897 |
+
def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None:
|
1898 |
+
self.write(node.name)
|
1899 |
+
|
1900 |
+
def visit_ContextReference(
|
1901 |
+
self, node: nodes.ContextReference, frame: Frame
|
1902 |
+
) -> None:
|
1903 |
+
self.write("context")
|
1904 |
+
|
1905 |
+
def visit_DerivedContextReference(
|
1906 |
+
self, node: nodes.DerivedContextReference, frame: Frame
|
1907 |
+
) -> None:
|
1908 |
+
self.write(self.derive_context(frame))
|
1909 |
+
|
1910 |
+
def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:
|
1911 |
+
self.writeline("continue", node)
|
1912 |
+
|
1913 |
+
def visit_Break(self, node: nodes.Break, frame: Frame) -> None:
|
1914 |
+
self.writeline("break", node)
|
1915 |
+
|
1916 |
+
def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None:
|
1917 |
+
scope_frame = frame.inner()
|
1918 |
+
scope_frame.symbols.analyze_node(node)
|
1919 |
+
self.enter_frame(scope_frame)
|
1920 |
+
self.blockvisit(node.body, scope_frame)
|
1921 |
+
self.leave_frame(scope_frame)
|
1922 |
+
|
1923 |
+
def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None:
|
1924 |
+
ctx = self.temporary_identifier()
|
1925 |
+
self.writeline(f"{ctx} = {self.derive_context(frame)}")
|
1926 |
+
self.writeline(f"{ctx}.vars = ")
|
1927 |
+
self.visit(node.context, frame)
|
1928 |
+
self.push_context_reference(ctx)
|
1929 |
+
|
1930 |
+
scope_frame = frame.inner(isolated=True)
|
1931 |
+
scope_frame.symbols.analyze_node(node)
|
1932 |
+
self.enter_frame(scope_frame)
|
1933 |
+
self.blockvisit(node.body, scope_frame)
|
1934 |
+
self.leave_frame(scope_frame)
|
1935 |
+
self.pop_context_reference()
|
1936 |
+
|
1937 |
+
def visit_EvalContextModifier(
|
1938 |
+
self, node: nodes.EvalContextModifier, frame: Frame
|
1939 |
+
) -> None:
|
1940 |
+
for keyword in node.options:
|
1941 |
+
self.writeline(f"context.eval_ctx.{keyword.key} = ")
|
1942 |
+
self.visit(keyword.value, frame)
|
1943 |
+
try:
|
1944 |
+
val = keyword.value.as_const(frame.eval_ctx)
|
1945 |
+
except nodes.Impossible:
|
1946 |
+
frame.eval_ctx.volatile = True
|
1947 |
+
else:
|
1948 |
+
setattr(frame.eval_ctx, keyword.key, val)
|
1949 |
+
|
1950 |
+
def visit_ScopedEvalContextModifier(
|
1951 |
+
self, node: nodes.ScopedEvalContextModifier, frame: Frame
|
1952 |
+
) -> None:
|
1953 |
+
old_ctx_name = self.temporary_identifier()
|
1954 |
+
saved_ctx = frame.eval_ctx.save()
|
1955 |
+
self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")
|
1956 |
+
self.visit_EvalContextModifier(node, frame)
|
1957 |
+
for child in node.body:
|
1958 |
+
self.visit(child, frame)
|
1959 |
+
frame.eval_ctx.revert(saved_ctx)
|
1960 |
+
self.writeline(f"context.eval_ctx.revert({old_ctx_name})")
|
llmeval-env/lib/python3.10/site-packages/jinja2/constants.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#: list of lorem ipsum words used by the lipsum() helper function
|
2 |
+
LOREM_IPSUM_WORDS = """\
|
3 |
+
a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at
|
4 |
+
auctor augue bibendum blandit class commodo condimentum congue consectetuer
|
5 |
+
consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus
|
6 |
+
diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend
|
7 |
+
elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames
|
8 |
+
faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac
|
9 |
+
hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum
|
10 |
+
justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem
|
11 |
+
luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie
|
12 |
+
mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non
|
13 |
+
nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque
|
14 |
+
penatibus per pharetra phasellus placerat platea porta porttitor posuere
|
15 |
+
potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus
|
16 |
+
ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit
|
17 |
+
sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor
|
18 |
+
tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices
|
19 |
+
ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus
|
20 |
+
viverra volutpat vulputate"""
|
llmeval-env/lib/python3.10/site-packages/jinja2/debug.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import typing as t
|
3 |
+
from types import CodeType
|
4 |
+
from types import TracebackType
|
5 |
+
|
6 |
+
from .exceptions import TemplateSyntaxError
|
7 |
+
from .utils import internal_code
|
8 |
+
from .utils import missing
|
9 |
+
|
10 |
+
if t.TYPE_CHECKING:
|
11 |
+
from .runtime import Context
|
12 |
+
|
13 |
+
|
14 |
+
def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:
|
15 |
+
"""Rewrite the current exception to replace any tracebacks from
|
16 |
+
within compiled template code with tracebacks that look like they
|
17 |
+
came from the template source.
|
18 |
+
|
19 |
+
This must be called within an ``except`` block.
|
20 |
+
|
21 |
+
:param source: For ``TemplateSyntaxError``, the original source if
|
22 |
+
known.
|
23 |
+
:return: The original exception with the rewritten traceback.
|
24 |
+
"""
|
25 |
+
_, exc_value, tb = sys.exc_info()
|
26 |
+
exc_value = t.cast(BaseException, exc_value)
|
27 |
+
tb = t.cast(TracebackType, tb)
|
28 |
+
|
29 |
+
if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:
|
30 |
+
exc_value.translated = True
|
31 |
+
exc_value.source = source
|
32 |
+
# Remove the old traceback, otherwise the frames from the
|
33 |
+
# compiler still show up.
|
34 |
+
exc_value.with_traceback(None)
|
35 |
+
# Outside of runtime, so the frame isn't executing template
|
36 |
+
# code, but it still needs to point at the template.
|
37 |
+
tb = fake_traceback(
|
38 |
+
exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
|
39 |
+
)
|
40 |
+
else:
|
41 |
+
# Skip the frame for the render function.
|
42 |
+
tb = tb.tb_next
|
43 |
+
|
44 |
+
stack = []
|
45 |
+
|
46 |
+
# Build the stack of traceback object, replacing any in template
|
47 |
+
# code with the source file and line information.
|
48 |
+
while tb is not None:
|
49 |
+
# Skip frames decorated with @internalcode. These are internal
|
50 |
+
# calls that aren't useful in template debugging output.
|
51 |
+
if tb.tb_frame.f_code in internal_code:
|
52 |
+
tb = tb.tb_next
|
53 |
+
continue
|
54 |
+
|
55 |
+
template = tb.tb_frame.f_globals.get("__jinja_template__")
|
56 |
+
|
57 |
+
if template is not None:
|
58 |
+
lineno = template.get_corresponding_lineno(tb.tb_lineno)
|
59 |
+
fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)
|
60 |
+
stack.append(fake_tb)
|
61 |
+
else:
|
62 |
+
stack.append(tb)
|
63 |
+
|
64 |
+
tb = tb.tb_next
|
65 |
+
|
66 |
+
tb_next = None
|
67 |
+
|
68 |
+
# Assign tb_next in reverse to avoid circular references.
|
69 |
+
for tb in reversed(stack):
|
70 |
+
tb.tb_next = tb_next
|
71 |
+
tb_next = tb
|
72 |
+
|
73 |
+
return exc_value.with_traceback(tb_next)
|
74 |
+
|
75 |
+
|
76 |
+
def fake_traceback( # type: ignore
|
77 |
+
exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int
|
78 |
+
) -> TracebackType:
|
79 |
+
"""Produce a new traceback object that looks like it came from the
|
80 |
+
template source instead of the compiled code. The filename, line
|
81 |
+
number, and location name will point to the template, and the local
|
82 |
+
variables will be the current template context.
|
83 |
+
|
84 |
+
:param exc_value: The original exception to be re-raised to create
|
85 |
+
the new traceback.
|
86 |
+
:param tb: The original traceback to get the local variables and
|
87 |
+
code info from.
|
88 |
+
:param filename: The template filename.
|
89 |
+
:param lineno: The line number in the template source.
|
90 |
+
"""
|
91 |
+
if tb is not None:
|
92 |
+
# Replace the real locals with the context that would be
|
93 |
+
# available at that point in the template.
|
94 |
+
locals = get_template_locals(tb.tb_frame.f_locals)
|
95 |
+
locals.pop("__jinja_exception__", None)
|
96 |
+
else:
|
97 |
+
locals = {}
|
98 |
+
|
99 |
+
globals = {
|
100 |
+
"__name__": filename,
|
101 |
+
"__file__": filename,
|
102 |
+
"__jinja_exception__": exc_value,
|
103 |
+
}
|
104 |
+
# Raise an exception at the correct line number.
|
105 |
+
code: CodeType = compile(
|
106 |
+
"\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec"
|
107 |
+
)
|
108 |
+
|
109 |
+
# Build a new code object that points to the template file and
|
110 |
+
# replaces the location with a block name.
|
111 |
+
location = "template"
|
112 |
+
|
113 |
+
if tb is not None:
|
114 |
+
function = tb.tb_frame.f_code.co_name
|
115 |
+
|
116 |
+
if function == "root":
|
117 |
+
location = "top-level template code"
|
118 |
+
elif function.startswith("block_"):
|
119 |
+
location = f"block {function[6:]!r}"
|
120 |
+
|
121 |
+
if sys.version_info >= (3, 8):
|
122 |
+
code = code.replace(co_name=location)
|
123 |
+
else:
|
124 |
+
code = CodeType(
|
125 |
+
code.co_argcount,
|
126 |
+
code.co_kwonlyargcount,
|
127 |
+
code.co_nlocals,
|
128 |
+
code.co_stacksize,
|
129 |
+
code.co_flags,
|
130 |
+
code.co_code,
|
131 |
+
code.co_consts,
|
132 |
+
code.co_names,
|
133 |
+
code.co_varnames,
|
134 |
+
code.co_filename,
|
135 |
+
location,
|
136 |
+
code.co_firstlineno,
|
137 |
+
code.co_lnotab,
|
138 |
+
code.co_freevars,
|
139 |
+
code.co_cellvars,
|
140 |
+
)
|
141 |
+
|
142 |
+
# Execute the new code, which is guaranteed to raise, and return
|
143 |
+
# the new traceback without this frame.
|
144 |
+
try:
|
145 |
+
exec(code, globals, locals)
|
146 |
+
except BaseException:
|
147 |
+
return sys.exc_info()[2].tb_next # type: ignore
|
148 |
+
|
149 |
+
|
150 |
+
def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:
|
151 |
+
"""Based on the runtime locals, get the context that would be
|
152 |
+
available at that point in the template.
|
153 |
+
"""
|
154 |
+
# Start with the current template context.
|
155 |
+
ctx: "t.Optional[Context]" = real_locals.get("context")
|
156 |
+
|
157 |
+
if ctx is not None:
|
158 |
+
data: t.Dict[str, t.Any] = ctx.get_all().copy()
|
159 |
+
else:
|
160 |
+
data = {}
|
161 |
+
|
162 |
+
# Might be in a derived context that only sets local variables
|
163 |
+
# rather than pushing a context. Local variables follow the scheme
|
164 |
+
# l_depth_name. Find the highest-depth local that has a value for
|
165 |
+
# each name.
|
166 |
+
local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}
|
167 |
+
|
168 |
+
for name, value in real_locals.items():
|
169 |
+
if not name.startswith("l_") or value is missing:
|
170 |
+
# Not a template variable, or no longer relevant.
|
171 |
+
continue
|
172 |
+
|
173 |
+
try:
|
174 |
+
_, depth_str, name = name.split("_", 2)
|
175 |
+
depth = int(depth_str)
|
176 |
+
except ValueError:
|
177 |
+
continue
|
178 |
+
|
179 |
+
cur_depth = local_overrides.get(name, (-1,))[0]
|
180 |
+
|
181 |
+
if cur_depth < depth:
|
182 |
+
local_overrides[name] = (depth, value)
|
183 |
+
|
184 |
+
# Modify the context with any derived context.
|
185 |
+
for name, (_, value) in local_overrides.items():
|
186 |
+
if value is missing:
|
187 |
+
data.pop(name, None)
|
188 |
+
else:
|
189 |
+
data[name] = value
|
190 |
+
|
191 |
+
return data
|
llmeval-env/lib/python3.10/site-packages/jinja2/defaults.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
|
3 |
+
from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401
|
4 |
+
from .tests import TESTS as DEFAULT_TESTS # noqa: F401
|
5 |
+
from .utils import Cycler
|
6 |
+
from .utils import generate_lorem_ipsum
|
7 |
+
from .utils import Joiner
|
8 |
+
from .utils import Namespace
|
9 |
+
|
10 |
+
if t.TYPE_CHECKING:
|
11 |
+
import typing_extensions as te
|
12 |
+
|
13 |
+
# defaults for the parser / lexer
|
14 |
+
BLOCK_START_STRING = "{%"
|
15 |
+
BLOCK_END_STRING = "%}"
|
16 |
+
VARIABLE_START_STRING = "{{"
|
17 |
+
VARIABLE_END_STRING = "}}"
|
18 |
+
COMMENT_START_STRING = "{#"
|
19 |
+
COMMENT_END_STRING = "#}"
|
20 |
+
LINE_STATEMENT_PREFIX: t.Optional[str] = None
|
21 |
+
LINE_COMMENT_PREFIX: t.Optional[str] = None
|
22 |
+
TRIM_BLOCKS = False
|
23 |
+
LSTRIP_BLOCKS = False
|
24 |
+
NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n"
|
25 |
+
KEEP_TRAILING_NEWLINE = False
|
26 |
+
|
27 |
+
# default filters, tests and namespace
|
28 |
+
|
29 |
+
DEFAULT_NAMESPACE = {
|
30 |
+
"range": range,
|
31 |
+
"dict": dict,
|
32 |
+
"lipsum": generate_lorem_ipsum,
|
33 |
+
"cycler": Cycler,
|
34 |
+
"joiner": Joiner,
|
35 |
+
"namespace": Namespace,
|
36 |
+
}
|
37 |
+
|
38 |
+
# default policies
|
39 |
+
DEFAULT_POLICIES: t.Dict[str, t.Any] = {
|
40 |
+
"compiler.ascii_str": True,
|
41 |
+
"urlize.rel": "noopener",
|
42 |
+
"urlize.target": None,
|
43 |
+
"urlize.extra_schemes": None,
|
44 |
+
"truncate.leeway": 5,
|
45 |
+
"json.dumps_function": None,
|
46 |
+
"json.dumps_kwargs": {"sort_keys": True},
|
47 |
+
"ext.i18n.trimmed": False,
|
48 |
+
}
|
llmeval-env/lib/python3.10/site-packages/jinja2/environment.py
ADDED
@@ -0,0 +1,1675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Classes for managing templates and their runtime and compile time
|
2 |
+
options.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import os
|
6 |
+
import typing
|
7 |
+
import typing as t
|
8 |
+
import weakref
|
9 |
+
from collections import ChainMap
|
10 |
+
from functools import lru_cache
|
11 |
+
from functools import partial
|
12 |
+
from functools import reduce
|
13 |
+
from types import CodeType
|
14 |
+
|
15 |
+
from markupsafe import Markup
|
16 |
+
|
17 |
+
from . import nodes
|
18 |
+
from .compiler import CodeGenerator
|
19 |
+
from .compiler import generate
|
20 |
+
from .defaults import BLOCK_END_STRING
|
21 |
+
from .defaults import BLOCK_START_STRING
|
22 |
+
from .defaults import COMMENT_END_STRING
|
23 |
+
from .defaults import COMMENT_START_STRING
|
24 |
+
from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]
|
25 |
+
from .defaults import DEFAULT_NAMESPACE
|
26 |
+
from .defaults import DEFAULT_POLICIES
|
27 |
+
from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]
|
28 |
+
from .defaults import KEEP_TRAILING_NEWLINE
|
29 |
+
from .defaults import LINE_COMMENT_PREFIX
|
30 |
+
from .defaults import LINE_STATEMENT_PREFIX
|
31 |
+
from .defaults import LSTRIP_BLOCKS
|
32 |
+
from .defaults import NEWLINE_SEQUENCE
|
33 |
+
from .defaults import TRIM_BLOCKS
|
34 |
+
from .defaults import VARIABLE_END_STRING
|
35 |
+
from .defaults import VARIABLE_START_STRING
|
36 |
+
from .exceptions import TemplateNotFound
|
37 |
+
from .exceptions import TemplateRuntimeError
|
38 |
+
from .exceptions import TemplatesNotFound
|
39 |
+
from .exceptions import TemplateSyntaxError
|
40 |
+
from .exceptions import UndefinedError
|
41 |
+
from .lexer import get_lexer
|
42 |
+
from .lexer import Lexer
|
43 |
+
from .lexer import TokenStream
|
44 |
+
from .nodes import EvalContext
|
45 |
+
from .parser import Parser
|
46 |
+
from .runtime import Context
|
47 |
+
from .runtime import new_context
|
48 |
+
from .runtime import Undefined
|
49 |
+
from .utils import _PassArg
|
50 |
+
from .utils import concat
|
51 |
+
from .utils import consume
|
52 |
+
from .utils import import_string
|
53 |
+
from .utils import internalcode
|
54 |
+
from .utils import LRUCache
|
55 |
+
from .utils import missing
|
56 |
+
|
57 |
+
if t.TYPE_CHECKING:
|
58 |
+
import typing_extensions as te
|
59 |
+
|
60 |
+
from .bccache import BytecodeCache
|
61 |
+
from .ext import Extension
|
62 |
+
from .loaders import BaseLoader
|
63 |
+
|
64 |
+
_env_bound = t.TypeVar("_env_bound", bound="Environment")
|
65 |
+
|
66 |
+
|
67 |
+
# for direct template usage we have up to ten living environments
|
68 |
+
@lru_cache(maxsize=10)
|
69 |
+
def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound:
|
70 |
+
"""Return a new spontaneous environment. A spontaneous environment
|
71 |
+
is used for templates created directly rather than through an
|
72 |
+
existing environment.
|
73 |
+
|
74 |
+
:param cls: Environment class to create.
|
75 |
+
:param args: Positional arguments passed to environment.
|
76 |
+
"""
|
77 |
+
env = cls(*args)
|
78 |
+
env.shared = True
|
79 |
+
return env
|
80 |
+
|
81 |
+
|
82 |
+
def create_cache(
|
83 |
+
size: int,
|
84 |
+
) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:
|
85 |
+
"""Return the cache class for the given size."""
|
86 |
+
if size == 0:
|
87 |
+
return None
|
88 |
+
|
89 |
+
if size < 0:
|
90 |
+
return {}
|
91 |
+
|
92 |
+
return LRUCache(size) # type: ignore
|
93 |
+
|
94 |
+
|
95 |
+
def copy_cache(
|
96 |
+
cache: t.Optional[t.MutableMapping[t.Any, t.Any]],
|
97 |
+
) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:
|
98 |
+
"""Create an empty copy of the given cache."""
|
99 |
+
if cache is None:
|
100 |
+
return None
|
101 |
+
|
102 |
+
if type(cache) is dict: # noqa E721
|
103 |
+
return {}
|
104 |
+
|
105 |
+
return LRUCache(cache.capacity) # type: ignore
|
106 |
+
|
107 |
+
|
108 |
+
def load_extensions(
|
109 |
+
environment: "Environment",
|
110 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]],
|
111 |
+
) -> t.Dict[str, "Extension"]:
|
112 |
+
"""Load the extensions from the list and bind it to the environment.
|
113 |
+
Returns a dict of instantiated extensions.
|
114 |
+
"""
|
115 |
+
result = {}
|
116 |
+
|
117 |
+
for extension in extensions:
|
118 |
+
if isinstance(extension, str):
|
119 |
+
extension = t.cast(t.Type["Extension"], import_string(extension))
|
120 |
+
|
121 |
+
result[extension.identifier] = extension(environment)
|
122 |
+
|
123 |
+
return result
|
124 |
+
|
125 |
+
|
126 |
+
def _environment_config_check(environment: "Environment") -> "Environment":
|
127 |
+
"""Perform a sanity check on the environment."""
|
128 |
+
assert issubclass(
|
129 |
+
environment.undefined, Undefined
|
130 |
+
), "'undefined' must be a subclass of 'jinja2.Undefined'."
|
131 |
+
assert (
|
132 |
+
environment.block_start_string
|
133 |
+
!= environment.variable_start_string
|
134 |
+
!= environment.comment_start_string
|
135 |
+
), "block, variable and comment start strings must be different."
|
136 |
+
assert environment.newline_sequence in {
|
137 |
+
"\r",
|
138 |
+
"\r\n",
|
139 |
+
"\n",
|
140 |
+
}, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."
|
141 |
+
return environment
|
142 |
+
|
143 |
+
|
144 |
+
class Environment:
|
145 |
+
r"""The core component of Jinja is the `Environment`. It contains
|
146 |
+
important shared variables like configuration, filters, tests,
|
147 |
+
globals and others. Instances of this class may be modified if
|
148 |
+
they are not shared and if no template was loaded so far.
|
149 |
+
Modifications on environments after the first template was loaded
|
150 |
+
will lead to surprising effects and undefined behavior.
|
151 |
+
|
152 |
+
Here are the possible initialization parameters:
|
153 |
+
|
154 |
+
`block_start_string`
|
155 |
+
The string marking the beginning of a block. Defaults to ``'{%'``.
|
156 |
+
|
157 |
+
`block_end_string`
|
158 |
+
The string marking the end of a block. Defaults to ``'%}'``.
|
159 |
+
|
160 |
+
`variable_start_string`
|
161 |
+
The string marking the beginning of a print statement.
|
162 |
+
Defaults to ``'{{'``.
|
163 |
+
|
164 |
+
`variable_end_string`
|
165 |
+
The string marking the end of a print statement. Defaults to
|
166 |
+
``'}}'``.
|
167 |
+
|
168 |
+
`comment_start_string`
|
169 |
+
The string marking the beginning of a comment. Defaults to ``'{#'``.
|
170 |
+
|
171 |
+
`comment_end_string`
|
172 |
+
The string marking the end of a comment. Defaults to ``'#}'``.
|
173 |
+
|
174 |
+
`line_statement_prefix`
|
175 |
+
If given and a string, this will be used as prefix for line based
|
176 |
+
statements. See also :ref:`line-statements`.
|
177 |
+
|
178 |
+
`line_comment_prefix`
|
179 |
+
If given and a string, this will be used as prefix for line based
|
180 |
+
comments. See also :ref:`line-statements`.
|
181 |
+
|
182 |
+
.. versionadded:: 2.2
|
183 |
+
|
184 |
+
`trim_blocks`
|
185 |
+
If this is set to ``True`` the first newline after a block is
|
186 |
+
removed (block, not variable tag!). Defaults to `False`.
|
187 |
+
|
188 |
+
`lstrip_blocks`
|
189 |
+
If this is set to ``True`` leading spaces and tabs are stripped
|
190 |
+
from the start of a line to a block. Defaults to `False`.
|
191 |
+
|
192 |
+
`newline_sequence`
|
193 |
+
The sequence that starts a newline. Must be one of ``'\r'``,
|
194 |
+
``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
|
195 |
+
useful default for Linux and OS X systems as well as web
|
196 |
+
applications.
|
197 |
+
|
198 |
+
`keep_trailing_newline`
|
199 |
+
Preserve the trailing newline when rendering templates.
|
200 |
+
The default is ``False``, which causes a single newline,
|
201 |
+
if present, to be stripped from the end of the template.
|
202 |
+
|
203 |
+
.. versionadded:: 2.7
|
204 |
+
|
205 |
+
`extensions`
|
206 |
+
List of Jinja extensions to use. This can either be import paths
|
207 |
+
as strings or extension classes. For more information have a
|
208 |
+
look at :ref:`the extensions documentation <jinja-extensions>`.
|
209 |
+
|
210 |
+
`optimized`
|
211 |
+
should the optimizer be enabled? Default is ``True``.
|
212 |
+
|
213 |
+
`undefined`
|
214 |
+
:class:`Undefined` or a subclass of it that is used to represent
|
215 |
+
undefined values in the template.
|
216 |
+
|
217 |
+
`finalize`
|
218 |
+
A callable that can be used to process the result of a variable
|
219 |
+
expression before it is output. For example one can convert
|
220 |
+
``None`` implicitly into an empty string here.
|
221 |
+
|
222 |
+
`autoescape`
|
223 |
+
If set to ``True`` the XML/HTML autoescaping feature is enabled by
|
224 |
+
default. For more details about autoescaping see
|
225 |
+
:class:`~markupsafe.Markup`. As of Jinja 2.4 this can also
|
226 |
+
be a callable that is passed the template name and has to
|
227 |
+
return ``True`` or ``False`` depending on autoescape should be
|
228 |
+
enabled by default.
|
229 |
+
|
230 |
+
.. versionchanged:: 2.4
|
231 |
+
`autoescape` can now be a function
|
232 |
+
|
233 |
+
`loader`
|
234 |
+
The template loader for this environment.
|
235 |
+
|
236 |
+
`cache_size`
|
237 |
+
The size of the cache. Per default this is ``400`` which means
|
238 |
+
that if more than 400 templates are loaded the loader will clean
|
239 |
+
out the least recently used template. If the cache size is set to
|
240 |
+
``0`` templates are recompiled all the time, if the cache size is
|
241 |
+
``-1`` the cache will not be cleaned.
|
242 |
+
|
243 |
+
.. versionchanged:: 2.8
|
244 |
+
The cache size was increased to 400 from a low 50.
|
245 |
+
|
246 |
+
`auto_reload`
|
247 |
+
Some loaders load templates from locations where the template
|
248 |
+
sources may change (ie: file system or database). If
|
249 |
+
``auto_reload`` is set to ``True`` (default) every time a template is
|
250 |
+
requested the loader checks if the source changed and if yes, it
|
251 |
+
will reload the template. For higher performance it's possible to
|
252 |
+
disable that.
|
253 |
+
|
254 |
+
`bytecode_cache`
|
255 |
+
If set to a bytecode cache object, this object will provide a
|
256 |
+
cache for the internal Jinja bytecode so that templates don't
|
257 |
+
have to be parsed if they were not changed.
|
258 |
+
|
259 |
+
See :ref:`bytecode-cache` for more information.
|
260 |
+
|
261 |
+
`enable_async`
|
262 |
+
If set to true this enables async template execution which
|
263 |
+
allows using async functions and generators.
|
264 |
+
"""
|
265 |
+
|
266 |
+
#: if this environment is sandboxed. Modifying this variable won't make
|
267 |
+
#: the environment sandboxed though. For a real sandboxed environment
|
268 |
+
#: have a look at jinja2.sandbox. This flag alone controls the code
|
269 |
+
#: generation by the compiler.
|
270 |
+
sandboxed = False
|
271 |
+
|
272 |
+
#: True if the environment is just an overlay
|
273 |
+
overlayed = False
|
274 |
+
|
275 |
+
#: the environment this environment is linked to if it is an overlay
|
276 |
+
linked_to: t.Optional["Environment"] = None
|
277 |
+
|
278 |
+
#: shared environments have this set to `True`. A shared environment
|
279 |
+
#: must not be modified
|
280 |
+
shared = False
|
281 |
+
|
282 |
+
#: the class that is used for code generation. See
|
283 |
+
#: :class:`~jinja2.compiler.CodeGenerator` for more information.
|
284 |
+
code_generator_class: t.Type["CodeGenerator"] = CodeGenerator
|
285 |
+
|
286 |
+
concat = "".join
|
287 |
+
|
288 |
+
#: the context class that is used for templates. See
|
289 |
+
#: :class:`~jinja2.runtime.Context` for more information.
|
290 |
+
context_class: t.Type[Context] = Context
|
291 |
+
|
292 |
+
template_class: t.Type["Template"]
|
293 |
+
|
294 |
+
def __init__(
|
295 |
+
self,
|
296 |
+
block_start_string: str = BLOCK_START_STRING,
|
297 |
+
block_end_string: str = BLOCK_END_STRING,
|
298 |
+
variable_start_string: str = VARIABLE_START_STRING,
|
299 |
+
variable_end_string: str = VARIABLE_END_STRING,
|
300 |
+
comment_start_string: str = COMMENT_START_STRING,
|
301 |
+
comment_end_string: str = COMMENT_END_STRING,
|
302 |
+
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
|
303 |
+
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
|
304 |
+
trim_blocks: bool = TRIM_BLOCKS,
|
305 |
+
lstrip_blocks: bool = LSTRIP_BLOCKS,
|
306 |
+
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
|
307 |
+
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
|
308 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
|
309 |
+
optimized: bool = True,
|
310 |
+
undefined: t.Type[Undefined] = Undefined,
|
311 |
+
finalize: t.Optional[t.Callable[..., t.Any]] = None,
|
312 |
+
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
|
313 |
+
loader: t.Optional["BaseLoader"] = None,
|
314 |
+
cache_size: int = 400,
|
315 |
+
auto_reload: bool = True,
|
316 |
+
bytecode_cache: t.Optional["BytecodeCache"] = None,
|
317 |
+
enable_async: bool = False,
|
318 |
+
):
|
319 |
+
# !!Important notice!!
|
320 |
+
# The constructor accepts quite a few arguments that should be
|
321 |
+
# passed by keyword rather than position. However it's important to
|
322 |
+
# not change the order of arguments because it's used at least
|
323 |
+
# internally in those cases:
|
324 |
+
# - spontaneous environments (i18n extension and Template)
|
325 |
+
# - unittests
|
326 |
+
# If parameter changes are required only add parameters at the end
|
327 |
+
# and don't change the arguments (or the defaults!) of the arguments
|
328 |
+
# existing already.
|
329 |
+
|
330 |
+
# lexer / parser information
|
331 |
+
self.block_start_string = block_start_string
|
332 |
+
self.block_end_string = block_end_string
|
333 |
+
self.variable_start_string = variable_start_string
|
334 |
+
self.variable_end_string = variable_end_string
|
335 |
+
self.comment_start_string = comment_start_string
|
336 |
+
self.comment_end_string = comment_end_string
|
337 |
+
self.line_statement_prefix = line_statement_prefix
|
338 |
+
self.line_comment_prefix = line_comment_prefix
|
339 |
+
self.trim_blocks = trim_blocks
|
340 |
+
self.lstrip_blocks = lstrip_blocks
|
341 |
+
self.newline_sequence = newline_sequence
|
342 |
+
self.keep_trailing_newline = keep_trailing_newline
|
343 |
+
|
344 |
+
# runtime information
|
345 |
+
self.undefined: t.Type[Undefined] = undefined
|
346 |
+
self.optimized = optimized
|
347 |
+
self.finalize = finalize
|
348 |
+
self.autoescape = autoescape
|
349 |
+
|
350 |
+
# defaults
|
351 |
+
self.filters = DEFAULT_FILTERS.copy()
|
352 |
+
self.tests = DEFAULT_TESTS.copy()
|
353 |
+
self.globals = DEFAULT_NAMESPACE.copy()
|
354 |
+
|
355 |
+
# set the loader provided
|
356 |
+
self.loader = loader
|
357 |
+
self.cache = create_cache(cache_size)
|
358 |
+
self.bytecode_cache = bytecode_cache
|
359 |
+
self.auto_reload = auto_reload
|
360 |
+
|
361 |
+
# configurable policies
|
362 |
+
self.policies = DEFAULT_POLICIES.copy()
|
363 |
+
|
364 |
+
# load extensions
|
365 |
+
self.extensions = load_extensions(self, extensions)
|
366 |
+
|
367 |
+
self.is_async = enable_async
|
368 |
+
_environment_config_check(self)
|
369 |
+
|
370 |
+
def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:
|
371 |
+
"""Adds an extension after the environment was created.
|
372 |
+
|
373 |
+
.. versionadded:: 2.5
|
374 |
+
"""
|
375 |
+
self.extensions.update(load_extensions(self, [extension]))
|
376 |
+
|
377 |
+
def extend(self, **attributes: t.Any) -> None:
|
378 |
+
"""Add the items to the instance of the environment if they do not exist
|
379 |
+
yet. This is used by :ref:`extensions <writing-extensions>` to register
|
380 |
+
callbacks and configuration values without breaking inheritance.
|
381 |
+
"""
|
382 |
+
for key, value in attributes.items():
|
383 |
+
if not hasattr(self, key):
|
384 |
+
setattr(self, key, value)
|
385 |
+
|
386 |
+
def overlay(
|
387 |
+
self,
|
388 |
+
block_start_string: str = missing,
|
389 |
+
block_end_string: str = missing,
|
390 |
+
variable_start_string: str = missing,
|
391 |
+
variable_end_string: str = missing,
|
392 |
+
comment_start_string: str = missing,
|
393 |
+
comment_end_string: str = missing,
|
394 |
+
line_statement_prefix: t.Optional[str] = missing,
|
395 |
+
line_comment_prefix: t.Optional[str] = missing,
|
396 |
+
trim_blocks: bool = missing,
|
397 |
+
lstrip_blocks: bool = missing,
|
398 |
+
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,
|
399 |
+
keep_trailing_newline: bool = missing,
|
400 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,
|
401 |
+
optimized: bool = missing,
|
402 |
+
undefined: t.Type[Undefined] = missing,
|
403 |
+
finalize: t.Optional[t.Callable[..., t.Any]] = missing,
|
404 |
+
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,
|
405 |
+
loader: t.Optional["BaseLoader"] = missing,
|
406 |
+
cache_size: int = missing,
|
407 |
+
auto_reload: bool = missing,
|
408 |
+
bytecode_cache: t.Optional["BytecodeCache"] = missing,
|
409 |
+
enable_async: bool = False,
|
410 |
+
) -> "Environment":
|
411 |
+
"""Create a new overlay environment that shares all the data with the
|
412 |
+
current environment except for cache and the overridden attributes.
|
413 |
+
Extensions cannot be removed for an overlayed environment. An overlayed
|
414 |
+
environment automatically gets all the extensions of the environment it
|
415 |
+
is linked to plus optional extra extensions.
|
416 |
+
|
417 |
+
Creating overlays should happen after the initial environment was set
|
418 |
+
up completely. Not all attributes are truly linked, some are just
|
419 |
+
copied over so modifications on the original environment may not shine
|
420 |
+
through.
|
421 |
+
|
422 |
+
.. versionchanged:: 3.1.2
|
423 |
+
Added the ``newline_sequence``,, ``keep_trailing_newline``,
|
424 |
+
and ``enable_async`` parameters to match ``__init__``.
|
425 |
+
"""
|
426 |
+
args = dict(locals())
|
427 |
+
del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
|
428 |
+
|
429 |
+
rv = object.__new__(self.__class__)
|
430 |
+
rv.__dict__.update(self.__dict__)
|
431 |
+
rv.overlayed = True
|
432 |
+
rv.linked_to = self
|
433 |
+
|
434 |
+
for key, value in args.items():
|
435 |
+
if value is not missing:
|
436 |
+
setattr(rv, key, value)
|
437 |
+
|
438 |
+
if cache_size is not missing:
|
439 |
+
rv.cache = create_cache(cache_size)
|
440 |
+
else:
|
441 |
+
rv.cache = copy_cache(self.cache)
|
442 |
+
|
443 |
+
rv.extensions = {}
|
444 |
+
for key, value in self.extensions.items():
|
445 |
+
rv.extensions[key] = value.bind(rv)
|
446 |
+
if extensions is not missing:
|
447 |
+
rv.extensions.update(load_extensions(rv, extensions))
|
448 |
+
|
449 |
+
if enable_async is not missing:
|
450 |
+
rv.is_async = enable_async
|
451 |
+
|
452 |
+
return _environment_config_check(rv)
|
453 |
+
|
454 |
+
@property
|
455 |
+
def lexer(self) -> Lexer:
|
456 |
+
"""The lexer for this environment."""
|
457 |
+
return get_lexer(self)
|
458 |
+
|
459 |
+
def iter_extensions(self) -> t.Iterator["Extension"]:
|
460 |
+
"""Iterates over the extensions by priority."""
|
461 |
+
return iter(sorted(self.extensions.values(), key=lambda x: x.priority))
|
462 |
+
|
463 |
+
def getitem(
|
464 |
+
self, obj: t.Any, argument: t.Union[str, t.Any]
|
465 |
+
) -> t.Union[t.Any, Undefined]:
|
466 |
+
"""Get an item or attribute of an object but prefer the item."""
|
467 |
+
try:
|
468 |
+
return obj[argument]
|
469 |
+
except (AttributeError, TypeError, LookupError):
|
470 |
+
if isinstance(argument, str):
|
471 |
+
try:
|
472 |
+
attr = str(argument)
|
473 |
+
except Exception:
|
474 |
+
pass
|
475 |
+
else:
|
476 |
+
try:
|
477 |
+
return getattr(obj, attr)
|
478 |
+
except AttributeError:
|
479 |
+
pass
|
480 |
+
return self.undefined(obj=obj, name=argument)
|
481 |
+
|
482 |
+
def getattr(self, obj: t.Any, attribute: str) -> t.Any:
|
483 |
+
"""Get an item or attribute of an object but prefer the attribute.
|
484 |
+
Unlike :meth:`getitem` the attribute *must* be a string.
|
485 |
+
"""
|
486 |
+
try:
|
487 |
+
return getattr(obj, attribute)
|
488 |
+
except AttributeError:
|
489 |
+
pass
|
490 |
+
try:
|
491 |
+
return obj[attribute]
|
492 |
+
except (TypeError, LookupError, AttributeError):
|
493 |
+
return self.undefined(obj=obj, name=attribute)
|
494 |
+
|
495 |
+
def _filter_test_common(
|
496 |
+
self,
|
497 |
+
name: t.Union[str, Undefined],
|
498 |
+
value: t.Any,
|
499 |
+
args: t.Optional[t.Sequence[t.Any]],
|
500 |
+
kwargs: t.Optional[t.Mapping[str, t.Any]],
|
501 |
+
context: t.Optional[Context],
|
502 |
+
eval_ctx: t.Optional[EvalContext],
|
503 |
+
is_filter: bool,
|
504 |
+
) -> t.Any:
|
505 |
+
if is_filter:
|
506 |
+
env_map = self.filters
|
507 |
+
type_name = "filter"
|
508 |
+
else:
|
509 |
+
env_map = self.tests
|
510 |
+
type_name = "test"
|
511 |
+
|
512 |
+
func = env_map.get(name) # type: ignore
|
513 |
+
|
514 |
+
if func is None:
|
515 |
+
msg = f"No {type_name} named {name!r}."
|
516 |
+
|
517 |
+
if isinstance(name, Undefined):
|
518 |
+
try:
|
519 |
+
name._fail_with_undefined_error()
|
520 |
+
except Exception as e:
|
521 |
+
msg = f"{msg} ({e}; did you forget to quote the callable name?)"
|
522 |
+
|
523 |
+
raise TemplateRuntimeError(msg)
|
524 |
+
|
525 |
+
args = [value, *(args if args is not None else ())]
|
526 |
+
kwargs = kwargs if kwargs is not None else {}
|
527 |
+
pass_arg = _PassArg.from_obj(func)
|
528 |
+
|
529 |
+
if pass_arg is _PassArg.context:
|
530 |
+
if context is None:
|
531 |
+
raise TemplateRuntimeError(
|
532 |
+
f"Attempted to invoke a context {type_name} without context."
|
533 |
+
)
|
534 |
+
|
535 |
+
args.insert(0, context)
|
536 |
+
elif pass_arg is _PassArg.eval_context:
|
537 |
+
if eval_ctx is None:
|
538 |
+
if context is not None:
|
539 |
+
eval_ctx = context.eval_ctx
|
540 |
+
else:
|
541 |
+
eval_ctx = EvalContext(self)
|
542 |
+
|
543 |
+
args.insert(0, eval_ctx)
|
544 |
+
elif pass_arg is _PassArg.environment:
|
545 |
+
args.insert(0, self)
|
546 |
+
|
547 |
+
return func(*args, **kwargs)
|
548 |
+
|
549 |
+
def call_filter(
|
550 |
+
self,
|
551 |
+
name: str,
|
552 |
+
value: t.Any,
|
553 |
+
args: t.Optional[t.Sequence[t.Any]] = None,
|
554 |
+
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
|
555 |
+
context: t.Optional[Context] = None,
|
556 |
+
eval_ctx: t.Optional[EvalContext] = None,
|
557 |
+
) -> t.Any:
|
558 |
+
"""Invoke a filter on a value the same way the compiler does.
|
559 |
+
|
560 |
+
This might return a coroutine if the filter is running from an
|
561 |
+
environment in async mode and the filter supports async
|
562 |
+
execution. It's your responsibility to await this if needed.
|
563 |
+
|
564 |
+
.. versionadded:: 2.7
|
565 |
+
"""
|
566 |
+
return self._filter_test_common(
|
567 |
+
name, value, args, kwargs, context, eval_ctx, True
|
568 |
+
)
|
569 |
+
|
570 |
+
def call_test(
|
571 |
+
self,
|
572 |
+
name: str,
|
573 |
+
value: t.Any,
|
574 |
+
args: t.Optional[t.Sequence[t.Any]] = None,
|
575 |
+
kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
|
576 |
+
context: t.Optional[Context] = None,
|
577 |
+
eval_ctx: t.Optional[EvalContext] = None,
|
578 |
+
) -> t.Any:
|
579 |
+
"""Invoke a test on a value the same way the compiler does.
|
580 |
+
|
581 |
+
This might return a coroutine if the test is running from an
|
582 |
+
environment in async mode and the test supports async execution.
|
583 |
+
It's your responsibility to await this if needed.
|
584 |
+
|
585 |
+
.. versionchanged:: 3.0
|
586 |
+
Tests support ``@pass_context``, etc. decorators. Added
|
587 |
+
the ``context`` and ``eval_ctx`` parameters.
|
588 |
+
|
589 |
+
.. versionadded:: 2.7
|
590 |
+
"""
|
591 |
+
return self._filter_test_common(
|
592 |
+
name, value, args, kwargs, context, eval_ctx, False
|
593 |
+
)
|
594 |
+
|
595 |
+
@internalcode
|
596 |
+
def parse(
|
597 |
+
self,
|
598 |
+
source: str,
|
599 |
+
name: t.Optional[str] = None,
|
600 |
+
filename: t.Optional[str] = None,
|
601 |
+
) -> nodes.Template:
|
602 |
+
"""Parse the sourcecode and return the abstract syntax tree. This
|
603 |
+
tree of nodes is used by the compiler to convert the template into
|
604 |
+
executable source- or bytecode. This is useful for debugging or to
|
605 |
+
extract information from templates.
|
606 |
+
|
607 |
+
If you are :ref:`developing Jinja extensions <writing-extensions>`
|
608 |
+
this gives you a good overview of the node tree generated.
|
609 |
+
"""
|
610 |
+
try:
|
611 |
+
return self._parse(source, name, filename)
|
612 |
+
except TemplateSyntaxError:
|
613 |
+
self.handle_exception(source=source)
|
614 |
+
|
615 |
+
def _parse(
|
616 |
+
self, source: str, name: t.Optional[str], filename: t.Optional[str]
|
617 |
+
) -> nodes.Template:
|
618 |
+
"""Internal parsing function used by `parse` and `compile`."""
|
619 |
+
return Parser(self, source, name, filename).parse()
|
620 |
+
|
621 |
+
def lex(
|
622 |
+
self,
|
623 |
+
source: str,
|
624 |
+
name: t.Optional[str] = None,
|
625 |
+
filename: t.Optional[str] = None,
|
626 |
+
) -> t.Iterator[t.Tuple[int, str, str]]:
|
627 |
+
"""Lex the given sourcecode and return a generator that yields
|
628 |
+
tokens as tuples in the form ``(lineno, token_type, value)``.
|
629 |
+
This can be useful for :ref:`extension development <writing-extensions>`
|
630 |
+
and debugging templates.
|
631 |
+
|
632 |
+
This does not perform preprocessing. If you want the preprocessing
|
633 |
+
of the extensions to be applied you have to filter source through
|
634 |
+
the :meth:`preprocess` method.
|
635 |
+
"""
|
636 |
+
source = str(source)
|
637 |
+
try:
|
638 |
+
return self.lexer.tokeniter(source, name, filename)
|
639 |
+
except TemplateSyntaxError:
|
640 |
+
self.handle_exception(source=source)
|
641 |
+
|
642 |
+
def preprocess(
|
643 |
+
self,
|
644 |
+
source: str,
|
645 |
+
name: t.Optional[str] = None,
|
646 |
+
filename: t.Optional[str] = None,
|
647 |
+
) -> str:
|
648 |
+
"""Preprocesses the source with all extensions. This is automatically
|
649 |
+
called for all parsing and compiling methods but *not* for :meth:`lex`
|
650 |
+
because there you usually only want the actual source tokenized.
|
651 |
+
"""
|
652 |
+
return reduce(
|
653 |
+
lambda s, e: e.preprocess(s, name, filename),
|
654 |
+
self.iter_extensions(),
|
655 |
+
str(source),
|
656 |
+
)
|
657 |
+
|
658 |
+
def _tokenize(
|
659 |
+
self,
|
660 |
+
source: str,
|
661 |
+
name: t.Optional[str],
|
662 |
+
filename: t.Optional[str] = None,
|
663 |
+
state: t.Optional[str] = None,
|
664 |
+
) -> TokenStream:
|
665 |
+
"""Called by the parser to do the preprocessing and filtering
|
666 |
+
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
|
667 |
+
"""
|
668 |
+
source = self.preprocess(source, name, filename)
|
669 |
+
stream = self.lexer.tokenize(source, name, filename, state)
|
670 |
+
|
671 |
+
for ext in self.iter_extensions():
|
672 |
+
stream = ext.filter_stream(stream) # type: ignore
|
673 |
+
|
674 |
+
if not isinstance(stream, TokenStream):
|
675 |
+
stream = TokenStream(stream, name, filename)
|
676 |
+
|
677 |
+
return stream
|
678 |
+
|
679 |
+
def _generate(
|
680 |
+
self,
|
681 |
+
source: nodes.Template,
|
682 |
+
name: t.Optional[str],
|
683 |
+
filename: t.Optional[str],
|
684 |
+
defer_init: bool = False,
|
685 |
+
) -> str:
|
686 |
+
"""Internal hook that can be overridden to hook a different generate
|
687 |
+
method in.
|
688 |
+
|
689 |
+
.. versionadded:: 2.5
|
690 |
+
"""
|
691 |
+
return generate( # type: ignore
|
692 |
+
source,
|
693 |
+
self,
|
694 |
+
name,
|
695 |
+
filename,
|
696 |
+
defer_init=defer_init,
|
697 |
+
optimized=self.optimized,
|
698 |
+
)
|
699 |
+
|
700 |
+
def _compile(self, source: str, filename: str) -> CodeType:
|
701 |
+
"""Internal hook that can be overridden to hook a different compile
|
702 |
+
method in.
|
703 |
+
|
704 |
+
.. versionadded:: 2.5
|
705 |
+
"""
|
706 |
+
return compile(source, filename, "exec")
|
707 |
+
|
708 |
+
@typing.overload
|
709 |
+
def compile( # type: ignore
|
710 |
+
self,
|
711 |
+
source: t.Union[str, nodes.Template],
|
712 |
+
name: t.Optional[str] = None,
|
713 |
+
filename: t.Optional[str] = None,
|
714 |
+
raw: "te.Literal[False]" = False,
|
715 |
+
defer_init: bool = False,
|
716 |
+
) -> CodeType: ...
|
717 |
+
|
718 |
+
@typing.overload
|
719 |
+
def compile(
|
720 |
+
self,
|
721 |
+
source: t.Union[str, nodes.Template],
|
722 |
+
name: t.Optional[str] = None,
|
723 |
+
filename: t.Optional[str] = None,
|
724 |
+
raw: "te.Literal[True]" = ...,
|
725 |
+
defer_init: bool = False,
|
726 |
+
) -> str: ...
|
727 |
+
|
728 |
+
@internalcode
|
729 |
+
def compile(
|
730 |
+
self,
|
731 |
+
source: t.Union[str, nodes.Template],
|
732 |
+
name: t.Optional[str] = None,
|
733 |
+
filename: t.Optional[str] = None,
|
734 |
+
raw: bool = False,
|
735 |
+
defer_init: bool = False,
|
736 |
+
) -> t.Union[str, CodeType]:
|
737 |
+
"""Compile a node or template source code. The `name` parameter is
|
738 |
+
the load name of the template after it was joined using
|
739 |
+
:meth:`join_path` if necessary, not the filename on the file system.
|
740 |
+
the `filename` parameter is the estimated filename of the template on
|
741 |
+
the file system. If the template came from a database or memory this
|
742 |
+
can be omitted.
|
743 |
+
|
744 |
+
The return value of this method is a python code object. If the `raw`
|
745 |
+
parameter is `True` the return value will be a string with python
|
746 |
+
code equivalent to the bytecode returned otherwise. This method is
|
747 |
+
mainly used internally.
|
748 |
+
|
749 |
+
`defer_init` is use internally to aid the module code generator. This
|
750 |
+
causes the generated code to be able to import without the global
|
751 |
+
environment variable to be set.
|
752 |
+
|
753 |
+
.. versionadded:: 2.4
|
754 |
+
`defer_init` parameter added.
|
755 |
+
"""
|
756 |
+
source_hint = None
|
757 |
+
try:
|
758 |
+
if isinstance(source, str):
|
759 |
+
source_hint = source
|
760 |
+
source = self._parse(source, name, filename)
|
761 |
+
source = self._generate(source, name, filename, defer_init=defer_init)
|
762 |
+
if raw:
|
763 |
+
return source
|
764 |
+
if filename is None:
|
765 |
+
filename = "<template>"
|
766 |
+
return self._compile(source, filename)
|
767 |
+
except TemplateSyntaxError:
|
768 |
+
self.handle_exception(source=source_hint)
|
769 |
+
|
770 |
+
def compile_expression(
|
771 |
+
self, source: str, undefined_to_none: bool = True
|
772 |
+
) -> "TemplateExpression":
|
773 |
+
"""A handy helper method that returns a callable that accepts keyword
|
774 |
+
arguments that appear as variables in the expression. If called it
|
775 |
+
returns the result of the expression.
|
776 |
+
|
777 |
+
This is useful if applications want to use the same rules as Jinja
|
778 |
+
in template "configuration files" or similar situations.
|
779 |
+
|
780 |
+
Example usage:
|
781 |
+
|
782 |
+
>>> env = Environment()
|
783 |
+
>>> expr = env.compile_expression('foo == 42')
|
784 |
+
>>> expr(foo=23)
|
785 |
+
False
|
786 |
+
>>> expr(foo=42)
|
787 |
+
True
|
788 |
+
|
789 |
+
Per default the return value is converted to `None` if the
|
790 |
+
expression returns an undefined value. This can be changed
|
791 |
+
by setting `undefined_to_none` to `False`.
|
792 |
+
|
793 |
+
>>> env.compile_expression('var')() is None
|
794 |
+
True
|
795 |
+
>>> env.compile_expression('var', undefined_to_none=False)()
|
796 |
+
Undefined
|
797 |
+
|
798 |
+
.. versionadded:: 2.1
|
799 |
+
"""
|
800 |
+
parser = Parser(self, source, state="variable")
|
801 |
+
try:
|
802 |
+
expr = parser.parse_expression()
|
803 |
+
if not parser.stream.eos:
|
804 |
+
raise TemplateSyntaxError(
|
805 |
+
"chunk after expression", parser.stream.current.lineno, None, None
|
806 |
+
)
|
807 |
+
expr.set_environment(self)
|
808 |
+
except TemplateSyntaxError:
|
809 |
+
self.handle_exception(source=source)
|
810 |
+
|
811 |
+
body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]
|
812 |
+
template = self.from_string(nodes.Template(body, lineno=1))
|
813 |
+
return TemplateExpression(template, undefined_to_none)
|
814 |
+
|
815 |
+
def compile_templates(
|
816 |
+
self,
|
817 |
+
target: t.Union[str, "os.PathLike[str]"],
|
818 |
+
extensions: t.Optional[t.Collection[str]] = None,
|
819 |
+
filter_func: t.Optional[t.Callable[[str], bool]] = None,
|
820 |
+
zip: t.Optional[str] = "deflated",
|
821 |
+
log_function: t.Optional[t.Callable[[str], None]] = None,
|
822 |
+
ignore_errors: bool = True,
|
823 |
+
) -> None:
|
824 |
+
"""Finds all the templates the loader can find, compiles them
|
825 |
+
and stores them in `target`. If `zip` is `None`, instead of in a
|
826 |
+
zipfile, the templates will be stored in a directory.
|
827 |
+
By default a deflate zip algorithm is used. To switch to
|
828 |
+
the stored algorithm, `zip` can be set to ``'stored'``.
|
829 |
+
|
830 |
+
`extensions` and `filter_func` are passed to :meth:`list_templates`.
|
831 |
+
Each template returned will be compiled to the target folder or
|
832 |
+
zipfile.
|
833 |
+
|
834 |
+
By default template compilation errors are ignored. In case a
|
835 |
+
log function is provided, errors are logged. If you want template
|
836 |
+
syntax errors to abort the compilation you can set `ignore_errors`
|
837 |
+
to `False` and you will get an exception on syntax errors.
|
838 |
+
|
839 |
+
.. versionadded:: 2.4
|
840 |
+
"""
|
841 |
+
from .loaders import ModuleLoader
|
842 |
+
|
843 |
+
if log_function is None:
|
844 |
+
|
845 |
+
def log_function(x: str) -> None:
|
846 |
+
pass
|
847 |
+
|
848 |
+
assert log_function is not None
|
849 |
+
assert self.loader is not None, "No loader configured."
|
850 |
+
|
851 |
+
def write_file(filename: str, data: str) -> None:
|
852 |
+
if zip:
|
853 |
+
info = ZipInfo(filename)
|
854 |
+
info.external_attr = 0o755 << 16
|
855 |
+
zip_file.writestr(info, data)
|
856 |
+
else:
|
857 |
+
with open(os.path.join(target, filename), "wb") as f:
|
858 |
+
f.write(data.encode("utf8"))
|
859 |
+
|
860 |
+
if zip is not None:
|
861 |
+
from zipfile import ZIP_DEFLATED
|
862 |
+
from zipfile import ZIP_STORED
|
863 |
+
from zipfile import ZipFile
|
864 |
+
from zipfile import ZipInfo
|
865 |
+
|
866 |
+
zip_file = ZipFile(
|
867 |
+
target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]
|
868 |
+
)
|
869 |
+
log_function(f"Compiling into Zip archive {target!r}")
|
870 |
+
else:
|
871 |
+
if not os.path.isdir(target):
|
872 |
+
os.makedirs(target)
|
873 |
+
log_function(f"Compiling into folder {target!r}")
|
874 |
+
|
875 |
+
try:
|
876 |
+
for name in self.list_templates(extensions, filter_func):
|
877 |
+
source, filename, _ = self.loader.get_source(self, name)
|
878 |
+
try:
|
879 |
+
code = self.compile(source, name, filename, True, True)
|
880 |
+
except TemplateSyntaxError as e:
|
881 |
+
if not ignore_errors:
|
882 |
+
raise
|
883 |
+
log_function(f'Could not compile "{name}": {e}')
|
884 |
+
continue
|
885 |
+
|
886 |
+
filename = ModuleLoader.get_module_filename(name)
|
887 |
+
|
888 |
+
write_file(filename, code)
|
889 |
+
log_function(f'Compiled "{name}" as {filename}')
|
890 |
+
finally:
|
891 |
+
if zip:
|
892 |
+
zip_file.close()
|
893 |
+
|
894 |
+
log_function("Finished compiling templates")
|
895 |
+
|
896 |
+
def list_templates(
|
897 |
+
self,
|
898 |
+
extensions: t.Optional[t.Collection[str]] = None,
|
899 |
+
filter_func: t.Optional[t.Callable[[str], bool]] = None,
|
900 |
+
) -> t.List[str]:
|
901 |
+
"""Returns a list of templates for this environment. This requires
|
902 |
+
that the loader supports the loader's
|
903 |
+
:meth:`~BaseLoader.list_templates` method.
|
904 |
+
|
905 |
+
If there are other files in the template folder besides the
|
906 |
+
actual templates, the returned list can be filtered. There are two
|
907 |
+
ways: either `extensions` is set to a list of file extensions for
|
908 |
+
templates, or a `filter_func` can be provided which is a callable that
|
909 |
+
is passed a template name and should return `True` if it should end up
|
910 |
+
in the result list.
|
911 |
+
|
912 |
+
If the loader does not support that, a :exc:`TypeError` is raised.
|
913 |
+
|
914 |
+
.. versionadded:: 2.4
|
915 |
+
"""
|
916 |
+
assert self.loader is not None, "No loader configured."
|
917 |
+
names = self.loader.list_templates()
|
918 |
+
|
919 |
+
if extensions is not None:
|
920 |
+
if filter_func is not None:
|
921 |
+
raise TypeError(
|
922 |
+
"either extensions or filter_func can be passed, but not both"
|
923 |
+
)
|
924 |
+
|
925 |
+
def filter_func(x: str) -> bool:
|
926 |
+
return "." in x and x.rsplit(".", 1)[1] in extensions
|
927 |
+
|
928 |
+
if filter_func is not None:
|
929 |
+
names = [name for name in names if filter_func(name)]
|
930 |
+
|
931 |
+
return names
|
932 |
+
|
933 |
+
def handle_exception(self, source: t.Optional[str] = None) -> "te.NoReturn":
|
934 |
+
"""Exception handling helper. This is used internally to either raise
|
935 |
+
rewritten exceptions or return a rendered traceback for the template.
|
936 |
+
"""
|
937 |
+
from .debug import rewrite_traceback_stack
|
938 |
+
|
939 |
+
raise rewrite_traceback_stack(source=source)
|
940 |
+
|
941 |
+
def join_path(self, template: str, parent: str) -> str:
|
942 |
+
"""Join a template with the parent. By default all the lookups are
|
943 |
+
relative to the loader root so this method returns the `template`
|
944 |
+
parameter unchanged, but if the paths should be relative to the
|
945 |
+
parent template, this function can be used to calculate the real
|
946 |
+
template name.
|
947 |
+
|
948 |
+
Subclasses may override this method and implement template path
|
949 |
+
joining here.
|
950 |
+
"""
|
951 |
+
return template
|
952 |
+
|
953 |
+
@internalcode
|
954 |
+
def _load_template(
|
955 |
+
self, name: str, globals: t.Optional[t.MutableMapping[str, t.Any]]
|
956 |
+
) -> "Template":
|
957 |
+
if self.loader is None:
|
958 |
+
raise TypeError("no loader for this environment specified")
|
959 |
+
cache_key = (weakref.ref(self.loader), name)
|
960 |
+
if self.cache is not None:
|
961 |
+
template = self.cache.get(cache_key)
|
962 |
+
if template is not None and (
|
963 |
+
not self.auto_reload or template.is_up_to_date
|
964 |
+
):
|
965 |
+
# template.globals is a ChainMap, modifying it will only
|
966 |
+
# affect the template, not the environment globals.
|
967 |
+
if globals:
|
968 |
+
template.globals.update(globals)
|
969 |
+
|
970 |
+
return template
|
971 |
+
|
972 |
+
template = self.loader.load(self, name, self.make_globals(globals))
|
973 |
+
|
974 |
+
if self.cache is not None:
|
975 |
+
self.cache[cache_key] = template
|
976 |
+
return template
|
977 |
+
|
978 |
+
@internalcode
|
979 |
+
def get_template(
|
980 |
+
self,
|
981 |
+
name: t.Union[str, "Template"],
|
982 |
+
parent: t.Optional[str] = None,
|
983 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
984 |
+
) -> "Template":
|
985 |
+
"""Load a template by name with :attr:`loader` and return a
|
986 |
+
:class:`Template`. If the template does not exist a
|
987 |
+
:exc:`TemplateNotFound` exception is raised.
|
988 |
+
|
989 |
+
:param name: Name of the template to load. When loading
|
990 |
+
templates from the filesystem, "/" is used as the path
|
991 |
+
separator, even on Windows.
|
992 |
+
:param parent: The name of the parent template importing this
|
993 |
+
template. :meth:`join_path` can be used to implement name
|
994 |
+
transformations with this.
|
995 |
+
:param globals: Extend the environment :attr:`globals` with
|
996 |
+
these extra variables available for all renders of this
|
997 |
+
template. If the template has already been loaded and
|
998 |
+
cached, its globals are updated with any new items.
|
999 |
+
|
1000 |
+
.. versionchanged:: 3.0
|
1001 |
+
If a template is loaded from cache, ``globals`` will update
|
1002 |
+
the template's globals instead of ignoring the new values.
|
1003 |
+
|
1004 |
+
.. versionchanged:: 2.4
|
1005 |
+
If ``name`` is a :class:`Template` object it is returned
|
1006 |
+
unchanged.
|
1007 |
+
"""
|
1008 |
+
if isinstance(name, Template):
|
1009 |
+
return name
|
1010 |
+
if parent is not None:
|
1011 |
+
name = self.join_path(name, parent)
|
1012 |
+
|
1013 |
+
return self._load_template(name, globals)
|
1014 |
+
|
1015 |
+
@internalcode
|
1016 |
+
def select_template(
|
1017 |
+
self,
|
1018 |
+
names: t.Iterable[t.Union[str, "Template"]],
|
1019 |
+
parent: t.Optional[str] = None,
|
1020 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
1021 |
+
) -> "Template":
|
1022 |
+
"""Like :meth:`get_template`, but tries loading multiple names.
|
1023 |
+
If none of the names can be loaded a :exc:`TemplatesNotFound`
|
1024 |
+
exception is raised.
|
1025 |
+
|
1026 |
+
:param names: List of template names to try loading in order.
|
1027 |
+
:param parent: The name of the parent template importing this
|
1028 |
+
template. :meth:`join_path` can be used to implement name
|
1029 |
+
transformations with this.
|
1030 |
+
:param globals: Extend the environment :attr:`globals` with
|
1031 |
+
these extra variables available for all renders of this
|
1032 |
+
template. If the template has already been loaded and
|
1033 |
+
cached, its globals are updated with any new items.
|
1034 |
+
|
1035 |
+
.. versionchanged:: 3.0
|
1036 |
+
If a template is loaded from cache, ``globals`` will update
|
1037 |
+
the template's globals instead of ignoring the new values.
|
1038 |
+
|
1039 |
+
.. versionchanged:: 2.11
|
1040 |
+
If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`
|
1041 |
+
is raised instead. If no templates were found and ``names``
|
1042 |
+
contains :class:`Undefined`, the message is more helpful.
|
1043 |
+
|
1044 |
+
.. versionchanged:: 2.4
|
1045 |
+
If ``names`` contains a :class:`Template` object it is
|
1046 |
+
returned unchanged.
|
1047 |
+
|
1048 |
+
.. versionadded:: 2.3
|
1049 |
+
"""
|
1050 |
+
if isinstance(names, Undefined):
|
1051 |
+
names._fail_with_undefined_error()
|
1052 |
+
|
1053 |
+
if not names:
|
1054 |
+
raise TemplatesNotFound(
|
1055 |
+
message="Tried to select from an empty list of templates."
|
1056 |
+
)
|
1057 |
+
|
1058 |
+
for name in names:
|
1059 |
+
if isinstance(name, Template):
|
1060 |
+
return name
|
1061 |
+
if parent is not None:
|
1062 |
+
name = self.join_path(name, parent)
|
1063 |
+
try:
|
1064 |
+
return self._load_template(name, globals)
|
1065 |
+
except (TemplateNotFound, UndefinedError):
|
1066 |
+
pass
|
1067 |
+
raise TemplatesNotFound(names) # type: ignore
|
1068 |
+
|
1069 |
+
@internalcode
|
1070 |
+
def get_or_select_template(
|
1071 |
+
self,
|
1072 |
+
template_name_or_list: t.Union[
|
1073 |
+
str, "Template", t.List[t.Union[str, "Template"]]
|
1074 |
+
],
|
1075 |
+
parent: t.Optional[str] = None,
|
1076 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
1077 |
+
) -> "Template":
|
1078 |
+
"""Use :meth:`select_template` if an iterable of template names
|
1079 |
+
is given, or :meth:`get_template` if one name is given.
|
1080 |
+
|
1081 |
+
.. versionadded:: 2.3
|
1082 |
+
"""
|
1083 |
+
if isinstance(template_name_or_list, (str, Undefined)):
|
1084 |
+
return self.get_template(template_name_or_list, parent, globals)
|
1085 |
+
elif isinstance(template_name_or_list, Template):
|
1086 |
+
return template_name_or_list
|
1087 |
+
return self.select_template(template_name_or_list, parent, globals)
|
1088 |
+
|
1089 |
+
def from_string(
|
1090 |
+
self,
|
1091 |
+
source: t.Union[str, nodes.Template],
|
1092 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
1093 |
+
template_class: t.Optional[t.Type["Template"]] = None,
|
1094 |
+
) -> "Template":
|
1095 |
+
"""Load a template from a source string without using
|
1096 |
+
:attr:`loader`.
|
1097 |
+
|
1098 |
+
:param source: Jinja source to compile into a template.
|
1099 |
+
:param globals: Extend the environment :attr:`globals` with
|
1100 |
+
these extra variables available for all renders of this
|
1101 |
+
template. If the template has already been loaded and
|
1102 |
+
cached, its globals are updated with any new items.
|
1103 |
+
:param template_class: Return an instance of this
|
1104 |
+
:class:`Template` class.
|
1105 |
+
"""
|
1106 |
+
gs = self.make_globals(globals)
|
1107 |
+
cls = template_class or self.template_class
|
1108 |
+
return cls.from_code(self, self.compile(source), gs, None)
|
1109 |
+
|
1110 |
+
def make_globals(
|
1111 |
+
self, d: t.Optional[t.MutableMapping[str, t.Any]]
|
1112 |
+
) -> t.MutableMapping[str, t.Any]:
|
1113 |
+
"""Make the globals map for a template. Any given template
|
1114 |
+
globals overlay the environment :attr:`globals`.
|
1115 |
+
|
1116 |
+
Returns a :class:`collections.ChainMap`. This allows any changes
|
1117 |
+
to a template's globals to only affect that template, while
|
1118 |
+
changes to the environment's globals are still reflected.
|
1119 |
+
However, avoid modifying any globals after a template is loaded.
|
1120 |
+
|
1121 |
+
:param d: Dict of template-specific globals.
|
1122 |
+
|
1123 |
+
.. versionchanged:: 3.0
|
1124 |
+
Use :class:`collections.ChainMap` to always prevent mutating
|
1125 |
+
environment globals.
|
1126 |
+
"""
|
1127 |
+
if d is None:
|
1128 |
+
d = {}
|
1129 |
+
|
1130 |
+
return ChainMap(d, self.globals)
|
1131 |
+
|
1132 |
+
|
1133 |
+
class Template:
|
1134 |
+
"""A compiled template that can be rendered.
|
1135 |
+
|
1136 |
+
Use the methods on :class:`Environment` to create or load templates.
|
1137 |
+
The environment is used to configure how templates are compiled and
|
1138 |
+
behave.
|
1139 |
+
|
1140 |
+
It is also possible to create a template object directly. This is
|
1141 |
+
not usually recommended. The constructor takes most of the same
|
1142 |
+
arguments as :class:`Environment`. All templates created with the
|
1143 |
+
same environment arguments share the same ephemeral ``Environment``
|
1144 |
+
instance behind the scenes.
|
1145 |
+
|
1146 |
+
A template object should be considered immutable. Modifications on
|
1147 |
+
the object are not supported.
|
1148 |
+
"""
|
1149 |
+
|
1150 |
+
#: Type of environment to create when creating a template directly
|
1151 |
+
#: rather than through an existing environment.
|
1152 |
+
environment_class: t.Type[Environment] = Environment
|
1153 |
+
|
1154 |
+
environment: Environment
|
1155 |
+
globals: t.MutableMapping[str, t.Any]
|
1156 |
+
name: t.Optional[str]
|
1157 |
+
filename: t.Optional[str]
|
1158 |
+
blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]]
|
1159 |
+
root_render_func: t.Callable[[Context], t.Iterator[str]]
|
1160 |
+
_module: t.Optional["TemplateModule"]
|
1161 |
+
_debug_info: str
|
1162 |
+
_uptodate: t.Optional[t.Callable[[], bool]]
|
1163 |
+
|
1164 |
+
def __new__(
|
1165 |
+
cls,
|
1166 |
+
source: t.Union[str, nodes.Template],
|
1167 |
+
block_start_string: str = BLOCK_START_STRING,
|
1168 |
+
block_end_string: str = BLOCK_END_STRING,
|
1169 |
+
variable_start_string: str = VARIABLE_START_STRING,
|
1170 |
+
variable_end_string: str = VARIABLE_END_STRING,
|
1171 |
+
comment_start_string: str = COMMENT_START_STRING,
|
1172 |
+
comment_end_string: str = COMMENT_END_STRING,
|
1173 |
+
line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,
|
1174 |
+
line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,
|
1175 |
+
trim_blocks: bool = TRIM_BLOCKS,
|
1176 |
+
lstrip_blocks: bool = LSTRIP_BLOCKS,
|
1177 |
+
newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,
|
1178 |
+
keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,
|
1179 |
+
extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),
|
1180 |
+
optimized: bool = True,
|
1181 |
+
undefined: t.Type[Undefined] = Undefined,
|
1182 |
+
finalize: t.Optional[t.Callable[..., t.Any]] = None,
|
1183 |
+
autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,
|
1184 |
+
enable_async: bool = False,
|
1185 |
+
) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...
|
1186 |
+
env = get_spontaneous_environment(
|
1187 |
+
cls.environment_class, # type: ignore
|
1188 |
+
block_start_string,
|
1189 |
+
block_end_string,
|
1190 |
+
variable_start_string,
|
1191 |
+
variable_end_string,
|
1192 |
+
comment_start_string,
|
1193 |
+
comment_end_string,
|
1194 |
+
line_statement_prefix,
|
1195 |
+
line_comment_prefix,
|
1196 |
+
trim_blocks,
|
1197 |
+
lstrip_blocks,
|
1198 |
+
newline_sequence,
|
1199 |
+
keep_trailing_newline,
|
1200 |
+
frozenset(extensions),
|
1201 |
+
optimized,
|
1202 |
+
undefined, # type: ignore
|
1203 |
+
finalize,
|
1204 |
+
autoescape,
|
1205 |
+
None,
|
1206 |
+
0,
|
1207 |
+
False,
|
1208 |
+
None,
|
1209 |
+
enable_async,
|
1210 |
+
)
|
1211 |
+
return env.from_string(source, template_class=cls)
|
1212 |
+
|
1213 |
+
@classmethod
|
1214 |
+
def from_code(
|
1215 |
+
cls,
|
1216 |
+
environment: Environment,
|
1217 |
+
code: CodeType,
|
1218 |
+
globals: t.MutableMapping[str, t.Any],
|
1219 |
+
uptodate: t.Optional[t.Callable[[], bool]] = None,
|
1220 |
+
) -> "Template":
|
1221 |
+
"""Creates a template object from compiled code and the globals. This
|
1222 |
+
is used by the loaders and environment to create a template object.
|
1223 |
+
"""
|
1224 |
+
namespace = {"environment": environment, "__file__": code.co_filename}
|
1225 |
+
exec(code, namespace)
|
1226 |
+
rv = cls._from_namespace(environment, namespace, globals)
|
1227 |
+
rv._uptodate = uptodate
|
1228 |
+
return rv
|
1229 |
+
|
1230 |
+
@classmethod
|
1231 |
+
def from_module_dict(
|
1232 |
+
cls,
|
1233 |
+
environment: Environment,
|
1234 |
+
module_dict: t.MutableMapping[str, t.Any],
|
1235 |
+
globals: t.MutableMapping[str, t.Any],
|
1236 |
+
) -> "Template":
|
1237 |
+
"""Creates a template object from a module. This is used by the
|
1238 |
+
module loader to create a template object.
|
1239 |
+
|
1240 |
+
.. versionadded:: 2.4
|
1241 |
+
"""
|
1242 |
+
return cls._from_namespace(environment, module_dict, globals)
|
1243 |
+
|
1244 |
+
@classmethod
|
1245 |
+
def _from_namespace(
|
1246 |
+
cls,
|
1247 |
+
environment: Environment,
|
1248 |
+
namespace: t.MutableMapping[str, t.Any],
|
1249 |
+
globals: t.MutableMapping[str, t.Any],
|
1250 |
+
) -> "Template":
|
1251 |
+
t: "Template" = object.__new__(cls)
|
1252 |
+
t.environment = environment
|
1253 |
+
t.globals = globals
|
1254 |
+
t.name = namespace["name"]
|
1255 |
+
t.filename = namespace["__file__"]
|
1256 |
+
t.blocks = namespace["blocks"]
|
1257 |
+
|
1258 |
+
# render function and module
|
1259 |
+
t.root_render_func = namespace["root"]
|
1260 |
+
t._module = None
|
1261 |
+
|
1262 |
+
# debug and loader helpers
|
1263 |
+
t._debug_info = namespace["debug_info"]
|
1264 |
+
t._uptodate = None
|
1265 |
+
|
1266 |
+
# store the reference
|
1267 |
+
namespace["environment"] = environment
|
1268 |
+
namespace["__jinja_template__"] = t
|
1269 |
+
|
1270 |
+
return t
|
1271 |
+
|
1272 |
+
def render(self, *args: t.Any, **kwargs: t.Any) -> str:
|
1273 |
+
"""This method accepts the same arguments as the `dict` constructor:
|
1274 |
+
A dict, a dict subclass or some keyword arguments. If no arguments
|
1275 |
+
are given the context will be empty. These two calls do the same::
|
1276 |
+
|
1277 |
+
template.render(knights='that say nih')
|
1278 |
+
template.render({'knights': 'that say nih'})
|
1279 |
+
|
1280 |
+
This will return the rendered template as a string.
|
1281 |
+
"""
|
1282 |
+
if self.environment.is_async:
|
1283 |
+
import asyncio
|
1284 |
+
|
1285 |
+
close = False
|
1286 |
+
|
1287 |
+
try:
|
1288 |
+
loop = asyncio.get_running_loop()
|
1289 |
+
except RuntimeError:
|
1290 |
+
loop = asyncio.new_event_loop()
|
1291 |
+
close = True
|
1292 |
+
|
1293 |
+
try:
|
1294 |
+
return loop.run_until_complete(self.render_async(*args, **kwargs))
|
1295 |
+
finally:
|
1296 |
+
if close:
|
1297 |
+
loop.close()
|
1298 |
+
|
1299 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
1300 |
+
|
1301 |
+
try:
|
1302 |
+
return self.environment.concat(self.root_render_func(ctx)) # type: ignore
|
1303 |
+
except Exception:
|
1304 |
+
self.environment.handle_exception()
|
1305 |
+
|
1306 |
+
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:
|
1307 |
+
"""This works similar to :meth:`render` but returns a coroutine
|
1308 |
+
that when awaited returns the entire rendered template string. This
|
1309 |
+
requires the async feature to be enabled.
|
1310 |
+
|
1311 |
+
Example usage::
|
1312 |
+
|
1313 |
+
await template.render_async(knights='that say nih; asynchronously')
|
1314 |
+
"""
|
1315 |
+
if not self.environment.is_async:
|
1316 |
+
raise RuntimeError(
|
1317 |
+
"The environment was not created with async mode enabled."
|
1318 |
+
)
|
1319 |
+
|
1320 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
1321 |
+
|
1322 |
+
try:
|
1323 |
+
return self.environment.concat( # type: ignore
|
1324 |
+
[n async for n in self.root_render_func(ctx)] # type: ignore
|
1325 |
+
)
|
1326 |
+
except Exception:
|
1327 |
+
return self.environment.handle_exception()
|
1328 |
+
|
1329 |
+
def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":
|
1330 |
+
"""Works exactly like :meth:`generate` but returns a
|
1331 |
+
:class:`TemplateStream`.
|
1332 |
+
"""
|
1333 |
+
return TemplateStream(self.generate(*args, **kwargs))
|
1334 |
+
|
1335 |
+
def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:
|
1336 |
+
"""For very large templates it can be useful to not render the whole
|
1337 |
+
template at once but evaluate each statement after another and yield
|
1338 |
+
piece for piece. This method basically does exactly that and returns
|
1339 |
+
a generator that yields one item after another as strings.
|
1340 |
+
|
1341 |
+
It accepts the same arguments as :meth:`render`.
|
1342 |
+
"""
|
1343 |
+
if self.environment.is_async:
|
1344 |
+
import asyncio
|
1345 |
+
|
1346 |
+
async def to_list() -> t.List[str]:
|
1347 |
+
return [x async for x in self.generate_async(*args, **kwargs)]
|
1348 |
+
|
1349 |
+
yield from asyncio.run(to_list())
|
1350 |
+
return
|
1351 |
+
|
1352 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
1353 |
+
|
1354 |
+
try:
|
1355 |
+
yield from self.root_render_func(ctx)
|
1356 |
+
except Exception:
|
1357 |
+
yield self.environment.handle_exception()
|
1358 |
+
|
1359 |
+
async def generate_async(
|
1360 |
+
self, *args: t.Any, **kwargs: t.Any
|
1361 |
+
) -> t.AsyncIterator[str]:
|
1362 |
+
"""An async version of :meth:`generate`. Works very similarly but
|
1363 |
+
returns an async iterator instead.
|
1364 |
+
"""
|
1365 |
+
if not self.environment.is_async:
|
1366 |
+
raise RuntimeError(
|
1367 |
+
"The environment was not created with async mode enabled."
|
1368 |
+
)
|
1369 |
+
|
1370 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
1371 |
+
|
1372 |
+
try:
|
1373 |
+
async for event in self.root_render_func(ctx): # type: ignore
|
1374 |
+
yield event
|
1375 |
+
except Exception:
|
1376 |
+
yield self.environment.handle_exception()
|
1377 |
+
|
1378 |
+
def new_context(
|
1379 |
+
self,
|
1380 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
1381 |
+
shared: bool = False,
|
1382 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
1383 |
+
) -> Context:
|
1384 |
+
"""Create a new :class:`Context` for this template. The vars
|
1385 |
+
provided will be passed to the template. Per default the globals
|
1386 |
+
are added to the context. If shared is set to `True` the data
|
1387 |
+
is passed as is to the context without adding the globals.
|
1388 |
+
|
1389 |
+
`locals` can be a dict of local variables for internal usage.
|
1390 |
+
"""
|
1391 |
+
return new_context(
|
1392 |
+
self.environment, self.name, self.blocks, vars, shared, self.globals, locals
|
1393 |
+
)
|
1394 |
+
|
1395 |
+
def make_module(
|
1396 |
+
self,
|
1397 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
1398 |
+
shared: bool = False,
|
1399 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
1400 |
+
) -> "TemplateModule":
|
1401 |
+
"""This method works like the :attr:`module` attribute when called
|
1402 |
+
without arguments but it will evaluate the template on every call
|
1403 |
+
rather than caching it. It's also possible to provide
|
1404 |
+
a dict which is then used as context. The arguments are the same
|
1405 |
+
as for the :meth:`new_context` method.
|
1406 |
+
"""
|
1407 |
+
ctx = self.new_context(vars, shared, locals)
|
1408 |
+
return TemplateModule(self, ctx)
|
1409 |
+
|
1410 |
+
async def make_module_async(
|
1411 |
+
self,
|
1412 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
1413 |
+
shared: bool = False,
|
1414 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
1415 |
+
) -> "TemplateModule":
|
1416 |
+
"""As template module creation can invoke template code for
|
1417 |
+
asynchronous executions this method must be used instead of the
|
1418 |
+
normal :meth:`make_module` one. Likewise the module attribute
|
1419 |
+
becomes unavailable in async mode.
|
1420 |
+
"""
|
1421 |
+
ctx = self.new_context(vars, shared, locals)
|
1422 |
+
return TemplateModule(
|
1423 |
+
self,
|
1424 |
+
ctx,
|
1425 |
+
[x async for x in self.root_render_func(ctx)], # type: ignore
|
1426 |
+
)
|
1427 |
+
|
1428 |
+
@internalcode
|
1429 |
+
def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":
|
1430 |
+
"""If a context is passed in, this means that the template was
|
1431 |
+
imported. Imported templates have access to the current
|
1432 |
+
template's globals by default, but they can only be accessed via
|
1433 |
+
the context during runtime.
|
1434 |
+
|
1435 |
+
If there are new globals, we need to create a new module because
|
1436 |
+
the cached module is already rendered and will not have access
|
1437 |
+
to globals from the current context. This new module is not
|
1438 |
+
cached because the template can be imported elsewhere, and it
|
1439 |
+
should have access to only the current template's globals.
|
1440 |
+
"""
|
1441 |
+
if self.environment.is_async:
|
1442 |
+
raise RuntimeError("Module is not available in async mode.")
|
1443 |
+
|
1444 |
+
if ctx is not None:
|
1445 |
+
keys = ctx.globals_keys - self.globals.keys()
|
1446 |
+
|
1447 |
+
if keys:
|
1448 |
+
return self.make_module({k: ctx.parent[k] for k in keys})
|
1449 |
+
|
1450 |
+
if self._module is None:
|
1451 |
+
self._module = self.make_module()
|
1452 |
+
|
1453 |
+
return self._module
|
1454 |
+
|
1455 |
+
async def _get_default_module_async(
|
1456 |
+
self, ctx: t.Optional[Context] = None
|
1457 |
+
) -> "TemplateModule":
|
1458 |
+
if ctx is not None:
|
1459 |
+
keys = ctx.globals_keys - self.globals.keys()
|
1460 |
+
|
1461 |
+
if keys:
|
1462 |
+
return await self.make_module_async({k: ctx.parent[k] for k in keys})
|
1463 |
+
|
1464 |
+
if self._module is None:
|
1465 |
+
self._module = await self.make_module_async()
|
1466 |
+
|
1467 |
+
return self._module
|
1468 |
+
|
1469 |
+
@property
|
1470 |
+
def module(self) -> "TemplateModule":
|
1471 |
+
"""The template as module. This is used for imports in the
|
1472 |
+
template runtime but is also useful if one wants to access
|
1473 |
+
exported template variables from the Python layer:
|
1474 |
+
|
1475 |
+
>>> t = Template('{% macro foo() %}42{% endmacro %}23')
|
1476 |
+
>>> str(t.module)
|
1477 |
+
'23'
|
1478 |
+
>>> t.module.foo() == u'42'
|
1479 |
+
True
|
1480 |
+
|
1481 |
+
This attribute is not available if async mode is enabled.
|
1482 |
+
"""
|
1483 |
+
return self._get_default_module()
|
1484 |
+
|
1485 |
+
def get_corresponding_lineno(self, lineno: int) -> int:
|
1486 |
+
"""Return the source line number of a line number in the
|
1487 |
+
generated bytecode as they are not in sync.
|
1488 |
+
"""
|
1489 |
+
for template_line, code_line in reversed(self.debug_info):
|
1490 |
+
if code_line <= lineno:
|
1491 |
+
return template_line
|
1492 |
+
return 1
|
1493 |
+
|
1494 |
+
@property
|
1495 |
+
def is_up_to_date(self) -> bool:
|
1496 |
+
"""If this variable is `False` there is a newer version available."""
|
1497 |
+
if self._uptodate is None:
|
1498 |
+
return True
|
1499 |
+
return self._uptodate()
|
1500 |
+
|
1501 |
+
@property
|
1502 |
+
def debug_info(self) -> t.List[t.Tuple[int, int]]:
|
1503 |
+
"""The debug info mapping."""
|
1504 |
+
if self._debug_info:
|
1505 |
+
return [
|
1506 |
+
tuple(map(int, x.split("="))) # type: ignore
|
1507 |
+
for x in self._debug_info.split("&")
|
1508 |
+
]
|
1509 |
+
|
1510 |
+
return []
|
1511 |
+
|
1512 |
+
def __repr__(self) -> str:
|
1513 |
+
if self.name is None:
|
1514 |
+
name = f"memory:{id(self):x}"
|
1515 |
+
else:
|
1516 |
+
name = repr(self.name)
|
1517 |
+
return f"<{type(self).__name__} {name}>"
|
1518 |
+
|
1519 |
+
|
1520 |
+
class TemplateModule:
|
1521 |
+
"""Represents an imported template. All the exported names of the
|
1522 |
+
template are available as attributes on this object. Additionally
|
1523 |
+
converting it into a string renders the contents.
|
1524 |
+
"""
|
1525 |
+
|
1526 |
+
def __init__(
|
1527 |
+
self,
|
1528 |
+
template: Template,
|
1529 |
+
context: Context,
|
1530 |
+
body_stream: t.Optional[t.Iterable[str]] = None,
|
1531 |
+
) -> None:
|
1532 |
+
if body_stream is None:
|
1533 |
+
if context.environment.is_async:
|
1534 |
+
raise RuntimeError(
|
1535 |
+
"Async mode requires a body stream to be passed to"
|
1536 |
+
" a template module. Use the async methods of the"
|
1537 |
+
" API you are using."
|
1538 |
+
)
|
1539 |
+
|
1540 |
+
body_stream = list(template.root_render_func(context))
|
1541 |
+
|
1542 |
+
self._body_stream = body_stream
|
1543 |
+
self.__dict__.update(context.get_exported())
|
1544 |
+
self.__name__ = template.name
|
1545 |
+
|
1546 |
+
def __html__(self) -> Markup:
|
1547 |
+
return Markup(concat(self._body_stream))
|
1548 |
+
|
1549 |
+
def __str__(self) -> str:
|
1550 |
+
return concat(self._body_stream)
|
1551 |
+
|
1552 |
+
def __repr__(self) -> str:
|
1553 |
+
if self.__name__ is None:
|
1554 |
+
name = f"memory:{id(self):x}"
|
1555 |
+
else:
|
1556 |
+
name = repr(self.__name__)
|
1557 |
+
return f"<{type(self).__name__} {name}>"
|
1558 |
+
|
1559 |
+
|
1560 |
+
class TemplateExpression:
|
1561 |
+
"""The :meth:`jinja2.Environment.compile_expression` method returns an
|
1562 |
+
instance of this object. It encapsulates the expression-like access
|
1563 |
+
to the template with an expression it wraps.
|
1564 |
+
"""
|
1565 |
+
|
1566 |
+
def __init__(self, template: Template, undefined_to_none: bool) -> None:
|
1567 |
+
self._template = template
|
1568 |
+
self._undefined_to_none = undefined_to_none
|
1569 |
+
|
1570 |
+
def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]:
|
1571 |
+
context = self._template.new_context(dict(*args, **kwargs))
|
1572 |
+
consume(self._template.root_render_func(context))
|
1573 |
+
rv = context.vars["result"]
|
1574 |
+
if self._undefined_to_none and isinstance(rv, Undefined):
|
1575 |
+
rv = None
|
1576 |
+
return rv
|
1577 |
+
|
1578 |
+
|
1579 |
+
class TemplateStream:
|
1580 |
+
"""A template stream works pretty much like an ordinary python generator
|
1581 |
+
but it can buffer multiple items to reduce the number of total iterations.
|
1582 |
+
Per default the output is unbuffered which means that for every unbuffered
|
1583 |
+
instruction in the template one string is yielded.
|
1584 |
+
|
1585 |
+
If buffering is enabled with a buffer size of 5, five items are combined
|
1586 |
+
into a new string. This is mainly useful if you are streaming
|
1587 |
+
big templates to a client via WSGI which flushes after each iteration.
|
1588 |
+
"""
|
1589 |
+
|
1590 |
+
def __init__(self, gen: t.Iterator[str]) -> None:
|
1591 |
+
self._gen = gen
|
1592 |
+
self.disable_buffering()
|
1593 |
+
|
1594 |
+
def dump(
|
1595 |
+
self,
|
1596 |
+
fp: t.Union[str, t.IO[bytes]],
|
1597 |
+
encoding: t.Optional[str] = None,
|
1598 |
+
errors: t.Optional[str] = "strict",
|
1599 |
+
) -> None:
|
1600 |
+
"""Dump the complete stream into a file or file-like object.
|
1601 |
+
Per default strings are written, if you want to encode
|
1602 |
+
before writing specify an `encoding`.
|
1603 |
+
|
1604 |
+
Example usage::
|
1605 |
+
|
1606 |
+
Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
|
1607 |
+
"""
|
1608 |
+
close = False
|
1609 |
+
|
1610 |
+
if isinstance(fp, str):
|
1611 |
+
if encoding is None:
|
1612 |
+
encoding = "utf-8"
|
1613 |
+
|
1614 |
+
real_fp: t.IO[bytes] = open(fp, "wb")
|
1615 |
+
close = True
|
1616 |
+
else:
|
1617 |
+
real_fp = fp
|
1618 |
+
|
1619 |
+
try:
|
1620 |
+
if encoding is not None:
|
1621 |
+
iterable = (x.encode(encoding, errors) for x in self) # type: ignore
|
1622 |
+
else:
|
1623 |
+
iterable = self # type: ignore
|
1624 |
+
|
1625 |
+
if hasattr(real_fp, "writelines"):
|
1626 |
+
real_fp.writelines(iterable)
|
1627 |
+
else:
|
1628 |
+
for item in iterable:
|
1629 |
+
real_fp.write(item)
|
1630 |
+
finally:
|
1631 |
+
if close:
|
1632 |
+
real_fp.close()
|
1633 |
+
|
1634 |
+
def disable_buffering(self) -> None:
|
1635 |
+
"""Disable the output buffering."""
|
1636 |
+
self._next = partial(next, self._gen)
|
1637 |
+
self.buffered = False
|
1638 |
+
|
1639 |
+
def _buffered_generator(self, size: int) -> t.Iterator[str]:
|
1640 |
+
buf: t.List[str] = []
|
1641 |
+
c_size = 0
|
1642 |
+
push = buf.append
|
1643 |
+
|
1644 |
+
while True:
|
1645 |
+
try:
|
1646 |
+
while c_size < size:
|
1647 |
+
c = next(self._gen)
|
1648 |
+
push(c)
|
1649 |
+
if c:
|
1650 |
+
c_size += 1
|
1651 |
+
except StopIteration:
|
1652 |
+
if not c_size:
|
1653 |
+
return
|
1654 |
+
yield concat(buf)
|
1655 |
+
del buf[:]
|
1656 |
+
c_size = 0
|
1657 |
+
|
1658 |
+
def enable_buffering(self, size: int = 5) -> None:
|
1659 |
+
"""Enable buffering. Buffer `size` items before yielding them."""
|
1660 |
+
if size <= 1:
|
1661 |
+
raise ValueError("buffer size too small")
|
1662 |
+
|
1663 |
+
self.buffered = True
|
1664 |
+
self._next = partial(next, self._buffered_generator(size))
|
1665 |
+
|
1666 |
+
def __iter__(self) -> "TemplateStream":
|
1667 |
+
return self
|
1668 |
+
|
1669 |
+
def __next__(self) -> str:
|
1670 |
+
return self._next() # type: ignore
|
1671 |
+
|
1672 |
+
|
1673 |
+
# hook in default template class. if anyone reads this comment: ignore that
|
1674 |
+
# it's possible to use custom templates ;-)
|
1675 |
+
Environment.template_class = Template
|
llmeval-env/lib/python3.10/site-packages/jinja2/exceptions.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
|
3 |
+
if t.TYPE_CHECKING:
|
4 |
+
from .runtime import Undefined
|
5 |
+
|
6 |
+
|
7 |
+
class TemplateError(Exception):
|
8 |
+
"""Baseclass for all template errors."""
|
9 |
+
|
10 |
+
def __init__(self, message: t.Optional[str] = None) -> None:
|
11 |
+
super().__init__(message)
|
12 |
+
|
13 |
+
@property
|
14 |
+
def message(self) -> t.Optional[str]:
|
15 |
+
return self.args[0] if self.args else None
|
16 |
+
|
17 |
+
|
18 |
+
class TemplateNotFound(IOError, LookupError, TemplateError):
|
19 |
+
"""Raised if a template does not exist.
|
20 |
+
|
21 |
+
.. versionchanged:: 2.11
|
22 |
+
If the given name is :class:`Undefined` and no message was
|
23 |
+
provided, an :exc:`UndefinedError` is raised.
|
24 |
+
"""
|
25 |
+
|
26 |
+
# Silence the Python warning about message being deprecated since
|
27 |
+
# it's not valid here.
|
28 |
+
message: t.Optional[str] = None
|
29 |
+
|
30 |
+
def __init__(
|
31 |
+
self,
|
32 |
+
name: t.Optional[t.Union[str, "Undefined"]],
|
33 |
+
message: t.Optional[str] = None,
|
34 |
+
) -> None:
|
35 |
+
IOError.__init__(self, name)
|
36 |
+
|
37 |
+
if message is None:
|
38 |
+
from .runtime import Undefined
|
39 |
+
|
40 |
+
if isinstance(name, Undefined):
|
41 |
+
name._fail_with_undefined_error()
|
42 |
+
|
43 |
+
message = name
|
44 |
+
|
45 |
+
self.message = message
|
46 |
+
self.name = name
|
47 |
+
self.templates = [name]
|
48 |
+
|
49 |
+
def __str__(self) -> str:
|
50 |
+
return str(self.message)
|
51 |
+
|
52 |
+
|
53 |
+
class TemplatesNotFound(TemplateNotFound):
|
54 |
+
"""Like :class:`TemplateNotFound` but raised if multiple templates
|
55 |
+
are selected. This is a subclass of :class:`TemplateNotFound`
|
56 |
+
exception, so just catching the base exception will catch both.
|
57 |
+
|
58 |
+
.. versionchanged:: 2.11
|
59 |
+
If a name in the list of names is :class:`Undefined`, a message
|
60 |
+
about it being undefined is shown rather than the empty string.
|
61 |
+
|
62 |
+
.. versionadded:: 2.2
|
63 |
+
"""
|
64 |
+
|
65 |
+
def __init__(
|
66 |
+
self,
|
67 |
+
names: t.Sequence[t.Union[str, "Undefined"]] = (),
|
68 |
+
message: t.Optional[str] = None,
|
69 |
+
) -> None:
|
70 |
+
if message is None:
|
71 |
+
from .runtime import Undefined
|
72 |
+
|
73 |
+
parts = []
|
74 |
+
|
75 |
+
for name in names:
|
76 |
+
if isinstance(name, Undefined):
|
77 |
+
parts.append(name._undefined_message)
|
78 |
+
else:
|
79 |
+
parts.append(name)
|
80 |
+
|
81 |
+
parts_str = ", ".join(map(str, parts))
|
82 |
+
message = f"none of the templates given were found: {parts_str}"
|
83 |
+
|
84 |
+
super().__init__(names[-1] if names else None, message)
|
85 |
+
self.templates = list(names)
|
86 |
+
|
87 |
+
|
88 |
+
class TemplateSyntaxError(TemplateError):
|
89 |
+
"""Raised to tell the user that there is a problem with the template."""
|
90 |
+
|
91 |
+
def __init__(
|
92 |
+
self,
|
93 |
+
message: str,
|
94 |
+
lineno: int,
|
95 |
+
name: t.Optional[str] = None,
|
96 |
+
filename: t.Optional[str] = None,
|
97 |
+
) -> None:
|
98 |
+
super().__init__(message)
|
99 |
+
self.lineno = lineno
|
100 |
+
self.name = name
|
101 |
+
self.filename = filename
|
102 |
+
self.source: t.Optional[str] = None
|
103 |
+
|
104 |
+
# this is set to True if the debug.translate_syntax_error
|
105 |
+
# function translated the syntax error into a new traceback
|
106 |
+
self.translated = False
|
107 |
+
|
108 |
+
def __str__(self) -> str:
|
109 |
+
# for translated errors we only return the message
|
110 |
+
if self.translated:
|
111 |
+
return t.cast(str, self.message)
|
112 |
+
|
113 |
+
# otherwise attach some stuff
|
114 |
+
location = f"line {self.lineno}"
|
115 |
+
name = self.filename or self.name
|
116 |
+
if name:
|
117 |
+
location = f'File "{name}", {location}'
|
118 |
+
lines = [t.cast(str, self.message), " " + location]
|
119 |
+
|
120 |
+
# if the source is set, add the line to the output
|
121 |
+
if self.source is not None:
|
122 |
+
try:
|
123 |
+
line = self.source.splitlines()[self.lineno - 1]
|
124 |
+
except IndexError:
|
125 |
+
pass
|
126 |
+
else:
|
127 |
+
lines.append(" " + line.strip())
|
128 |
+
|
129 |
+
return "\n".join(lines)
|
130 |
+
|
131 |
+
def __reduce__(self): # type: ignore
|
132 |
+
# https://bugs.python.org/issue1692335 Exceptions that take
|
133 |
+
# multiple required arguments have problems with pickling.
|
134 |
+
# Without this, raises TypeError: __init__() missing 1 required
|
135 |
+
# positional argument: 'lineno'
|
136 |
+
return self.__class__, (self.message, self.lineno, self.name, self.filename)
|
137 |
+
|
138 |
+
|
139 |
+
class TemplateAssertionError(TemplateSyntaxError):
|
140 |
+
"""Like a template syntax error, but covers cases where something in the
|
141 |
+
template caused an error at compile time that wasn't necessarily caused
|
142 |
+
by a syntax error. However it's a direct subclass of
|
143 |
+
:exc:`TemplateSyntaxError` and has the same attributes.
|
144 |
+
"""
|
145 |
+
|
146 |
+
|
147 |
+
class TemplateRuntimeError(TemplateError):
|
148 |
+
"""A generic runtime error in the template engine. Under some situations
|
149 |
+
Jinja may raise this exception.
|
150 |
+
"""
|
151 |
+
|
152 |
+
|
153 |
+
class UndefinedError(TemplateRuntimeError):
|
154 |
+
"""Raised if a template tries to operate on :class:`Undefined`."""
|
155 |
+
|
156 |
+
|
157 |
+
class SecurityError(TemplateRuntimeError):
|
158 |
+
"""Raised if a template tries to do something insecure if the
|
159 |
+
sandbox is enabled.
|
160 |
+
"""
|
161 |
+
|
162 |
+
|
163 |
+
class FilterArgumentError(TemplateRuntimeError):
|
164 |
+
"""This error is raised if a filter was called with inappropriate
|
165 |
+
arguments
|
166 |
+
"""
|
llmeval-env/lib/python3.10/site-packages/jinja2/ext.py
ADDED
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Extension API for adding custom tags and behavior."""
|
2 |
+
|
3 |
+
import pprint
|
4 |
+
import re
|
5 |
+
import typing as t
|
6 |
+
|
7 |
+
from markupsafe import Markup
|
8 |
+
|
9 |
+
from . import defaults
|
10 |
+
from . import nodes
|
11 |
+
from .environment import Environment
|
12 |
+
from .exceptions import TemplateAssertionError
|
13 |
+
from .exceptions import TemplateSyntaxError
|
14 |
+
from .runtime import concat # type: ignore
|
15 |
+
from .runtime import Context
|
16 |
+
from .runtime import Undefined
|
17 |
+
from .utils import import_string
|
18 |
+
from .utils import pass_context
|
19 |
+
|
20 |
+
if t.TYPE_CHECKING:
|
21 |
+
import typing_extensions as te
|
22 |
+
|
23 |
+
from .lexer import Token
|
24 |
+
from .lexer import TokenStream
|
25 |
+
from .parser import Parser
|
26 |
+
|
27 |
+
class _TranslationsBasic(te.Protocol):
|
28 |
+
def gettext(self, message: str) -> str: ...
|
29 |
+
|
30 |
+
def ngettext(self, singular: str, plural: str, n: int) -> str:
|
31 |
+
pass
|
32 |
+
|
33 |
+
class _TranslationsContext(_TranslationsBasic):
|
34 |
+
def pgettext(self, context: str, message: str) -> str: ...
|
35 |
+
|
36 |
+
def npgettext(
|
37 |
+
self, context: str, singular: str, plural: str, n: int
|
38 |
+
) -> str: ...
|
39 |
+
|
40 |
+
_SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]
|
41 |
+
|
42 |
+
|
43 |
+
# I18N functions available in Jinja templates. If the I18N library
|
44 |
+
# provides ugettext, it will be assigned to gettext.
|
45 |
+
GETTEXT_FUNCTIONS: t.Tuple[str, ...] = (
|
46 |
+
"_",
|
47 |
+
"gettext",
|
48 |
+
"ngettext",
|
49 |
+
"pgettext",
|
50 |
+
"npgettext",
|
51 |
+
)
|
52 |
+
_ws_re = re.compile(r"\s*\n\s*")
|
53 |
+
|
54 |
+
|
55 |
+
class Extension:
|
56 |
+
"""Extensions can be used to add extra functionality to the Jinja template
|
57 |
+
system at the parser level. Custom extensions are bound to an environment
|
58 |
+
but may not store environment specific data on `self`. The reason for
|
59 |
+
this is that an extension can be bound to another environment (for
|
60 |
+
overlays) by creating a copy and reassigning the `environment` attribute.
|
61 |
+
|
62 |
+
As extensions are created by the environment they cannot accept any
|
63 |
+
arguments for configuration. One may want to work around that by using
|
64 |
+
a factory function, but that is not possible as extensions are identified
|
65 |
+
by their import name. The correct way to configure the extension is
|
66 |
+
storing the configuration values on the environment. Because this way the
|
67 |
+
environment ends up acting as central configuration storage the
|
68 |
+
attributes may clash which is why extensions have to ensure that the names
|
69 |
+
they choose for configuration are not too generic. ``prefix`` for example
|
70 |
+
is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
|
71 |
+
name as includes the name of the extension (fragment cache).
|
72 |
+
"""
|
73 |
+
|
74 |
+
identifier: t.ClassVar[str]
|
75 |
+
|
76 |
+
def __init_subclass__(cls) -> None:
|
77 |
+
cls.identifier = f"{cls.__module__}.{cls.__name__}"
|
78 |
+
|
79 |
+
#: if this extension parses this is the list of tags it's listening to.
|
80 |
+
tags: t.Set[str] = set()
|
81 |
+
|
82 |
+
#: the priority of that extension. This is especially useful for
|
83 |
+
#: extensions that preprocess values. A lower value means higher
|
84 |
+
#: priority.
|
85 |
+
#:
|
86 |
+
#: .. versionadded:: 2.4
|
87 |
+
priority = 100
|
88 |
+
|
89 |
+
def __init__(self, environment: Environment) -> None:
|
90 |
+
self.environment = environment
|
91 |
+
|
92 |
+
def bind(self, environment: Environment) -> "Extension":
|
93 |
+
"""Create a copy of this extension bound to another environment."""
|
94 |
+
rv = object.__new__(self.__class__)
|
95 |
+
rv.__dict__.update(self.__dict__)
|
96 |
+
rv.environment = environment
|
97 |
+
return rv
|
98 |
+
|
99 |
+
def preprocess(
|
100 |
+
self, source: str, name: t.Optional[str], filename: t.Optional[str] = None
|
101 |
+
) -> str:
|
102 |
+
"""This method is called before the actual lexing and can be used to
|
103 |
+
preprocess the source. The `filename` is optional. The return value
|
104 |
+
must be the preprocessed source.
|
105 |
+
"""
|
106 |
+
return source
|
107 |
+
|
108 |
+
def filter_stream(
|
109 |
+
self, stream: "TokenStream"
|
110 |
+
) -> t.Union["TokenStream", t.Iterable["Token"]]:
|
111 |
+
"""It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
|
112 |
+
to filter tokens returned. This method has to return an iterable of
|
113 |
+
:class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a
|
114 |
+
:class:`~jinja2.lexer.TokenStream`.
|
115 |
+
"""
|
116 |
+
return stream
|
117 |
+
|
118 |
+
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
|
119 |
+
"""If any of the :attr:`tags` matched this method is called with the
|
120 |
+
parser as first argument. The token the parser stream is pointing at
|
121 |
+
is the name token that matched. This method has to return one or a
|
122 |
+
list of multiple nodes.
|
123 |
+
"""
|
124 |
+
raise NotImplementedError()
|
125 |
+
|
126 |
+
def attr(
|
127 |
+
self, name: str, lineno: t.Optional[int] = None
|
128 |
+
) -> nodes.ExtensionAttribute:
|
129 |
+
"""Return an attribute node for the current extension. This is useful
|
130 |
+
to pass constants on extensions to generated template code.
|
131 |
+
|
132 |
+
::
|
133 |
+
|
134 |
+
self.attr('_my_attribute', lineno=lineno)
|
135 |
+
"""
|
136 |
+
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
|
137 |
+
|
138 |
+
def call_method(
|
139 |
+
self,
|
140 |
+
name: str,
|
141 |
+
args: t.Optional[t.List[nodes.Expr]] = None,
|
142 |
+
kwargs: t.Optional[t.List[nodes.Keyword]] = None,
|
143 |
+
dyn_args: t.Optional[nodes.Expr] = None,
|
144 |
+
dyn_kwargs: t.Optional[nodes.Expr] = None,
|
145 |
+
lineno: t.Optional[int] = None,
|
146 |
+
) -> nodes.Call:
|
147 |
+
"""Call a method of the extension. This is a shortcut for
|
148 |
+
:meth:`attr` + :class:`jinja2.nodes.Call`.
|
149 |
+
"""
|
150 |
+
if args is None:
|
151 |
+
args = []
|
152 |
+
if kwargs is None:
|
153 |
+
kwargs = []
|
154 |
+
return nodes.Call(
|
155 |
+
self.attr(name, lineno=lineno),
|
156 |
+
args,
|
157 |
+
kwargs,
|
158 |
+
dyn_args,
|
159 |
+
dyn_kwargs,
|
160 |
+
lineno=lineno,
|
161 |
+
)
|
162 |
+
|
163 |
+
|
164 |
+
@pass_context
|
165 |
+
def _gettext_alias(
|
166 |
+
__context: Context, *args: t.Any, **kwargs: t.Any
|
167 |
+
) -> t.Union[t.Any, Undefined]:
|
168 |
+
return __context.call(__context.resolve("gettext"), *args, **kwargs)
|
169 |
+
|
170 |
+
|
171 |
+
def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:
|
172 |
+
@pass_context
|
173 |
+
def gettext(__context: Context, __string: str, **variables: t.Any) -> str:
|
174 |
+
rv = __context.call(func, __string)
|
175 |
+
if __context.eval_ctx.autoescape:
|
176 |
+
rv = Markup(rv)
|
177 |
+
# Always treat as a format string, even if there are no
|
178 |
+
# variables. This makes translation strings more consistent
|
179 |
+
# and predictable. This requires escaping
|
180 |
+
return rv % variables # type: ignore
|
181 |
+
|
182 |
+
return gettext
|
183 |
+
|
184 |
+
|
185 |
+
def _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:
|
186 |
+
@pass_context
|
187 |
+
def ngettext(
|
188 |
+
__context: Context,
|
189 |
+
__singular: str,
|
190 |
+
__plural: str,
|
191 |
+
__num: int,
|
192 |
+
**variables: t.Any,
|
193 |
+
) -> str:
|
194 |
+
variables.setdefault("num", __num)
|
195 |
+
rv = __context.call(func, __singular, __plural, __num)
|
196 |
+
if __context.eval_ctx.autoescape:
|
197 |
+
rv = Markup(rv)
|
198 |
+
# Always treat as a format string, see gettext comment above.
|
199 |
+
return rv % variables # type: ignore
|
200 |
+
|
201 |
+
return ngettext
|
202 |
+
|
203 |
+
|
204 |
+
def _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:
|
205 |
+
@pass_context
|
206 |
+
def pgettext(
|
207 |
+
__context: Context, __string_ctx: str, __string: str, **variables: t.Any
|
208 |
+
) -> str:
|
209 |
+
variables.setdefault("context", __string_ctx)
|
210 |
+
rv = __context.call(func, __string_ctx, __string)
|
211 |
+
|
212 |
+
if __context.eval_ctx.autoescape:
|
213 |
+
rv = Markup(rv)
|
214 |
+
|
215 |
+
# Always treat as a format string, see gettext comment above.
|
216 |
+
return rv % variables # type: ignore
|
217 |
+
|
218 |
+
return pgettext
|
219 |
+
|
220 |
+
|
221 |
+
def _make_new_npgettext(
|
222 |
+
func: t.Callable[[str, str, str, int], str],
|
223 |
+
) -> t.Callable[..., str]:
|
224 |
+
@pass_context
|
225 |
+
def npgettext(
|
226 |
+
__context: Context,
|
227 |
+
__string_ctx: str,
|
228 |
+
__singular: str,
|
229 |
+
__plural: str,
|
230 |
+
__num: int,
|
231 |
+
**variables: t.Any,
|
232 |
+
) -> str:
|
233 |
+
variables.setdefault("context", __string_ctx)
|
234 |
+
variables.setdefault("num", __num)
|
235 |
+
rv = __context.call(func, __string_ctx, __singular, __plural, __num)
|
236 |
+
|
237 |
+
if __context.eval_ctx.autoescape:
|
238 |
+
rv = Markup(rv)
|
239 |
+
|
240 |
+
# Always treat as a format string, see gettext comment above.
|
241 |
+
return rv % variables # type: ignore
|
242 |
+
|
243 |
+
return npgettext
|
244 |
+
|
245 |
+
|
246 |
+
class InternationalizationExtension(Extension):
|
247 |
+
"""This extension adds gettext support to Jinja."""
|
248 |
+
|
249 |
+
tags = {"trans"}
|
250 |
+
|
251 |
+
# TODO: the i18n extension is currently reevaluating values in a few
|
252 |
+
# situations. Take this example:
|
253 |
+
# {% trans count=something() %}{{ count }} foo{% pluralize
|
254 |
+
# %}{{ count }} fooss{% endtrans %}
|
255 |
+
# something is called twice here. One time for the gettext value and
|
256 |
+
# the other time for the n-parameter of the ngettext function.
|
257 |
+
|
258 |
+
def __init__(self, environment: Environment) -> None:
|
259 |
+
super().__init__(environment)
|
260 |
+
environment.globals["_"] = _gettext_alias
|
261 |
+
environment.extend(
|
262 |
+
install_gettext_translations=self._install,
|
263 |
+
install_null_translations=self._install_null,
|
264 |
+
install_gettext_callables=self._install_callables,
|
265 |
+
uninstall_gettext_translations=self._uninstall,
|
266 |
+
extract_translations=self._extract,
|
267 |
+
newstyle_gettext=False,
|
268 |
+
)
|
269 |
+
|
270 |
+
def _install(
|
271 |
+
self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None
|
272 |
+
) -> None:
|
273 |
+
# ugettext and ungettext are preferred in case the I18N library
|
274 |
+
# is providing compatibility with older Python versions.
|
275 |
+
gettext = getattr(translations, "ugettext", None)
|
276 |
+
if gettext is None:
|
277 |
+
gettext = translations.gettext
|
278 |
+
ngettext = getattr(translations, "ungettext", None)
|
279 |
+
if ngettext is None:
|
280 |
+
ngettext = translations.ngettext
|
281 |
+
|
282 |
+
pgettext = getattr(translations, "pgettext", None)
|
283 |
+
npgettext = getattr(translations, "npgettext", None)
|
284 |
+
self._install_callables(
|
285 |
+
gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext
|
286 |
+
)
|
287 |
+
|
288 |
+
def _install_null(self, newstyle: t.Optional[bool] = None) -> None:
|
289 |
+
import gettext
|
290 |
+
|
291 |
+
translations = gettext.NullTranslations()
|
292 |
+
|
293 |
+
if hasattr(translations, "pgettext"):
|
294 |
+
# Python < 3.8
|
295 |
+
pgettext = translations.pgettext
|
296 |
+
else:
|
297 |
+
|
298 |
+
def pgettext(c: str, s: str) -> str: # type: ignore[misc]
|
299 |
+
return s
|
300 |
+
|
301 |
+
if hasattr(translations, "npgettext"):
|
302 |
+
npgettext = translations.npgettext
|
303 |
+
else:
|
304 |
+
|
305 |
+
def npgettext(c: str, s: str, p: str, n: int) -> str: # type: ignore[misc]
|
306 |
+
return s if n == 1 else p
|
307 |
+
|
308 |
+
self._install_callables(
|
309 |
+
gettext=translations.gettext,
|
310 |
+
ngettext=translations.ngettext,
|
311 |
+
newstyle=newstyle,
|
312 |
+
pgettext=pgettext,
|
313 |
+
npgettext=npgettext,
|
314 |
+
)
|
315 |
+
|
316 |
+
def _install_callables(
|
317 |
+
self,
|
318 |
+
gettext: t.Callable[[str], str],
|
319 |
+
ngettext: t.Callable[[str, str, int], str],
|
320 |
+
newstyle: t.Optional[bool] = None,
|
321 |
+
pgettext: t.Optional[t.Callable[[str, str], str]] = None,
|
322 |
+
npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,
|
323 |
+
) -> None:
|
324 |
+
if newstyle is not None:
|
325 |
+
self.environment.newstyle_gettext = newstyle # type: ignore
|
326 |
+
if self.environment.newstyle_gettext: # type: ignore
|
327 |
+
gettext = _make_new_gettext(gettext)
|
328 |
+
ngettext = _make_new_ngettext(ngettext)
|
329 |
+
|
330 |
+
if pgettext is not None:
|
331 |
+
pgettext = _make_new_pgettext(pgettext)
|
332 |
+
|
333 |
+
if npgettext is not None:
|
334 |
+
npgettext = _make_new_npgettext(npgettext)
|
335 |
+
|
336 |
+
self.environment.globals.update(
|
337 |
+
gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext
|
338 |
+
)
|
339 |
+
|
340 |
+
def _uninstall(self, translations: "_SupportedTranslations") -> None:
|
341 |
+
for key in ("gettext", "ngettext", "pgettext", "npgettext"):
|
342 |
+
self.environment.globals.pop(key, None)
|
343 |
+
|
344 |
+
def _extract(
|
345 |
+
self,
|
346 |
+
source: t.Union[str, nodes.Template],
|
347 |
+
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
|
348 |
+
) -> t.Iterator[
|
349 |
+
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
|
350 |
+
]:
|
351 |
+
if isinstance(source, str):
|
352 |
+
source = self.environment.parse(source)
|
353 |
+
return extract_from_ast(source, gettext_functions)
|
354 |
+
|
355 |
+
def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:
|
356 |
+
"""Parse a translatable tag."""
|
357 |
+
lineno = next(parser.stream).lineno
|
358 |
+
|
359 |
+
context = None
|
360 |
+
context_token = parser.stream.next_if("string")
|
361 |
+
|
362 |
+
if context_token is not None:
|
363 |
+
context = context_token.value
|
364 |
+
|
365 |
+
# find all the variables referenced. Additionally a variable can be
|
366 |
+
# defined in the body of the trans block too, but this is checked at
|
367 |
+
# a later state.
|
368 |
+
plural_expr: t.Optional[nodes.Expr] = None
|
369 |
+
plural_expr_assignment: t.Optional[nodes.Assign] = None
|
370 |
+
num_called_num = False
|
371 |
+
variables: t.Dict[str, nodes.Expr] = {}
|
372 |
+
trimmed = None
|
373 |
+
while parser.stream.current.type != "block_end":
|
374 |
+
if variables:
|
375 |
+
parser.stream.expect("comma")
|
376 |
+
|
377 |
+
# skip colon for python compatibility
|
378 |
+
if parser.stream.skip_if("colon"):
|
379 |
+
break
|
380 |
+
|
381 |
+
token = parser.stream.expect("name")
|
382 |
+
if token.value in variables:
|
383 |
+
parser.fail(
|
384 |
+
f"translatable variable {token.value!r} defined twice.",
|
385 |
+
token.lineno,
|
386 |
+
exc=TemplateAssertionError,
|
387 |
+
)
|
388 |
+
|
389 |
+
# expressions
|
390 |
+
if parser.stream.current.type == "assign":
|
391 |
+
next(parser.stream)
|
392 |
+
variables[token.value] = var = parser.parse_expression()
|
393 |
+
elif trimmed is None and token.value in ("trimmed", "notrimmed"):
|
394 |
+
trimmed = token.value == "trimmed"
|
395 |
+
continue
|
396 |
+
else:
|
397 |
+
variables[token.value] = var = nodes.Name(token.value, "load")
|
398 |
+
|
399 |
+
if plural_expr is None:
|
400 |
+
if isinstance(var, nodes.Call):
|
401 |
+
plural_expr = nodes.Name("_trans", "load")
|
402 |
+
variables[token.value] = plural_expr
|
403 |
+
plural_expr_assignment = nodes.Assign(
|
404 |
+
nodes.Name("_trans", "store"), var
|
405 |
+
)
|
406 |
+
else:
|
407 |
+
plural_expr = var
|
408 |
+
num_called_num = token.value == "num"
|
409 |
+
|
410 |
+
parser.stream.expect("block_end")
|
411 |
+
|
412 |
+
plural = None
|
413 |
+
have_plural = False
|
414 |
+
referenced = set()
|
415 |
+
|
416 |
+
# now parse until endtrans or pluralize
|
417 |
+
singular_names, singular = self._parse_block(parser, True)
|
418 |
+
if singular_names:
|
419 |
+
referenced.update(singular_names)
|
420 |
+
if plural_expr is None:
|
421 |
+
plural_expr = nodes.Name(singular_names[0], "load")
|
422 |
+
num_called_num = singular_names[0] == "num"
|
423 |
+
|
424 |
+
# if we have a pluralize block, we parse that too
|
425 |
+
if parser.stream.current.test("name:pluralize"):
|
426 |
+
have_plural = True
|
427 |
+
next(parser.stream)
|
428 |
+
if parser.stream.current.type != "block_end":
|
429 |
+
token = parser.stream.expect("name")
|
430 |
+
if token.value not in variables:
|
431 |
+
parser.fail(
|
432 |
+
f"unknown variable {token.value!r} for pluralization",
|
433 |
+
token.lineno,
|
434 |
+
exc=TemplateAssertionError,
|
435 |
+
)
|
436 |
+
plural_expr = variables[token.value]
|
437 |
+
num_called_num = token.value == "num"
|
438 |
+
parser.stream.expect("block_end")
|
439 |
+
plural_names, plural = self._parse_block(parser, False)
|
440 |
+
next(parser.stream)
|
441 |
+
referenced.update(plural_names)
|
442 |
+
else:
|
443 |
+
next(parser.stream)
|
444 |
+
|
445 |
+
# register free names as simple name expressions
|
446 |
+
for name in referenced:
|
447 |
+
if name not in variables:
|
448 |
+
variables[name] = nodes.Name(name, "load")
|
449 |
+
|
450 |
+
if not have_plural:
|
451 |
+
plural_expr = None
|
452 |
+
elif plural_expr is None:
|
453 |
+
parser.fail("pluralize without variables", lineno)
|
454 |
+
|
455 |
+
if trimmed is None:
|
456 |
+
trimmed = self.environment.policies["ext.i18n.trimmed"]
|
457 |
+
if trimmed:
|
458 |
+
singular = self._trim_whitespace(singular)
|
459 |
+
if plural:
|
460 |
+
plural = self._trim_whitespace(plural)
|
461 |
+
|
462 |
+
node = self._make_node(
|
463 |
+
singular,
|
464 |
+
plural,
|
465 |
+
context,
|
466 |
+
variables,
|
467 |
+
plural_expr,
|
468 |
+
bool(referenced),
|
469 |
+
num_called_num and have_plural,
|
470 |
+
)
|
471 |
+
node.set_lineno(lineno)
|
472 |
+
if plural_expr_assignment is not None:
|
473 |
+
return [plural_expr_assignment, node]
|
474 |
+
else:
|
475 |
+
return node
|
476 |
+
|
477 |
+
def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:
|
478 |
+
return _ws_re.sub(" ", string.strip())
|
479 |
+
|
480 |
+
def _parse_block(
|
481 |
+
self, parser: "Parser", allow_pluralize: bool
|
482 |
+
) -> t.Tuple[t.List[str], str]:
|
483 |
+
"""Parse until the next block tag with a given name."""
|
484 |
+
referenced = []
|
485 |
+
buf = []
|
486 |
+
|
487 |
+
while True:
|
488 |
+
if parser.stream.current.type == "data":
|
489 |
+
buf.append(parser.stream.current.value.replace("%", "%%"))
|
490 |
+
next(parser.stream)
|
491 |
+
elif parser.stream.current.type == "variable_begin":
|
492 |
+
next(parser.stream)
|
493 |
+
name = parser.stream.expect("name").value
|
494 |
+
referenced.append(name)
|
495 |
+
buf.append(f"%({name})s")
|
496 |
+
parser.stream.expect("variable_end")
|
497 |
+
elif parser.stream.current.type == "block_begin":
|
498 |
+
next(parser.stream)
|
499 |
+
block_name = (
|
500 |
+
parser.stream.current.value
|
501 |
+
if parser.stream.current.type == "name"
|
502 |
+
else None
|
503 |
+
)
|
504 |
+
if block_name == "endtrans":
|
505 |
+
break
|
506 |
+
elif block_name == "pluralize":
|
507 |
+
if allow_pluralize:
|
508 |
+
break
|
509 |
+
parser.fail(
|
510 |
+
"a translatable section can have only one pluralize section"
|
511 |
+
)
|
512 |
+
elif block_name == "trans":
|
513 |
+
parser.fail(
|
514 |
+
"trans blocks can't be nested; did you mean `endtrans`?"
|
515 |
+
)
|
516 |
+
parser.fail(
|
517 |
+
f"control structures in translatable sections are not allowed; "
|
518 |
+
f"saw `{block_name}`"
|
519 |
+
)
|
520 |
+
elif parser.stream.eos:
|
521 |
+
parser.fail("unclosed translation block")
|
522 |
+
else:
|
523 |
+
raise RuntimeError("internal parser error")
|
524 |
+
|
525 |
+
return referenced, concat(buf)
|
526 |
+
|
527 |
+
def _make_node(
|
528 |
+
self,
|
529 |
+
singular: str,
|
530 |
+
plural: t.Optional[str],
|
531 |
+
context: t.Optional[str],
|
532 |
+
variables: t.Dict[str, nodes.Expr],
|
533 |
+
plural_expr: t.Optional[nodes.Expr],
|
534 |
+
vars_referenced: bool,
|
535 |
+
num_called_num: bool,
|
536 |
+
) -> nodes.Output:
|
537 |
+
"""Generates a useful node from the data provided."""
|
538 |
+
newstyle = self.environment.newstyle_gettext # type: ignore
|
539 |
+
node: nodes.Expr
|
540 |
+
|
541 |
+
# no variables referenced? no need to escape for old style
|
542 |
+
# gettext invocations only if there are vars.
|
543 |
+
if not vars_referenced and not newstyle:
|
544 |
+
singular = singular.replace("%%", "%")
|
545 |
+
if plural:
|
546 |
+
plural = plural.replace("%%", "%")
|
547 |
+
|
548 |
+
func_name = "gettext"
|
549 |
+
func_args: t.List[nodes.Expr] = [nodes.Const(singular)]
|
550 |
+
|
551 |
+
if context is not None:
|
552 |
+
func_args.insert(0, nodes.Const(context))
|
553 |
+
func_name = f"p{func_name}"
|
554 |
+
|
555 |
+
if plural_expr is not None:
|
556 |
+
func_name = f"n{func_name}"
|
557 |
+
func_args.extend((nodes.Const(plural), plural_expr))
|
558 |
+
|
559 |
+
node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)
|
560 |
+
|
561 |
+
# in case newstyle gettext is used, the method is powerful
|
562 |
+
# enough to handle the variable expansion and autoescape
|
563 |
+
# handling itself
|
564 |
+
if newstyle:
|
565 |
+
for key, value in variables.items():
|
566 |
+
# the function adds that later anyways in case num was
|
567 |
+
# called num, so just skip it.
|
568 |
+
if num_called_num and key == "num":
|
569 |
+
continue
|
570 |
+
node.kwargs.append(nodes.Keyword(key, value))
|
571 |
+
|
572 |
+
# otherwise do that here
|
573 |
+
else:
|
574 |
+
# mark the return value as safe if we are in an
|
575 |
+
# environment with autoescaping turned on
|
576 |
+
node = nodes.MarkSafeIfAutoescape(node)
|
577 |
+
if variables:
|
578 |
+
node = nodes.Mod(
|
579 |
+
node,
|
580 |
+
nodes.Dict(
|
581 |
+
[
|
582 |
+
nodes.Pair(nodes.Const(key), value)
|
583 |
+
for key, value in variables.items()
|
584 |
+
]
|
585 |
+
),
|
586 |
+
)
|
587 |
+
return nodes.Output([node])
|
588 |
+
|
589 |
+
|
590 |
+
class ExprStmtExtension(Extension):
|
591 |
+
"""Adds a `do` tag to Jinja that works like the print statement just
|
592 |
+
that it doesn't print the return value.
|
593 |
+
"""
|
594 |
+
|
595 |
+
tags = {"do"}
|
596 |
+
|
597 |
+
def parse(self, parser: "Parser") -> nodes.ExprStmt:
|
598 |
+
node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
|
599 |
+
node.node = parser.parse_tuple()
|
600 |
+
return node
|
601 |
+
|
602 |
+
|
603 |
+
class LoopControlExtension(Extension):
|
604 |
+
"""Adds break and continue to the template engine."""
|
605 |
+
|
606 |
+
tags = {"break", "continue"}
|
607 |
+
|
608 |
+
def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:
|
609 |
+
token = next(parser.stream)
|
610 |
+
if token.value == "break":
|
611 |
+
return nodes.Break(lineno=token.lineno)
|
612 |
+
return nodes.Continue(lineno=token.lineno)
|
613 |
+
|
614 |
+
|
615 |
+
class DebugExtension(Extension):
|
616 |
+
"""A ``{% debug %}`` tag that dumps the available variables,
|
617 |
+
filters, and tests.
|
618 |
+
|
619 |
+
.. code-block:: html+jinja
|
620 |
+
|
621 |
+
<pre>{% debug %}</pre>
|
622 |
+
|
623 |
+
.. code-block:: text
|
624 |
+
|
625 |
+
{'context': {'cycler': <class 'jinja2.utils.Cycler'>,
|
626 |
+
...,
|
627 |
+
'namespace': <class 'jinja2.utils.Namespace'>},
|
628 |
+
'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',
|
629 |
+
..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],
|
630 |
+
'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',
|
631 |
+
..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}
|
632 |
+
|
633 |
+
.. versionadded:: 2.11.0
|
634 |
+
"""
|
635 |
+
|
636 |
+
tags = {"debug"}
|
637 |
+
|
638 |
+
def parse(self, parser: "Parser") -> nodes.Output:
|
639 |
+
lineno = parser.stream.expect("name:debug").lineno
|
640 |
+
context = nodes.ContextReference()
|
641 |
+
result = self.call_method("_render", [context], lineno=lineno)
|
642 |
+
return nodes.Output([result], lineno=lineno)
|
643 |
+
|
644 |
+
def _render(self, context: Context) -> str:
|
645 |
+
result = {
|
646 |
+
"context": context.get_all(),
|
647 |
+
"filters": sorted(self.environment.filters.keys()),
|
648 |
+
"tests": sorted(self.environment.tests.keys()),
|
649 |
+
}
|
650 |
+
|
651 |
+
# Set the depth since the intent is to show the top few names.
|
652 |
+
return pprint.pformat(result, depth=3, compact=True)
|
653 |
+
|
654 |
+
|
655 |
+
def extract_from_ast(
|
656 |
+
ast: nodes.Template,
|
657 |
+
gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,
|
658 |
+
babel_style: bool = True,
|
659 |
+
) -> t.Iterator[
|
660 |
+
t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]
|
661 |
+
]:
|
662 |
+
"""Extract localizable strings from the given template node. Per
|
663 |
+
default this function returns matches in babel style that means non string
|
664 |
+
parameters as well as keyword arguments are returned as `None`. This
|
665 |
+
allows Babel to figure out what you really meant if you are using
|
666 |
+
gettext functions that allow keyword arguments for placeholder expansion.
|
667 |
+
If you don't want that behavior set the `babel_style` parameter to `False`
|
668 |
+
which causes only strings to be returned and parameters are always stored
|
669 |
+
in tuples. As a consequence invalid gettext calls (calls without a single
|
670 |
+
string parameter or string parameters after non-string parameters) are
|
671 |
+
skipped.
|
672 |
+
|
673 |
+
This example explains the behavior:
|
674 |
+
|
675 |
+
>>> from jinja2 import Environment
|
676 |
+
>>> env = Environment()
|
677 |
+
>>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
|
678 |
+
>>> list(extract_from_ast(node))
|
679 |
+
[(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
|
680 |
+
>>> list(extract_from_ast(node, babel_style=False))
|
681 |
+
[(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
|
682 |
+
|
683 |
+
For every string found this function yields a ``(lineno, function,
|
684 |
+
message)`` tuple, where:
|
685 |
+
|
686 |
+
* ``lineno`` is the number of the line on which the string was found,
|
687 |
+
* ``function`` is the name of the ``gettext`` function used (if the
|
688 |
+
string was extracted from embedded Python code), and
|
689 |
+
* ``message`` is the string, or a tuple of strings for functions
|
690 |
+
with multiple string arguments.
|
691 |
+
|
692 |
+
This extraction function operates on the AST and is because of that unable
|
693 |
+
to extract any comments. For comment support you have to use the babel
|
694 |
+
extraction interface or extract comments yourself.
|
695 |
+
"""
|
696 |
+
out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]
|
697 |
+
|
698 |
+
for node in ast.find_all(nodes.Call):
|
699 |
+
if (
|
700 |
+
not isinstance(node.node, nodes.Name)
|
701 |
+
or node.node.name not in gettext_functions
|
702 |
+
):
|
703 |
+
continue
|
704 |
+
|
705 |
+
strings: t.List[t.Optional[str]] = []
|
706 |
+
|
707 |
+
for arg in node.args:
|
708 |
+
if isinstance(arg, nodes.Const) and isinstance(arg.value, str):
|
709 |
+
strings.append(arg.value)
|
710 |
+
else:
|
711 |
+
strings.append(None)
|
712 |
+
|
713 |
+
for _ in node.kwargs:
|
714 |
+
strings.append(None)
|
715 |
+
if node.dyn_args is not None:
|
716 |
+
strings.append(None)
|
717 |
+
if node.dyn_kwargs is not None:
|
718 |
+
strings.append(None)
|
719 |
+
|
720 |
+
if not babel_style:
|
721 |
+
out = tuple(x for x in strings if x is not None)
|
722 |
+
|
723 |
+
if not out:
|
724 |
+
continue
|
725 |
+
else:
|
726 |
+
if len(strings) == 1:
|
727 |
+
out = strings[0]
|
728 |
+
else:
|
729 |
+
out = tuple(strings)
|
730 |
+
|
731 |
+
yield node.lineno, node.node.name, out
|
732 |
+
|
733 |
+
|
734 |
+
class _CommentFinder:
|
735 |
+
"""Helper class to find comments in a token stream. Can only
|
736 |
+
find comments for gettext calls forwards. Once the comment
|
737 |
+
from line 4 is found, a comment for line 1 will not return a
|
738 |
+
usable value.
|
739 |
+
"""
|
740 |
+
|
741 |
+
def __init__(
|
742 |
+
self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]
|
743 |
+
) -> None:
|
744 |
+
self.tokens = tokens
|
745 |
+
self.comment_tags = comment_tags
|
746 |
+
self.offset = 0
|
747 |
+
self.last_lineno = 0
|
748 |
+
|
749 |
+
def find_backwards(self, offset: int) -> t.List[str]:
|
750 |
+
try:
|
751 |
+
for _, token_type, token_value in reversed(
|
752 |
+
self.tokens[self.offset : offset]
|
753 |
+
):
|
754 |
+
if token_type in ("comment", "linecomment"):
|
755 |
+
try:
|
756 |
+
prefix, comment = token_value.split(None, 1)
|
757 |
+
except ValueError:
|
758 |
+
continue
|
759 |
+
if prefix in self.comment_tags:
|
760 |
+
return [comment.rstrip()]
|
761 |
+
return []
|
762 |
+
finally:
|
763 |
+
self.offset = offset
|
764 |
+
|
765 |
+
def find_comments(self, lineno: int) -> t.List[str]:
|
766 |
+
if not self.comment_tags or self.last_lineno > lineno:
|
767 |
+
return []
|
768 |
+
for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):
|
769 |
+
if token_lineno > lineno:
|
770 |
+
return self.find_backwards(self.offset + idx)
|
771 |
+
return self.find_backwards(len(self.tokens))
|
772 |
+
|
773 |
+
|
774 |
+
def babel_extract(
|
775 |
+
fileobj: t.BinaryIO,
|
776 |
+
keywords: t.Sequence[str],
|
777 |
+
comment_tags: t.Sequence[str],
|
778 |
+
options: t.Dict[str, t.Any],
|
779 |
+
) -> t.Iterator[
|
780 |
+
t.Tuple[
|
781 |
+
int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]
|
782 |
+
]
|
783 |
+
]:
|
784 |
+
"""Babel extraction method for Jinja templates.
|
785 |
+
|
786 |
+
.. versionchanged:: 2.3
|
787 |
+
Basic support for translation comments was added. If `comment_tags`
|
788 |
+
is now set to a list of keywords for extraction, the extractor will
|
789 |
+
try to find the best preceding comment that begins with one of the
|
790 |
+
keywords. For best results, make sure to not have more than one
|
791 |
+
gettext call in one line of code and the matching comment in the
|
792 |
+
same line or the line before.
|
793 |
+
|
794 |
+
.. versionchanged:: 2.5.1
|
795 |
+
The `newstyle_gettext` flag can be set to `True` to enable newstyle
|
796 |
+
gettext calls.
|
797 |
+
|
798 |
+
.. versionchanged:: 2.7
|
799 |
+
A `silent` option can now be provided. If set to `False` template
|
800 |
+
syntax errors are propagated instead of being ignored.
|
801 |
+
|
802 |
+
:param fileobj: the file-like object the messages should be extracted from
|
803 |
+
:param keywords: a list of keywords (i.e. function names) that should be
|
804 |
+
recognized as translation functions
|
805 |
+
:param comment_tags: a list of translator tags to search for and include
|
806 |
+
in the results.
|
807 |
+
:param options: a dictionary of additional options (optional)
|
808 |
+
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
|
809 |
+
(comments will be empty currently)
|
810 |
+
"""
|
811 |
+
extensions: t.Dict[t.Type[Extension], None] = {}
|
812 |
+
|
813 |
+
for extension_name in options.get("extensions", "").split(","):
|
814 |
+
extension_name = extension_name.strip()
|
815 |
+
|
816 |
+
if not extension_name:
|
817 |
+
continue
|
818 |
+
|
819 |
+
extensions[import_string(extension_name)] = None
|
820 |
+
|
821 |
+
if InternationalizationExtension not in extensions:
|
822 |
+
extensions[InternationalizationExtension] = None
|
823 |
+
|
824 |
+
def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:
|
825 |
+
return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}
|
826 |
+
|
827 |
+
silent = getbool(options, "silent", True)
|
828 |
+
environment = Environment(
|
829 |
+
options.get("block_start_string", defaults.BLOCK_START_STRING),
|
830 |
+
options.get("block_end_string", defaults.BLOCK_END_STRING),
|
831 |
+
options.get("variable_start_string", defaults.VARIABLE_START_STRING),
|
832 |
+
options.get("variable_end_string", defaults.VARIABLE_END_STRING),
|
833 |
+
options.get("comment_start_string", defaults.COMMENT_START_STRING),
|
834 |
+
options.get("comment_end_string", defaults.COMMENT_END_STRING),
|
835 |
+
options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,
|
836 |
+
options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,
|
837 |
+
getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),
|
838 |
+
getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),
|
839 |
+
defaults.NEWLINE_SEQUENCE,
|
840 |
+
getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),
|
841 |
+
tuple(extensions),
|
842 |
+
cache_size=0,
|
843 |
+
auto_reload=False,
|
844 |
+
)
|
845 |
+
|
846 |
+
if getbool(options, "trimmed"):
|
847 |
+
environment.policies["ext.i18n.trimmed"] = True
|
848 |
+
if getbool(options, "newstyle_gettext"):
|
849 |
+
environment.newstyle_gettext = True # type: ignore
|
850 |
+
|
851 |
+
source = fileobj.read().decode(options.get("encoding", "utf-8"))
|
852 |
+
try:
|
853 |
+
node = environment.parse(source)
|
854 |
+
tokens = list(environment.lex(environment.preprocess(source)))
|
855 |
+
except TemplateSyntaxError:
|
856 |
+
if not silent:
|
857 |
+
raise
|
858 |
+
# skip templates with syntax errors
|
859 |
+
return
|
860 |
+
|
861 |
+
finder = _CommentFinder(tokens, comment_tags)
|
862 |
+
for lineno, func, message in extract_from_ast(node, keywords):
|
863 |
+
yield lineno, func, message, finder.find_comments(lineno)
|
864 |
+
|
865 |
+
|
866 |
+
#: nicer import names
|
867 |
+
i18n = InternationalizationExtension
|
868 |
+
do = ExprStmtExtension
|
869 |
+
loopcontrols = LoopControlExtension
|
870 |
+
debug = DebugExtension
|
llmeval-env/lib/python3.10/site-packages/jinja2/filters.py
ADDED
@@ -0,0 +1,1866 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Built-in template filters used with the ``|`` operator."""
|
2 |
+
|
3 |
+
import math
|
4 |
+
import random
|
5 |
+
import re
|
6 |
+
import typing
|
7 |
+
import typing as t
|
8 |
+
from collections import abc
|
9 |
+
from itertools import chain
|
10 |
+
from itertools import groupby
|
11 |
+
|
12 |
+
from markupsafe import escape
|
13 |
+
from markupsafe import Markup
|
14 |
+
from markupsafe import soft_str
|
15 |
+
|
16 |
+
from .async_utils import async_variant
|
17 |
+
from .async_utils import auto_aiter
|
18 |
+
from .async_utils import auto_await
|
19 |
+
from .async_utils import auto_to_list
|
20 |
+
from .exceptions import FilterArgumentError
|
21 |
+
from .runtime import Undefined
|
22 |
+
from .utils import htmlsafe_json_dumps
|
23 |
+
from .utils import pass_context
|
24 |
+
from .utils import pass_environment
|
25 |
+
from .utils import pass_eval_context
|
26 |
+
from .utils import pformat
|
27 |
+
from .utils import url_quote
|
28 |
+
from .utils import urlize
|
29 |
+
|
30 |
+
if t.TYPE_CHECKING:
|
31 |
+
import typing_extensions as te
|
32 |
+
|
33 |
+
from .environment import Environment
|
34 |
+
from .nodes import EvalContext
|
35 |
+
from .runtime import Context
|
36 |
+
from .sandbox import SandboxedEnvironment # noqa: F401
|
37 |
+
|
38 |
+
class HasHTML(te.Protocol):
|
39 |
+
def __html__(self) -> str:
|
40 |
+
pass
|
41 |
+
|
42 |
+
|
43 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
44 |
+
K = t.TypeVar("K")
|
45 |
+
V = t.TypeVar("V")
|
46 |
+
|
47 |
+
|
48 |
+
def ignore_case(value: V) -> V:
|
49 |
+
"""For use as a postprocessor for :func:`make_attrgetter`. Converts strings
|
50 |
+
to lowercase and returns other types as-is."""
|
51 |
+
if isinstance(value, str):
|
52 |
+
return t.cast(V, value.lower())
|
53 |
+
|
54 |
+
return value
|
55 |
+
|
56 |
+
|
57 |
+
def make_attrgetter(
|
58 |
+
environment: "Environment",
|
59 |
+
attribute: t.Optional[t.Union[str, int]],
|
60 |
+
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
|
61 |
+
default: t.Optional[t.Any] = None,
|
62 |
+
) -> t.Callable[[t.Any], t.Any]:
|
63 |
+
"""Returns a callable that looks up the given attribute from a
|
64 |
+
passed object with the rules of the environment. Dots are allowed
|
65 |
+
to access attributes of attributes. Integer parts in paths are
|
66 |
+
looked up as integers.
|
67 |
+
"""
|
68 |
+
parts = _prepare_attribute_parts(attribute)
|
69 |
+
|
70 |
+
def attrgetter(item: t.Any) -> t.Any:
|
71 |
+
for part in parts:
|
72 |
+
item = environment.getitem(item, part)
|
73 |
+
|
74 |
+
if default is not None and isinstance(item, Undefined):
|
75 |
+
item = default
|
76 |
+
|
77 |
+
if postprocess is not None:
|
78 |
+
item = postprocess(item)
|
79 |
+
|
80 |
+
return item
|
81 |
+
|
82 |
+
return attrgetter
|
83 |
+
|
84 |
+
|
85 |
+
def make_multi_attrgetter(
|
86 |
+
environment: "Environment",
|
87 |
+
attribute: t.Optional[t.Union[str, int]],
|
88 |
+
postprocess: t.Optional[t.Callable[[t.Any], t.Any]] = None,
|
89 |
+
) -> t.Callable[[t.Any], t.List[t.Any]]:
|
90 |
+
"""Returns a callable that looks up the given comma separated
|
91 |
+
attributes from a passed object with the rules of the environment.
|
92 |
+
Dots are allowed to access attributes of each attribute. Integer
|
93 |
+
parts in paths are looked up as integers.
|
94 |
+
|
95 |
+
The value returned by the returned callable is a list of extracted
|
96 |
+
attribute values.
|
97 |
+
|
98 |
+
Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.
|
99 |
+
"""
|
100 |
+
if isinstance(attribute, str):
|
101 |
+
split: t.Sequence[t.Union[str, int, None]] = attribute.split(",")
|
102 |
+
else:
|
103 |
+
split = [attribute]
|
104 |
+
|
105 |
+
parts = [_prepare_attribute_parts(item) for item in split]
|
106 |
+
|
107 |
+
def attrgetter(item: t.Any) -> t.List[t.Any]:
|
108 |
+
items = [None] * len(parts)
|
109 |
+
|
110 |
+
for i, attribute_part in enumerate(parts):
|
111 |
+
item_i = item
|
112 |
+
|
113 |
+
for part in attribute_part:
|
114 |
+
item_i = environment.getitem(item_i, part)
|
115 |
+
|
116 |
+
if postprocess is not None:
|
117 |
+
item_i = postprocess(item_i)
|
118 |
+
|
119 |
+
items[i] = item_i
|
120 |
+
|
121 |
+
return items
|
122 |
+
|
123 |
+
return attrgetter
|
124 |
+
|
125 |
+
|
126 |
+
def _prepare_attribute_parts(
|
127 |
+
attr: t.Optional[t.Union[str, int]],
|
128 |
+
) -> t.List[t.Union[str, int]]:
|
129 |
+
if attr is None:
|
130 |
+
return []
|
131 |
+
|
132 |
+
if isinstance(attr, str):
|
133 |
+
return [int(x) if x.isdigit() else x for x in attr.split(".")]
|
134 |
+
|
135 |
+
return [attr]
|
136 |
+
|
137 |
+
|
138 |
+
def do_forceescape(value: "t.Union[str, HasHTML]") -> Markup:
|
139 |
+
"""Enforce HTML escaping. This will probably double escape variables."""
|
140 |
+
if hasattr(value, "__html__"):
|
141 |
+
value = t.cast("HasHTML", value).__html__()
|
142 |
+
|
143 |
+
return escape(str(value))
|
144 |
+
|
145 |
+
|
146 |
+
def do_urlencode(
|
147 |
+
value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],
|
148 |
+
) -> str:
|
149 |
+
"""Quote data for use in a URL path or query using UTF-8.
|
150 |
+
|
151 |
+
Basic wrapper around :func:`urllib.parse.quote` when given a
|
152 |
+
string, or :func:`urllib.parse.urlencode` for a dict or iterable.
|
153 |
+
|
154 |
+
:param value: Data to quote. A string will be quoted directly. A
|
155 |
+
dict or iterable of ``(key, value)`` pairs will be joined as a
|
156 |
+
query string.
|
157 |
+
|
158 |
+
When given a string, "/" is not quoted. HTTP servers treat "/" and
|
159 |
+
"%2F" equivalently in paths. If you need quoted slashes, use the
|
160 |
+
``|replace("/", "%2F")`` filter.
|
161 |
+
|
162 |
+
.. versionadded:: 2.7
|
163 |
+
"""
|
164 |
+
if isinstance(value, str) or not isinstance(value, abc.Iterable):
|
165 |
+
return url_quote(value)
|
166 |
+
|
167 |
+
if isinstance(value, dict):
|
168 |
+
items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
|
169 |
+
else:
|
170 |
+
items = value # type: ignore
|
171 |
+
|
172 |
+
return "&".join(
|
173 |
+
f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
|
174 |
+
)
|
175 |
+
|
176 |
+
|
177 |
+
@pass_eval_context
|
178 |
+
def do_replace(
|
179 |
+
eval_ctx: "EvalContext", s: str, old: str, new: str, count: t.Optional[int] = None
|
180 |
+
) -> str:
|
181 |
+
"""Return a copy of the value with all occurrences of a substring
|
182 |
+
replaced with a new one. The first argument is the substring
|
183 |
+
that should be replaced, the second is the replacement string.
|
184 |
+
If the optional third argument ``count`` is given, only the first
|
185 |
+
``count`` occurrences are replaced:
|
186 |
+
|
187 |
+
.. sourcecode:: jinja
|
188 |
+
|
189 |
+
{{ "Hello World"|replace("Hello", "Goodbye") }}
|
190 |
+
-> Goodbye World
|
191 |
+
|
192 |
+
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
|
193 |
+
-> d'oh, d'oh, aaargh
|
194 |
+
"""
|
195 |
+
if count is None:
|
196 |
+
count = -1
|
197 |
+
|
198 |
+
if not eval_ctx.autoescape:
|
199 |
+
return str(s).replace(str(old), str(new), count)
|
200 |
+
|
201 |
+
if (
|
202 |
+
hasattr(old, "__html__")
|
203 |
+
or hasattr(new, "__html__")
|
204 |
+
and not hasattr(s, "__html__")
|
205 |
+
):
|
206 |
+
s = escape(s)
|
207 |
+
else:
|
208 |
+
s = soft_str(s)
|
209 |
+
|
210 |
+
return s.replace(soft_str(old), soft_str(new), count)
|
211 |
+
|
212 |
+
|
213 |
+
def do_upper(s: str) -> str:
|
214 |
+
"""Convert a value to uppercase."""
|
215 |
+
return soft_str(s).upper()
|
216 |
+
|
217 |
+
|
218 |
+
def do_lower(s: str) -> str:
|
219 |
+
"""Convert a value to lowercase."""
|
220 |
+
return soft_str(s).lower()
|
221 |
+
|
222 |
+
|
223 |
+
def do_items(value: t.Union[t.Mapping[K, V], Undefined]) -> t.Iterator[t.Tuple[K, V]]:
|
224 |
+
"""Return an iterator over the ``(key, value)`` items of a mapping.
|
225 |
+
|
226 |
+
``x|items`` is the same as ``x.items()``, except if ``x`` is
|
227 |
+
undefined an empty iterator is returned.
|
228 |
+
|
229 |
+
This filter is useful if you expect the template to be rendered with
|
230 |
+
an implementation of Jinja in another programming language that does
|
231 |
+
not have a ``.items()`` method on its mapping type.
|
232 |
+
|
233 |
+
.. code-block:: html+jinja
|
234 |
+
|
235 |
+
<dl>
|
236 |
+
{% for key, value in my_dict|items %}
|
237 |
+
<dt>{{ key }}
|
238 |
+
<dd>{{ value }}
|
239 |
+
{% endfor %}
|
240 |
+
</dl>
|
241 |
+
|
242 |
+
.. versionadded:: 3.1
|
243 |
+
"""
|
244 |
+
if isinstance(value, Undefined):
|
245 |
+
return
|
246 |
+
|
247 |
+
if not isinstance(value, abc.Mapping):
|
248 |
+
raise TypeError("Can only get item pairs from a mapping.")
|
249 |
+
|
250 |
+
yield from value.items()
|
251 |
+
|
252 |
+
|
253 |
+
# Check for characters that would move the parser state from key to value.
|
254 |
+
# https://html.spec.whatwg.org/#attribute-name-state
|
255 |
+
_attr_key_re = re.compile(r"[\s/>=]", flags=re.ASCII)
|
256 |
+
|
257 |
+
|
258 |
+
@pass_eval_context
|
259 |
+
def do_xmlattr(
|
260 |
+
eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True
|
261 |
+
) -> str:
|
262 |
+
"""Create an SGML/XML attribute string based on the items in a dict.
|
263 |
+
|
264 |
+
**Values** that are neither ``none`` nor ``undefined`` are automatically
|
265 |
+
escaped, safely allowing untrusted user input.
|
266 |
+
|
267 |
+
User input should not be used as **keys** to this filter. If any key
|
268 |
+
contains a space, ``/`` solidus, ``>`` greater-than sign, or ``=`` equals
|
269 |
+
sign, this fails with a ``ValueError``. Regardless of this, user input
|
270 |
+
should never be used as keys to this filter, or must be separately validated
|
271 |
+
first.
|
272 |
+
|
273 |
+
.. sourcecode:: html+jinja
|
274 |
+
|
275 |
+
<ul{{ {'class': 'my_list', 'missing': none,
|
276 |
+
'id': 'list-%d'|format(variable)}|xmlattr }}>
|
277 |
+
...
|
278 |
+
</ul>
|
279 |
+
|
280 |
+
Results in something like this:
|
281 |
+
|
282 |
+
.. sourcecode:: html
|
283 |
+
|
284 |
+
<ul class="my_list" id="list-42">
|
285 |
+
...
|
286 |
+
</ul>
|
287 |
+
|
288 |
+
As you can see it automatically prepends a space in front of the item
|
289 |
+
if the filter returned something unless the second parameter is false.
|
290 |
+
|
291 |
+
.. versionchanged:: 3.1.4
|
292 |
+
Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign
|
293 |
+
are not allowed.
|
294 |
+
|
295 |
+
.. versionchanged:: 3.1.3
|
296 |
+
Keys with spaces are not allowed.
|
297 |
+
"""
|
298 |
+
items = []
|
299 |
+
|
300 |
+
for key, value in d.items():
|
301 |
+
if value is None or isinstance(value, Undefined):
|
302 |
+
continue
|
303 |
+
|
304 |
+
if _attr_key_re.search(key) is not None:
|
305 |
+
raise ValueError(f"Invalid character in attribute name: {key!r}")
|
306 |
+
|
307 |
+
items.append(f'{escape(key)}="{escape(value)}"')
|
308 |
+
|
309 |
+
rv = " ".join(items)
|
310 |
+
|
311 |
+
if autospace and rv:
|
312 |
+
rv = " " + rv
|
313 |
+
|
314 |
+
if eval_ctx.autoescape:
|
315 |
+
rv = Markup(rv)
|
316 |
+
|
317 |
+
return rv
|
318 |
+
|
319 |
+
|
320 |
+
def do_capitalize(s: str) -> str:
|
321 |
+
"""Capitalize a value. The first character will be uppercase, all others
|
322 |
+
lowercase.
|
323 |
+
"""
|
324 |
+
return soft_str(s).capitalize()
|
325 |
+
|
326 |
+
|
327 |
+
_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")
|
328 |
+
|
329 |
+
|
330 |
+
def do_title(s: str) -> str:
|
331 |
+
"""Return a titlecased version of the value. I.e. words will start with
|
332 |
+
uppercase letters, all remaining characters are lowercase.
|
333 |
+
"""
|
334 |
+
return "".join(
|
335 |
+
[
|
336 |
+
item[0].upper() + item[1:].lower()
|
337 |
+
for item in _word_beginning_split_re.split(soft_str(s))
|
338 |
+
if item
|
339 |
+
]
|
340 |
+
)
|
341 |
+
|
342 |
+
|
343 |
+
def do_dictsort(
|
344 |
+
value: t.Mapping[K, V],
|
345 |
+
case_sensitive: bool = False,
|
346 |
+
by: 'te.Literal["key", "value"]' = "key",
|
347 |
+
reverse: bool = False,
|
348 |
+
) -> t.List[t.Tuple[K, V]]:
|
349 |
+
"""Sort a dict and yield (key, value) pairs. Python dicts may not
|
350 |
+
be in the order you want to display them in, so sort them first.
|
351 |
+
|
352 |
+
.. sourcecode:: jinja
|
353 |
+
|
354 |
+
{% for key, value in mydict|dictsort %}
|
355 |
+
sort the dict by key, case insensitive
|
356 |
+
|
357 |
+
{% for key, value in mydict|dictsort(reverse=true) %}
|
358 |
+
sort the dict by key, case insensitive, reverse order
|
359 |
+
|
360 |
+
{% for key, value in mydict|dictsort(true) %}
|
361 |
+
sort the dict by key, case sensitive
|
362 |
+
|
363 |
+
{% for key, value in mydict|dictsort(false, 'value') %}
|
364 |
+
sort the dict by value, case insensitive
|
365 |
+
"""
|
366 |
+
if by == "key":
|
367 |
+
pos = 0
|
368 |
+
elif by == "value":
|
369 |
+
pos = 1
|
370 |
+
else:
|
371 |
+
raise FilterArgumentError('You can only sort by either "key" or "value"')
|
372 |
+
|
373 |
+
def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:
|
374 |
+
value = item[pos]
|
375 |
+
|
376 |
+
if not case_sensitive:
|
377 |
+
value = ignore_case(value)
|
378 |
+
|
379 |
+
return value
|
380 |
+
|
381 |
+
return sorted(value.items(), key=sort_func, reverse=reverse)
|
382 |
+
|
383 |
+
|
384 |
+
@pass_environment
|
385 |
+
def do_sort(
|
386 |
+
environment: "Environment",
|
387 |
+
value: "t.Iterable[V]",
|
388 |
+
reverse: bool = False,
|
389 |
+
case_sensitive: bool = False,
|
390 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
391 |
+
) -> "t.List[V]":
|
392 |
+
"""Sort an iterable using Python's :func:`sorted`.
|
393 |
+
|
394 |
+
.. sourcecode:: jinja
|
395 |
+
|
396 |
+
{% for city in cities|sort %}
|
397 |
+
...
|
398 |
+
{% endfor %}
|
399 |
+
|
400 |
+
:param reverse: Sort descending instead of ascending.
|
401 |
+
:param case_sensitive: When sorting strings, sort upper and lower
|
402 |
+
case separately.
|
403 |
+
:param attribute: When sorting objects or dicts, an attribute or
|
404 |
+
key to sort by. Can use dot notation like ``"address.city"``.
|
405 |
+
Can be a list of attributes like ``"age,name"``.
|
406 |
+
|
407 |
+
The sort is stable, it does not change the relative order of
|
408 |
+
elements that compare equal. This makes it is possible to chain
|
409 |
+
sorts on different attributes and ordering.
|
410 |
+
|
411 |
+
.. sourcecode:: jinja
|
412 |
+
|
413 |
+
{% for user in users|sort(attribute="name")
|
414 |
+
|sort(reverse=true, attribute="age") %}
|
415 |
+
...
|
416 |
+
{% endfor %}
|
417 |
+
|
418 |
+
As a shortcut to chaining when the direction is the same for all
|
419 |
+
attributes, pass a comma separate list of attributes.
|
420 |
+
|
421 |
+
.. sourcecode:: jinja
|
422 |
+
|
423 |
+
{% for user in users|sort(attribute="age,name") %}
|
424 |
+
...
|
425 |
+
{% endfor %}
|
426 |
+
|
427 |
+
.. versionchanged:: 2.11.0
|
428 |
+
The ``attribute`` parameter can be a comma separated list of
|
429 |
+
attributes, e.g. ``"age,name"``.
|
430 |
+
|
431 |
+
.. versionchanged:: 2.6
|
432 |
+
The ``attribute`` parameter was added.
|
433 |
+
"""
|
434 |
+
key_func = make_multi_attrgetter(
|
435 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
436 |
+
)
|
437 |
+
return sorted(value, key=key_func, reverse=reverse)
|
438 |
+
|
439 |
+
|
440 |
+
@pass_environment
|
441 |
+
def do_unique(
|
442 |
+
environment: "Environment",
|
443 |
+
value: "t.Iterable[V]",
|
444 |
+
case_sensitive: bool = False,
|
445 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
446 |
+
) -> "t.Iterator[V]":
|
447 |
+
"""Returns a list of unique items from the given iterable.
|
448 |
+
|
449 |
+
.. sourcecode:: jinja
|
450 |
+
|
451 |
+
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
|
452 |
+
-> ['foo', 'bar', 'foobar']
|
453 |
+
|
454 |
+
The unique items are yielded in the same order as their first occurrence in
|
455 |
+
the iterable passed to the filter.
|
456 |
+
|
457 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
458 |
+
:param attribute: Filter objects with unique values for this attribute.
|
459 |
+
"""
|
460 |
+
getter = make_attrgetter(
|
461 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
462 |
+
)
|
463 |
+
seen = set()
|
464 |
+
|
465 |
+
for item in value:
|
466 |
+
key = getter(item)
|
467 |
+
|
468 |
+
if key not in seen:
|
469 |
+
seen.add(key)
|
470 |
+
yield item
|
471 |
+
|
472 |
+
|
473 |
+
def _min_or_max(
|
474 |
+
environment: "Environment",
|
475 |
+
value: "t.Iterable[V]",
|
476 |
+
func: "t.Callable[..., V]",
|
477 |
+
case_sensitive: bool,
|
478 |
+
attribute: t.Optional[t.Union[str, int]],
|
479 |
+
) -> "t.Union[V, Undefined]":
|
480 |
+
it = iter(value)
|
481 |
+
|
482 |
+
try:
|
483 |
+
first = next(it)
|
484 |
+
except StopIteration:
|
485 |
+
return environment.undefined("No aggregated item, sequence was empty.")
|
486 |
+
|
487 |
+
key_func = make_attrgetter(
|
488 |
+
environment, attribute, postprocess=ignore_case if not case_sensitive else None
|
489 |
+
)
|
490 |
+
return func(chain([first], it), key=key_func)
|
491 |
+
|
492 |
+
|
493 |
+
@pass_environment
|
494 |
+
def do_min(
|
495 |
+
environment: "Environment",
|
496 |
+
value: "t.Iterable[V]",
|
497 |
+
case_sensitive: bool = False,
|
498 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
499 |
+
) -> "t.Union[V, Undefined]":
|
500 |
+
"""Return the smallest item from the sequence.
|
501 |
+
|
502 |
+
.. sourcecode:: jinja
|
503 |
+
|
504 |
+
{{ [1, 2, 3]|min }}
|
505 |
+
-> 1
|
506 |
+
|
507 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
508 |
+
:param attribute: Get the object with the min value of this attribute.
|
509 |
+
"""
|
510 |
+
return _min_or_max(environment, value, min, case_sensitive, attribute)
|
511 |
+
|
512 |
+
|
513 |
+
@pass_environment
|
514 |
+
def do_max(
|
515 |
+
environment: "Environment",
|
516 |
+
value: "t.Iterable[V]",
|
517 |
+
case_sensitive: bool = False,
|
518 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
519 |
+
) -> "t.Union[V, Undefined]":
|
520 |
+
"""Return the largest item from the sequence.
|
521 |
+
|
522 |
+
.. sourcecode:: jinja
|
523 |
+
|
524 |
+
{{ [1, 2, 3]|max }}
|
525 |
+
-> 3
|
526 |
+
|
527 |
+
:param case_sensitive: Treat upper and lower case strings as distinct.
|
528 |
+
:param attribute: Get the object with the max value of this attribute.
|
529 |
+
"""
|
530 |
+
return _min_or_max(environment, value, max, case_sensitive, attribute)
|
531 |
+
|
532 |
+
|
533 |
+
def do_default(
|
534 |
+
value: V,
|
535 |
+
default_value: V = "", # type: ignore
|
536 |
+
boolean: bool = False,
|
537 |
+
) -> V:
|
538 |
+
"""If the value is undefined it will return the passed default value,
|
539 |
+
otherwise the value of the variable:
|
540 |
+
|
541 |
+
.. sourcecode:: jinja
|
542 |
+
|
543 |
+
{{ my_variable|default('my_variable is not defined') }}
|
544 |
+
|
545 |
+
This will output the value of ``my_variable`` if the variable was
|
546 |
+
defined, otherwise ``'my_variable is not defined'``. If you want
|
547 |
+
to use default with variables that evaluate to false you have to
|
548 |
+
set the second parameter to `true`:
|
549 |
+
|
550 |
+
.. sourcecode:: jinja
|
551 |
+
|
552 |
+
{{ ''|default('the string was empty', true) }}
|
553 |
+
|
554 |
+
.. versionchanged:: 2.11
|
555 |
+
It's now possible to configure the :class:`~jinja2.Environment` with
|
556 |
+
:class:`~jinja2.ChainableUndefined` to make the `default` filter work
|
557 |
+
on nested elements and attributes that may contain undefined values
|
558 |
+
in the chain without getting an :exc:`~jinja2.UndefinedError`.
|
559 |
+
"""
|
560 |
+
if isinstance(value, Undefined) or (boolean and not value):
|
561 |
+
return default_value
|
562 |
+
|
563 |
+
return value
|
564 |
+
|
565 |
+
|
566 |
+
@pass_eval_context
|
567 |
+
def sync_do_join(
|
568 |
+
eval_ctx: "EvalContext",
|
569 |
+
value: t.Iterable[t.Any],
|
570 |
+
d: str = "",
|
571 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
572 |
+
) -> str:
|
573 |
+
"""Return a string which is the concatenation of the strings in the
|
574 |
+
sequence. The separator between elements is an empty string per
|
575 |
+
default, you can define it with the optional parameter:
|
576 |
+
|
577 |
+
.. sourcecode:: jinja
|
578 |
+
|
579 |
+
{{ [1, 2, 3]|join('|') }}
|
580 |
+
-> 1|2|3
|
581 |
+
|
582 |
+
{{ [1, 2, 3]|join }}
|
583 |
+
-> 123
|
584 |
+
|
585 |
+
It is also possible to join certain attributes of an object:
|
586 |
+
|
587 |
+
.. sourcecode:: jinja
|
588 |
+
|
589 |
+
{{ users|join(', ', attribute='username') }}
|
590 |
+
|
591 |
+
.. versionadded:: 2.6
|
592 |
+
The `attribute` parameter was added.
|
593 |
+
"""
|
594 |
+
if attribute is not None:
|
595 |
+
value = map(make_attrgetter(eval_ctx.environment, attribute), value)
|
596 |
+
|
597 |
+
# no automatic escaping? joining is a lot easier then
|
598 |
+
if not eval_ctx.autoescape:
|
599 |
+
return str(d).join(map(str, value))
|
600 |
+
|
601 |
+
# if the delimiter doesn't have an html representation we check
|
602 |
+
# if any of the items has. If yes we do a coercion to Markup
|
603 |
+
if not hasattr(d, "__html__"):
|
604 |
+
value = list(value)
|
605 |
+
do_escape = False
|
606 |
+
|
607 |
+
for idx, item in enumerate(value):
|
608 |
+
if hasattr(item, "__html__"):
|
609 |
+
do_escape = True
|
610 |
+
else:
|
611 |
+
value[idx] = str(item)
|
612 |
+
|
613 |
+
if do_escape:
|
614 |
+
d = escape(d)
|
615 |
+
else:
|
616 |
+
d = str(d)
|
617 |
+
|
618 |
+
return d.join(value)
|
619 |
+
|
620 |
+
# no html involved, to normal joining
|
621 |
+
return soft_str(d).join(map(soft_str, value))
|
622 |
+
|
623 |
+
|
624 |
+
@async_variant(sync_do_join) # type: ignore
|
625 |
+
async def do_join(
|
626 |
+
eval_ctx: "EvalContext",
|
627 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
628 |
+
d: str = "",
|
629 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
630 |
+
) -> str:
|
631 |
+
return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)
|
632 |
+
|
633 |
+
|
634 |
+
def do_center(value: str, width: int = 80) -> str:
|
635 |
+
"""Centers the value in a field of a given width."""
|
636 |
+
return soft_str(value).center(width)
|
637 |
+
|
638 |
+
|
639 |
+
@pass_environment
|
640 |
+
def sync_do_first(
|
641 |
+
environment: "Environment", seq: "t.Iterable[V]"
|
642 |
+
) -> "t.Union[V, Undefined]":
|
643 |
+
"""Return the first item of a sequence."""
|
644 |
+
try:
|
645 |
+
return next(iter(seq))
|
646 |
+
except StopIteration:
|
647 |
+
return environment.undefined("No first item, sequence was empty.")
|
648 |
+
|
649 |
+
|
650 |
+
@async_variant(sync_do_first) # type: ignore
|
651 |
+
async def do_first(
|
652 |
+
environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"
|
653 |
+
) -> "t.Union[V, Undefined]":
|
654 |
+
try:
|
655 |
+
return await auto_aiter(seq).__anext__()
|
656 |
+
except StopAsyncIteration:
|
657 |
+
return environment.undefined("No first item, sequence was empty.")
|
658 |
+
|
659 |
+
|
660 |
+
@pass_environment
|
661 |
+
def do_last(
|
662 |
+
environment: "Environment", seq: "t.Reversible[V]"
|
663 |
+
) -> "t.Union[V, Undefined]":
|
664 |
+
"""Return the last item of a sequence.
|
665 |
+
|
666 |
+
Note: Does not work with generators. You may want to explicitly
|
667 |
+
convert it to a list:
|
668 |
+
|
669 |
+
.. sourcecode:: jinja
|
670 |
+
|
671 |
+
{{ data | selectattr('name', '==', 'Jinja') | list | last }}
|
672 |
+
"""
|
673 |
+
try:
|
674 |
+
return next(iter(reversed(seq)))
|
675 |
+
except StopIteration:
|
676 |
+
return environment.undefined("No last item, sequence was empty.")
|
677 |
+
|
678 |
+
|
679 |
+
# No async do_last, it may not be safe in async mode.
|
680 |
+
|
681 |
+
|
682 |
+
@pass_context
|
683 |
+
def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":
|
684 |
+
"""Return a random item from the sequence."""
|
685 |
+
try:
|
686 |
+
return random.choice(seq)
|
687 |
+
except IndexError:
|
688 |
+
return context.environment.undefined("No random item, sequence was empty.")
|
689 |
+
|
690 |
+
|
691 |
+
def do_filesizeformat(value: t.Union[str, float, int], binary: bool = False) -> str:
|
692 |
+
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
|
693 |
+
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
|
694 |
+
Giga, etc.), if the second parameter is set to `True` the binary
|
695 |
+
prefixes are used (Mebi, Gibi).
|
696 |
+
"""
|
697 |
+
bytes = float(value)
|
698 |
+
base = 1024 if binary else 1000
|
699 |
+
prefixes = [
|
700 |
+
("KiB" if binary else "kB"),
|
701 |
+
("MiB" if binary else "MB"),
|
702 |
+
("GiB" if binary else "GB"),
|
703 |
+
("TiB" if binary else "TB"),
|
704 |
+
("PiB" if binary else "PB"),
|
705 |
+
("EiB" if binary else "EB"),
|
706 |
+
("ZiB" if binary else "ZB"),
|
707 |
+
("YiB" if binary else "YB"),
|
708 |
+
]
|
709 |
+
|
710 |
+
if bytes == 1:
|
711 |
+
return "1 Byte"
|
712 |
+
elif bytes < base:
|
713 |
+
return f"{int(bytes)} Bytes"
|
714 |
+
else:
|
715 |
+
for i, prefix in enumerate(prefixes):
|
716 |
+
unit = base ** (i + 2)
|
717 |
+
|
718 |
+
if bytes < unit:
|
719 |
+
return f"{base * bytes / unit:.1f} {prefix}"
|
720 |
+
|
721 |
+
return f"{base * bytes / unit:.1f} {prefix}"
|
722 |
+
|
723 |
+
|
724 |
+
def do_pprint(value: t.Any) -> str:
|
725 |
+
"""Pretty print a variable. Useful for debugging."""
|
726 |
+
return pformat(value)
|
727 |
+
|
728 |
+
|
729 |
+
_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")
|
730 |
+
|
731 |
+
|
732 |
+
@pass_eval_context
|
733 |
+
def do_urlize(
|
734 |
+
eval_ctx: "EvalContext",
|
735 |
+
value: str,
|
736 |
+
trim_url_limit: t.Optional[int] = None,
|
737 |
+
nofollow: bool = False,
|
738 |
+
target: t.Optional[str] = None,
|
739 |
+
rel: t.Optional[str] = None,
|
740 |
+
extra_schemes: t.Optional[t.Iterable[str]] = None,
|
741 |
+
) -> str:
|
742 |
+
"""Convert URLs in text into clickable links.
|
743 |
+
|
744 |
+
This may not recognize links in some situations. Usually, a more
|
745 |
+
comprehensive formatter, such as a Markdown library, is a better
|
746 |
+
choice.
|
747 |
+
|
748 |
+
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
|
749 |
+
addresses. Links with trailing punctuation (periods, commas, closing
|
750 |
+
parentheses) and leading punctuation (opening parentheses) are
|
751 |
+
recognized excluding the punctuation. Email addresses that include
|
752 |
+
header fields are not recognized (for example,
|
753 |
+
``mailto:[email protected][email protected]``).
|
754 |
+
|
755 |
+
:param value: Original text containing URLs to link.
|
756 |
+
:param trim_url_limit: Shorten displayed URL values to this length.
|
757 |
+
:param nofollow: Add the ``rel=nofollow`` attribute to links.
|
758 |
+
:param target: Add the ``target`` attribute to links.
|
759 |
+
:param rel: Add the ``rel`` attribute to links.
|
760 |
+
:param extra_schemes: Recognize URLs that start with these schemes
|
761 |
+
in addition to the default behavior. Defaults to
|
762 |
+
``env.policies["urlize.extra_schemes"]``, which defaults to no
|
763 |
+
extra schemes.
|
764 |
+
|
765 |
+
.. versionchanged:: 3.0
|
766 |
+
The ``extra_schemes`` parameter was added.
|
767 |
+
|
768 |
+
.. versionchanged:: 3.0
|
769 |
+
Generate ``https://`` links for URLs without a scheme.
|
770 |
+
|
771 |
+
.. versionchanged:: 3.0
|
772 |
+
The parsing rules were updated. Recognize email addresses with
|
773 |
+
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
|
774 |
+
parentheses and brackets in more cases.
|
775 |
+
|
776 |
+
.. versionchanged:: 2.8
|
777 |
+
The ``target`` parameter was added.
|
778 |
+
"""
|
779 |
+
policies = eval_ctx.environment.policies
|
780 |
+
rel_parts = set((rel or "").split())
|
781 |
+
|
782 |
+
if nofollow:
|
783 |
+
rel_parts.add("nofollow")
|
784 |
+
|
785 |
+
rel_parts.update((policies["urlize.rel"] or "").split())
|
786 |
+
rel = " ".join(sorted(rel_parts)) or None
|
787 |
+
|
788 |
+
if target is None:
|
789 |
+
target = policies["urlize.target"]
|
790 |
+
|
791 |
+
if extra_schemes is None:
|
792 |
+
extra_schemes = policies["urlize.extra_schemes"] or ()
|
793 |
+
|
794 |
+
for scheme in extra_schemes:
|
795 |
+
if _uri_scheme_re.fullmatch(scheme) is None:
|
796 |
+
raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")
|
797 |
+
|
798 |
+
rv = urlize(
|
799 |
+
value,
|
800 |
+
trim_url_limit=trim_url_limit,
|
801 |
+
rel=rel,
|
802 |
+
target=target,
|
803 |
+
extra_schemes=extra_schemes,
|
804 |
+
)
|
805 |
+
|
806 |
+
if eval_ctx.autoescape:
|
807 |
+
rv = Markup(rv)
|
808 |
+
|
809 |
+
return rv
|
810 |
+
|
811 |
+
|
812 |
+
def do_indent(
|
813 |
+
s: str, width: t.Union[int, str] = 4, first: bool = False, blank: bool = False
|
814 |
+
) -> str:
|
815 |
+
"""Return a copy of the string with each line indented by 4 spaces. The
|
816 |
+
first line and blank lines are not indented by default.
|
817 |
+
|
818 |
+
:param width: Number of spaces, or a string, to indent by.
|
819 |
+
:param first: Don't skip indenting the first line.
|
820 |
+
:param blank: Don't skip indenting empty lines.
|
821 |
+
|
822 |
+
.. versionchanged:: 3.0
|
823 |
+
``width`` can be a string.
|
824 |
+
|
825 |
+
.. versionchanged:: 2.10
|
826 |
+
Blank lines are not indented by default.
|
827 |
+
|
828 |
+
Rename the ``indentfirst`` argument to ``first``.
|
829 |
+
"""
|
830 |
+
if isinstance(width, str):
|
831 |
+
indention = width
|
832 |
+
else:
|
833 |
+
indention = " " * width
|
834 |
+
|
835 |
+
newline = "\n"
|
836 |
+
|
837 |
+
if isinstance(s, Markup):
|
838 |
+
indention = Markup(indention)
|
839 |
+
newline = Markup(newline)
|
840 |
+
|
841 |
+
s += newline # this quirk is necessary for splitlines method
|
842 |
+
|
843 |
+
if blank:
|
844 |
+
rv = (newline + indention).join(s.splitlines())
|
845 |
+
else:
|
846 |
+
lines = s.splitlines()
|
847 |
+
rv = lines.pop(0)
|
848 |
+
|
849 |
+
if lines:
|
850 |
+
rv += newline + newline.join(
|
851 |
+
indention + line if line else line for line in lines
|
852 |
+
)
|
853 |
+
|
854 |
+
if first:
|
855 |
+
rv = indention + rv
|
856 |
+
|
857 |
+
return rv
|
858 |
+
|
859 |
+
|
860 |
+
@pass_environment
|
861 |
+
def do_truncate(
|
862 |
+
env: "Environment",
|
863 |
+
s: str,
|
864 |
+
length: int = 255,
|
865 |
+
killwords: bool = False,
|
866 |
+
end: str = "...",
|
867 |
+
leeway: t.Optional[int] = None,
|
868 |
+
) -> str:
|
869 |
+
"""Return a truncated copy of the string. The length is specified
|
870 |
+
with the first parameter which defaults to ``255``. If the second
|
871 |
+
parameter is ``true`` the filter will cut the text at length. Otherwise
|
872 |
+
it will discard the last word. If the text was in fact
|
873 |
+
truncated it will append an ellipsis sign (``"..."``). If you want a
|
874 |
+
different ellipsis sign than ``"..."`` you can specify it using the
|
875 |
+
third parameter. Strings that only exceed the length by the tolerance
|
876 |
+
margin given in the fourth parameter will not be truncated.
|
877 |
+
|
878 |
+
.. sourcecode:: jinja
|
879 |
+
|
880 |
+
{{ "foo bar baz qux"|truncate(9) }}
|
881 |
+
-> "foo..."
|
882 |
+
{{ "foo bar baz qux"|truncate(9, True) }}
|
883 |
+
-> "foo ba..."
|
884 |
+
{{ "foo bar baz qux"|truncate(11) }}
|
885 |
+
-> "foo bar baz qux"
|
886 |
+
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
|
887 |
+
-> "foo bar..."
|
888 |
+
|
889 |
+
The default leeway on newer Jinja versions is 5 and was 0 before but
|
890 |
+
can be reconfigured globally.
|
891 |
+
"""
|
892 |
+
if leeway is None:
|
893 |
+
leeway = env.policies["truncate.leeway"]
|
894 |
+
|
895 |
+
assert length >= len(end), f"expected length >= {len(end)}, got {length}"
|
896 |
+
assert leeway >= 0, f"expected leeway >= 0, got {leeway}"
|
897 |
+
|
898 |
+
if len(s) <= length + leeway:
|
899 |
+
return s
|
900 |
+
|
901 |
+
if killwords:
|
902 |
+
return s[: length - len(end)] + end
|
903 |
+
|
904 |
+
result = s[: length - len(end)].rsplit(" ", 1)[0]
|
905 |
+
return result + end
|
906 |
+
|
907 |
+
|
908 |
+
@pass_environment
|
909 |
+
def do_wordwrap(
|
910 |
+
environment: "Environment",
|
911 |
+
s: str,
|
912 |
+
width: int = 79,
|
913 |
+
break_long_words: bool = True,
|
914 |
+
wrapstring: t.Optional[str] = None,
|
915 |
+
break_on_hyphens: bool = True,
|
916 |
+
) -> str:
|
917 |
+
"""Wrap a string to the given width. Existing newlines are treated
|
918 |
+
as paragraphs to be wrapped separately.
|
919 |
+
|
920 |
+
:param s: Original text to wrap.
|
921 |
+
:param width: Maximum length of wrapped lines.
|
922 |
+
:param break_long_words: If a word is longer than ``width``, break
|
923 |
+
it across lines.
|
924 |
+
:param break_on_hyphens: If a word contains hyphens, it may be split
|
925 |
+
across lines.
|
926 |
+
:param wrapstring: String to join each wrapped line. Defaults to
|
927 |
+
:attr:`Environment.newline_sequence`.
|
928 |
+
|
929 |
+
.. versionchanged:: 2.11
|
930 |
+
Existing newlines are treated as paragraphs wrapped separately.
|
931 |
+
|
932 |
+
.. versionchanged:: 2.11
|
933 |
+
Added the ``break_on_hyphens`` parameter.
|
934 |
+
|
935 |
+
.. versionchanged:: 2.7
|
936 |
+
Added the ``wrapstring`` parameter.
|
937 |
+
"""
|
938 |
+
import textwrap
|
939 |
+
|
940 |
+
if wrapstring is None:
|
941 |
+
wrapstring = environment.newline_sequence
|
942 |
+
|
943 |
+
# textwrap.wrap doesn't consider existing newlines when wrapping.
|
944 |
+
# If the string has a newline before width, wrap will still insert
|
945 |
+
# a newline at width, resulting in a short line. Instead, split and
|
946 |
+
# wrap each paragraph individually.
|
947 |
+
return wrapstring.join(
|
948 |
+
[
|
949 |
+
wrapstring.join(
|
950 |
+
textwrap.wrap(
|
951 |
+
line,
|
952 |
+
width=width,
|
953 |
+
expand_tabs=False,
|
954 |
+
replace_whitespace=False,
|
955 |
+
break_long_words=break_long_words,
|
956 |
+
break_on_hyphens=break_on_hyphens,
|
957 |
+
)
|
958 |
+
)
|
959 |
+
for line in s.splitlines()
|
960 |
+
]
|
961 |
+
)
|
962 |
+
|
963 |
+
|
964 |
+
_word_re = re.compile(r"\w+")
|
965 |
+
|
966 |
+
|
967 |
+
def do_wordcount(s: str) -> int:
|
968 |
+
"""Count the words in that string."""
|
969 |
+
return len(_word_re.findall(soft_str(s)))
|
970 |
+
|
971 |
+
|
972 |
+
def do_int(value: t.Any, default: int = 0, base: int = 10) -> int:
|
973 |
+
"""Convert the value into an integer. If the
|
974 |
+
conversion doesn't work it will return ``0``. You can
|
975 |
+
override this default using the first parameter. You
|
976 |
+
can also override the default base (10) in the second
|
977 |
+
parameter, which handles input with prefixes such as
|
978 |
+
0b, 0o and 0x for bases 2, 8 and 16 respectively.
|
979 |
+
The base is ignored for decimal numbers and non-string values.
|
980 |
+
"""
|
981 |
+
try:
|
982 |
+
if isinstance(value, str):
|
983 |
+
return int(value, base)
|
984 |
+
|
985 |
+
return int(value)
|
986 |
+
except (TypeError, ValueError):
|
987 |
+
# this quirk is necessary so that "42.23"|int gives 42.
|
988 |
+
try:
|
989 |
+
return int(float(value))
|
990 |
+
except (TypeError, ValueError):
|
991 |
+
return default
|
992 |
+
|
993 |
+
|
994 |
+
def do_float(value: t.Any, default: float = 0.0) -> float:
|
995 |
+
"""Convert the value into a floating point number. If the
|
996 |
+
conversion doesn't work it will return ``0.0``. You can
|
997 |
+
override this default using the first parameter.
|
998 |
+
"""
|
999 |
+
try:
|
1000 |
+
return float(value)
|
1001 |
+
except (TypeError, ValueError):
|
1002 |
+
return default
|
1003 |
+
|
1004 |
+
|
1005 |
+
def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
|
1006 |
+
"""Apply the given values to a `printf-style`_ format string, like
|
1007 |
+
``string % values``.
|
1008 |
+
|
1009 |
+
.. sourcecode:: jinja
|
1010 |
+
|
1011 |
+
{{ "%s, %s!"|format(greeting, name) }}
|
1012 |
+
Hello, World!
|
1013 |
+
|
1014 |
+
In most cases it should be more convenient and efficient to use the
|
1015 |
+
``%`` operator or :meth:`str.format`.
|
1016 |
+
|
1017 |
+
.. code-block:: text
|
1018 |
+
|
1019 |
+
{{ "%s, %s!" % (greeting, name) }}
|
1020 |
+
{{ "{}, {}!".format(greeting, name) }}
|
1021 |
+
|
1022 |
+
.. _printf-style: https://docs.python.org/library/stdtypes.html
|
1023 |
+
#printf-style-string-formatting
|
1024 |
+
"""
|
1025 |
+
if args and kwargs:
|
1026 |
+
raise FilterArgumentError(
|
1027 |
+
"can't handle positional and keyword arguments at the same time"
|
1028 |
+
)
|
1029 |
+
|
1030 |
+
return soft_str(value) % (kwargs or args)
|
1031 |
+
|
1032 |
+
|
1033 |
+
def do_trim(value: str, chars: t.Optional[str] = None) -> str:
|
1034 |
+
"""Strip leading and trailing characters, by default whitespace."""
|
1035 |
+
return soft_str(value).strip(chars)
|
1036 |
+
|
1037 |
+
|
1038 |
+
def do_striptags(value: "t.Union[str, HasHTML]") -> str:
|
1039 |
+
"""Strip SGML/XML tags and replace adjacent whitespace by one space."""
|
1040 |
+
if hasattr(value, "__html__"):
|
1041 |
+
value = t.cast("HasHTML", value).__html__()
|
1042 |
+
|
1043 |
+
return Markup(str(value)).striptags()
|
1044 |
+
|
1045 |
+
|
1046 |
+
def sync_do_slice(
|
1047 |
+
value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None
|
1048 |
+
) -> "t.Iterator[t.List[V]]":
|
1049 |
+
"""Slice an iterator and return a list of lists containing
|
1050 |
+
those items. Useful if you want to create a div containing
|
1051 |
+
three ul tags that represent columns:
|
1052 |
+
|
1053 |
+
.. sourcecode:: html+jinja
|
1054 |
+
|
1055 |
+
<div class="columnwrapper">
|
1056 |
+
{%- for column in items|slice(3) %}
|
1057 |
+
<ul class="column-{{ loop.index }}">
|
1058 |
+
{%- for item in column %}
|
1059 |
+
<li>{{ item }}</li>
|
1060 |
+
{%- endfor %}
|
1061 |
+
</ul>
|
1062 |
+
{%- endfor %}
|
1063 |
+
</div>
|
1064 |
+
|
1065 |
+
If you pass it a second argument it's used to fill missing
|
1066 |
+
values on the last iteration.
|
1067 |
+
"""
|
1068 |
+
seq = list(value)
|
1069 |
+
length = len(seq)
|
1070 |
+
items_per_slice = length // slices
|
1071 |
+
slices_with_extra = length % slices
|
1072 |
+
offset = 0
|
1073 |
+
|
1074 |
+
for slice_number in range(slices):
|
1075 |
+
start = offset + slice_number * items_per_slice
|
1076 |
+
|
1077 |
+
if slice_number < slices_with_extra:
|
1078 |
+
offset += 1
|
1079 |
+
|
1080 |
+
end = offset + (slice_number + 1) * items_per_slice
|
1081 |
+
tmp = seq[start:end]
|
1082 |
+
|
1083 |
+
if fill_with is not None and slice_number >= slices_with_extra:
|
1084 |
+
tmp.append(fill_with)
|
1085 |
+
|
1086 |
+
yield tmp
|
1087 |
+
|
1088 |
+
|
1089 |
+
@async_variant(sync_do_slice) # type: ignore
|
1090 |
+
async def do_slice(
|
1091 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1092 |
+
slices: int,
|
1093 |
+
fill_with: t.Optional[t.Any] = None,
|
1094 |
+
) -> "t.Iterator[t.List[V]]":
|
1095 |
+
return sync_do_slice(await auto_to_list(value), slices, fill_with)
|
1096 |
+
|
1097 |
+
|
1098 |
+
def do_batch(
|
1099 |
+
value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
|
1100 |
+
) -> "t.Iterator[t.List[V]]":
|
1101 |
+
"""
|
1102 |
+
A filter that batches items. It works pretty much like `slice`
|
1103 |
+
just the other way round. It returns a list of lists with the
|
1104 |
+
given number of items. If you provide a second parameter this
|
1105 |
+
is used to fill up missing items. See this example:
|
1106 |
+
|
1107 |
+
.. sourcecode:: html+jinja
|
1108 |
+
|
1109 |
+
<table>
|
1110 |
+
{%- for row in items|batch(3, ' ') %}
|
1111 |
+
<tr>
|
1112 |
+
{%- for column in row %}
|
1113 |
+
<td>{{ column }}</td>
|
1114 |
+
{%- endfor %}
|
1115 |
+
</tr>
|
1116 |
+
{%- endfor %}
|
1117 |
+
</table>
|
1118 |
+
"""
|
1119 |
+
tmp: "t.List[V]" = []
|
1120 |
+
|
1121 |
+
for item in value:
|
1122 |
+
if len(tmp) == linecount:
|
1123 |
+
yield tmp
|
1124 |
+
tmp = []
|
1125 |
+
|
1126 |
+
tmp.append(item)
|
1127 |
+
|
1128 |
+
if tmp:
|
1129 |
+
if fill_with is not None and len(tmp) < linecount:
|
1130 |
+
tmp += [fill_with] * (linecount - len(tmp))
|
1131 |
+
|
1132 |
+
yield tmp
|
1133 |
+
|
1134 |
+
|
1135 |
+
def do_round(
|
1136 |
+
value: float,
|
1137 |
+
precision: int = 0,
|
1138 |
+
method: 'te.Literal["common", "ceil", "floor"]' = "common",
|
1139 |
+
) -> float:
|
1140 |
+
"""Round the number to a given precision. The first
|
1141 |
+
parameter specifies the precision (default is ``0``), the
|
1142 |
+
second the rounding method:
|
1143 |
+
|
1144 |
+
- ``'common'`` rounds either up or down
|
1145 |
+
- ``'ceil'`` always rounds up
|
1146 |
+
- ``'floor'`` always rounds down
|
1147 |
+
|
1148 |
+
If you don't specify a method ``'common'`` is used.
|
1149 |
+
|
1150 |
+
.. sourcecode:: jinja
|
1151 |
+
|
1152 |
+
{{ 42.55|round }}
|
1153 |
+
-> 43.0
|
1154 |
+
{{ 42.55|round(1, 'floor') }}
|
1155 |
+
-> 42.5
|
1156 |
+
|
1157 |
+
Note that even if rounded to 0 precision, a float is returned. If
|
1158 |
+
you need a real integer, pipe it through `int`:
|
1159 |
+
|
1160 |
+
.. sourcecode:: jinja
|
1161 |
+
|
1162 |
+
{{ 42.55|round|int }}
|
1163 |
+
-> 43
|
1164 |
+
"""
|
1165 |
+
if method not in {"common", "ceil", "floor"}:
|
1166 |
+
raise FilterArgumentError("method must be common, ceil or floor")
|
1167 |
+
|
1168 |
+
if method == "common":
|
1169 |
+
return round(value, precision)
|
1170 |
+
|
1171 |
+
func = getattr(math, method)
|
1172 |
+
return t.cast(float, func(value * (10**precision)) / (10**precision))
|
1173 |
+
|
1174 |
+
|
1175 |
+
class _GroupTuple(t.NamedTuple):
|
1176 |
+
grouper: t.Any
|
1177 |
+
list: t.List[t.Any]
|
1178 |
+
|
1179 |
+
# Use the regular tuple repr to hide this subclass if users print
|
1180 |
+
# out the value during debugging.
|
1181 |
+
def __repr__(self) -> str:
|
1182 |
+
return tuple.__repr__(self)
|
1183 |
+
|
1184 |
+
def __str__(self) -> str:
|
1185 |
+
return tuple.__str__(self)
|
1186 |
+
|
1187 |
+
|
1188 |
+
@pass_environment
|
1189 |
+
def sync_do_groupby(
|
1190 |
+
environment: "Environment",
|
1191 |
+
value: "t.Iterable[V]",
|
1192 |
+
attribute: t.Union[str, int],
|
1193 |
+
default: t.Optional[t.Any] = None,
|
1194 |
+
case_sensitive: bool = False,
|
1195 |
+
) -> "t.List[_GroupTuple]":
|
1196 |
+
"""Group a sequence of objects by an attribute using Python's
|
1197 |
+
:func:`itertools.groupby`. The attribute can use dot notation for
|
1198 |
+
nested access, like ``"address.city"``. Unlike Python's ``groupby``,
|
1199 |
+
the values are sorted first so only one group is returned for each
|
1200 |
+
unique value.
|
1201 |
+
|
1202 |
+
For example, a list of ``User`` objects with a ``city`` attribute
|
1203 |
+
can be rendered in groups. In this example, ``grouper`` refers to
|
1204 |
+
the ``city`` value of the group.
|
1205 |
+
|
1206 |
+
.. sourcecode:: html+jinja
|
1207 |
+
|
1208 |
+
<ul>{% for city, items in users|groupby("city") %}
|
1209 |
+
<li>{{ city }}
|
1210 |
+
<ul>{% for user in items %}
|
1211 |
+
<li>{{ user.name }}
|
1212 |
+
{% endfor %}</ul>
|
1213 |
+
</li>
|
1214 |
+
{% endfor %}</ul>
|
1215 |
+
|
1216 |
+
``groupby`` yields namedtuples of ``(grouper, list)``, which
|
1217 |
+
can be used instead of the tuple unpacking above. ``grouper`` is the
|
1218 |
+
value of the attribute, and ``list`` is the items with that value.
|
1219 |
+
|
1220 |
+
.. sourcecode:: html+jinja
|
1221 |
+
|
1222 |
+
<ul>{% for group in users|groupby("city") %}
|
1223 |
+
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
|
1224 |
+
{% endfor %}</ul>
|
1225 |
+
|
1226 |
+
You can specify a ``default`` value to use if an object in the list
|
1227 |
+
does not have the given attribute.
|
1228 |
+
|
1229 |
+
.. sourcecode:: jinja
|
1230 |
+
|
1231 |
+
<ul>{% for city, items in users|groupby("city", default="NY") %}
|
1232 |
+
<li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
|
1233 |
+
{% endfor %}</ul>
|
1234 |
+
|
1235 |
+
Like the :func:`~jinja-filters.sort` filter, sorting and grouping is
|
1236 |
+
case-insensitive by default. The ``key`` for each group will have
|
1237 |
+
the case of the first item in that group of values. For example, if
|
1238 |
+
a list of users has cities ``["CA", "NY", "ca"]``, the "CA" group
|
1239 |
+
will have two values. This can be disabled by passing
|
1240 |
+
``case_sensitive=True``.
|
1241 |
+
|
1242 |
+
.. versionchanged:: 3.1
|
1243 |
+
Added the ``case_sensitive`` parameter. Sorting and grouping is
|
1244 |
+
case-insensitive by default, matching other filters that do
|
1245 |
+
comparisons.
|
1246 |
+
|
1247 |
+
.. versionchanged:: 3.0
|
1248 |
+
Added the ``default`` parameter.
|
1249 |
+
|
1250 |
+
.. versionchanged:: 2.6
|
1251 |
+
The attribute supports dot notation for nested access.
|
1252 |
+
"""
|
1253 |
+
expr = make_attrgetter(
|
1254 |
+
environment,
|
1255 |
+
attribute,
|
1256 |
+
postprocess=ignore_case if not case_sensitive else None,
|
1257 |
+
default=default,
|
1258 |
+
)
|
1259 |
+
out = [
|
1260 |
+
_GroupTuple(key, list(values))
|
1261 |
+
for key, values in groupby(sorted(value, key=expr), expr)
|
1262 |
+
]
|
1263 |
+
|
1264 |
+
if not case_sensitive:
|
1265 |
+
# Return the real key from the first value instead of the lowercase key.
|
1266 |
+
output_expr = make_attrgetter(environment, attribute, default=default)
|
1267 |
+
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
|
1268 |
+
|
1269 |
+
return out
|
1270 |
+
|
1271 |
+
|
1272 |
+
@async_variant(sync_do_groupby) # type: ignore
|
1273 |
+
async def do_groupby(
|
1274 |
+
environment: "Environment",
|
1275 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1276 |
+
attribute: t.Union[str, int],
|
1277 |
+
default: t.Optional[t.Any] = None,
|
1278 |
+
case_sensitive: bool = False,
|
1279 |
+
) -> "t.List[_GroupTuple]":
|
1280 |
+
expr = make_attrgetter(
|
1281 |
+
environment,
|
1282 |
+
attribute,
|
1283 |
+
postprocess=ignore_case if not case_sensitive else None,
|
1284 |
+
default=default,
|
1285 |
+
)
|
1286 |
+
out = [
|
1287 |
+
_GroupTuple(key, await auto_to_list(values))
|
1288 |
+
for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
|
1289 |
+
]
|
1290 |
+
|
1291 |
+
if not case_sensitive:
|
1292 |
+
# Return the real key from the first value instead of the lowercase key.
|
1293 |
+
output_expr = make_attrgetter(environment, attribute, default=default)
|
1294 |
+
out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]
|
1295 |
+
|
1296 |
+
return out
|
1297 |
+
|
1298 |
+
|
1299 |
+
@pass_environment
|
1300 |
+
def sync_do_sum(
|
1301 |
+
environment: "Environment",
|
1302 |
+
iterable: "t.Iterable[V]",
|
1303 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
1304 |
+
start: V = 0, # type: ignore
|
1305 |
+
) -> V:
|
1306 |
+
"""Returns the sum of a sequence of numbers plus the value of parameter
|
1307 |
+
'start' (which defaults to 0). When the sequence is empty it returns
|
1308 |
+
start.
|
1309 |
+
|
1310 |
+
It is also possible to sum up only certain attributes:
|
1311 |
+
|
1312 |
+
.. sourcecode:: jinja
|
1313 |
+
|
1314 |
+
Total: {{ items|sum(attribute='price') }}
|
1315 |
+
|
1316 |
+
.. versionchanged:: 2.6
|
1317 |
+
The ``attribute`` parameter was added to allow summing up over
|
1318 |
+
attributes. Also the ``start`` parameter was moved on to the right.
|
1319 |
+
"""
|
1320 |
+
if attribute is not None:
|
1321 |
+
iterable = map(make_attrgetter(environment, attribute), iterable)
|
1322 |
+
|
1323 |
+
return sum(iterable, start) # type: ignore[no-any-return, call-overload]
|
1324 |
+
|
1325 |
+
|
1326 |
+
@async_variant(sync_do_sum) # type: ignore
|
1327 |
+
async def do_sum(
|
1328 |
+
environment: "Environment",
|
1329 |
+
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1330 |
+
attribute: t.Optional[t.Union[str, int]] = None,
|
1331 |
+
start: V = 0, # type: ignore
|
1332 |
+
) -> V:
|
1333 |
+
rv = start
|
1334 |
+
|
1335 |
+
if attribute is not None:
|
1336 |
+
func = make_attrgetter(environment, attribute)
|
1337 |
+
else:
|
1338 |
+
|
1339 |
+
def func(x: V) -> V:
|
1340 |
+
return x
|
1341 |
+
|
1342 |
+
async for item in auto_aiter(iterable):
|
1343 |
+
rv += func(item)
|
1344 |
+
|
1345 |
+
return rv
|
1346 |
+
|
1347 |
+
|
1348 |
+
def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":
|
1349 |
+
"""Convert the value into a list. If it was a string the returned list
|
1350 |
+
will be a list of characters.
|
1351 |
+
"""
|
1352 |
+
return list(value)
|
1353 |
+
|
1354 |
+
|
1355 |
+
@async_variant(sync_do_list) # type: ignore
|
1356 |
+
async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":
|
1357 |
+
return await auto_to_list(value)
|
1358 |
+
|
1359 |
+
|
1360 |
+
def do_mark_safe(value: str) -> Markup:
|
1361 |
+
"""Mark the value as safe which means that in an environment with automatic
|
1362 |
+
escaping enabled this variable will not be escaped.
|
1363 |
+
"""
|
1364 |
+
return Markup(value)
|
1365 |
+
|
1366 |
+
|
1367 |
+
def do_mark_unsafe(value: str) -> str:
|
1368 |
+
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
|
1369 |
+
return str(value)
|
1370 |
+
|
1371 |
+
|
1372 |
+
@typing.overload
|
1373 |
+
def do_reverse(value: str) -> str: ...
|
1374 |
+
|
1375 |
+
|
1376 |
+
@typing.overload
|
1377 |
+
def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...
|
1378 |
+
|
1379 |
+
|
1380 |
+
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
|
1381 |
+
"""Reverse the object or return an iterator that iterates over it the other
|
1382 |
+
way round.
|
1383 |
+
"""
|
1384 |
+
if isinstance(value, str):
|
1385 |
+
return value[::-1]
|
1386 |
+
|
1387 |
+
try:
|
1388 |
+
return reversed(value) # type: ignore
|
1389 |
+
except TypeError:
|
1390 |
+
try:
|
1391 |
+
rv = list(value)
|
1392 |
+
rv.reverse()
|
1393 |
+
return rv
|
1394 |
+
except TypeError as e:
|
1395 |
+
raise FilterArgumentError("argument must be iterable") from e
|
1396 |
+
|
1397 |
+
|
1398 |
+
@pass_environment
|
1399 |
+
def do_attr(
|
1400 |
+
environment: "Environment", obj: t.Any, name: str
|
1401 |
+
) -> t.Union[Undefined, t.Any]:
|
1402 |
+
"""Get an attribute of an object. ``foo|attr("bar")`` works like
|
1403 |
+
``foo.bar`` just that always an attribute is returned and items are not
|
1404 |
+
looked up.
|
1405 |
+
|
1406 |
+
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
|
1407 |
+
"""
|
1408 |
+
try:
|
1409 |
+
name = str(name)
|
1410 |
+
except UnicodeError:
|
1411 |
+
pass
|
1412 |
+
else:
|
1413 |
+
try:
|
1414 |
+
value = getattr(obj, name)
|
1415 |
+
except AttributeError:
|
1416 |
+
pass
|
1417 |
+
else:
|
1418 |
+
if environment.sandboxed:
|
1419 |
+
environment = t.cast("SandboxedEnvironment", environment)
|
1420 |
+
|
1421 |
+
if not environment.is_safe_attribute(obj, name, value):
|
1422 |
+
return environment.unsafe_undefined(obj, name)
|
1423 |
+
|
1424 |
+
return value
|
1425 |
+
|
1426 |
+
return environment.undefined(obj=obj, name=name)
|
1427 |
+
|
1428 |
+
|
1429 |
+
@typing.overload
|
1430 |
+
def sync_do_map(
|
1431 |
+
context: "Context",
|
1432 |
+
value: t.Iterable[t.Any],
|
1433 |
+
name: str,
|
1434 |
+
*args: t.Any,
|
1435 |
+
**kwargs: t.Any,
|
1436 |
+
) -> t.Iterable[t.Any]: ...
|
1437 |
+
|
1438 |
+
|
1439 |
+
@typing.overload
|
1440 |
+
def sync_do_map(
|
1441 |
+
context: "Context",
|
1442 |
+
value: t.Iterable[t.Any],
|
1443 |
+
*,
|
1444 |
+
attribute: str = ...,
|
1445 |
+
default: t.Optional[t.Any] = None,
|
1446 |
+
) -> t.Iterable[t.Any]: ...
|
1447 |
+
|
1448 |
+
|
1449 |
+
@pass_context
|
1450 |
+
def sync_do_map(
|
1451 |
+
context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any
|
1452 |
+
) -> t.Iterable[t.Any]:
|
1453 |
+
"""Applies a filter on a sequence of objects or looks up an attribute.
|
1454 |
+
This is useful when dealing with lists of objects but you are really
|
1455 |
+
only interested in a certain value of it.
|
1456 |
+
|
1457 |
+
The basic usage is mapping on an attribute. Imagine you have a list
|
1458 |
+
of users but you are only interested in a list of usernames:
|
1459 |
+
|
1460 |
+
.. sourcecode:: jinja
|
1461 |
+
|
1462 |
+
Users on this page: {{ users|map(attribute='username')|join(', ') }}
|
1463 |
+
|
1464 |
+
You can specify a ``default`` value to use if an object in the list
|
1465 |
+
does not have the given attribute.
|
1466 |
+
|
1467 |
+
.. sourcecode:: jinja
|
1468 |
+
|
1469 |
+
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
|
1470 |
+
|
1471 |
+
Alternatively you can let it invoke a filter by passing the name of the
|
1472 |
+
filter and the arguments afterwards. A good example would be applying a
|
1473 |
+
text conversion filter on a sequence:
|
1474 |
+
|
1475 |
+
.. sourcecode:: jinja
|
1476 |
+
|
1477 |
+
Users on this page: {{ titles|map('lower')|join(', ') }}
|
1478 |
+
|
1479 |
+
Similar to a generator comprehension such as:
|
1480 |
+
|
1481 |
+
.. code-block:: python
|
1482 |
+
|
1483 |
+
(u.username for u in users)
|
1484 |
+
(getattr(u, "username", "Anonymous") for u in users)
|
1485 |
+
(do_lower(x) for x in titles)
|
1486 |
+
|
1487 |
+
.. versionchanged:: 2.11.0
|
1488 |
+
Added the ``default`` parameter.
|
1489 |
+
|
1490 |
+
.. versionadded:: 2.7
|
1491 |
+
"""
|
1492 |
+
if value:
|
1493 |
+
func = prepare_map(context, args, kwargs)
|
1494 |
+
|
1495 |
+
for item in value:
|
1496 |
+
yield func(item)
|
1497 |
+
|
1498 |
+
|
1499 |
+
@typing.overload
|
1500 |
+
def do_map(
|
1501 |
+
context: "Context",
|
1502 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
1503 |
+
name: str,
|
1504 |
+
*args: t.Any,
|
1505 |
+
**kwargs: t.Any,
|
1506 |
+
) -> t.Iterable[t.Any]: ...
|
1507 |
+
|
1508 |
+
|
1509 |
+
@typing.overload
|
1510 |
+
def do_map(
|
1511 |
+
context: "Context",
|
1512 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
1513 |
+
*,
|
1514 |
+
attribute: str = ...,
|
1515 |
+
default: t.Optional[t.Any] = None,
|
1516 |
+
) -> t.Iterable[t.Any]: ...
|
1517 |
+
|
1518 |
+
|
1519 |
+
@async_variant(sync_do_map) # type: ignore
|
1520 |
+
async def do_map(
|
1521 |
+
context: "Context",
|
1522 |
+
value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
|
1523 |
+
*args: t.Any,
|
1524 |
+
**kwargs: t.Any,
|
1525 |
+
) -> t.AsyncIterable[t.Any]:
|
1526 |
+
if value:
|
1527 |
+
func = prepare_map(context, args, kwargs)
|
1528 |
+
|
1529 |
+
async for item in auto_aiter(value):
|
1530 |
+
yield await auto_await(func(item))
|
1531 |
+
|
1532 |
+
|
1533 |
+
@pass_context
|
1534 |
+
def sync_do_select(
|
1535 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
1536 |
+
) -> "t.Iterator[V]":
|
1537 |
+
"""Filters a sequence of objects by applying a test to each object,
|
1538 |
+
and only selecting the objects with the test succeeding.
|
1539 |
+
|
1540 |
+
If no test is specified, each object will be evaluated as a boolean.
|
1541 |
+
|
1542 |
+
Example usage:
|
1543 |
+
|
1544 |
+
.. sourcecode:: jinja
|
1545 |
+
|
1546 |
+
{{ numbers|select("odd") }}
|
1547 |
+
{{ numbers|select("odd") }}
|
1548 |
+
{{ numbers|select("divisibleby", 3) }}
|
1549 |
+
{{ numbers|select("lessthan", 42) }}
|
1550 |
+
{{ strings|select("equalto", "mystring") }}
|
1551 |
+
|
1552 |
+
Similar to a generator comprehension such as:
|
1553 |
+
|
1554 |
+
.. code-block:: python
|
1555 |
+
|
1556 |
+
(n for n in numbers if test_odd(n))
|
1557 |
+
(n for n in numbers if test_divisibleby(n, 3))
|
1558 |
+
|
1559 |
+
.. versionadded:: 2.7
|
1560 |
+
"""
|
1561 |
+
return select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
1562 |
+
|
1563 |
+
|
1564 |
+
@async_variant(sync_do_select) # type: ignore
|
1565 |
+
async def do_select(
|
1566 |
+
context: "Context",
|
1567 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1568 |
+
*args: t.Any,
|
1569 |
+
**kwargs: t.Any,
|
1570 |
+
) -> "t.AsyncIterator[V]":
|
1571 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)
|
1572 |
+
|
1573 |
+
|
1574 |
+
@pass_context
|
1575 |
+
def sync_do_reject(
|
1576 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
1577 |
+
) -> "t.Iterator[V]":
|
1578 |
+
"""Filters a sequence of objects by applying a test to each object,
|
1579 |
+
and rejecting the objects with the test succeeding.
|
1580 |
+
|
1581 |
+
If no test is specified, each object will be evaluated as a boolean.
|
1582 |
+
|
1583 |
+
Example usage:
|
1584 |
+
|
1585 |
+
.. sourcecode:: jinja
|
1586 |
+
|
1587 |
+
{{ numbers|reject("odd") }}
|
1588 |
+
|
1589 |
+
Similar to a generator comprehension such as:
|
1590 |
+
|
1591 |
+
.. code-block:: python
|
1592 |
+
|
1593 |
+
(n for n in numbers if not test_odd(n))
|
1594 |
+
|
1595 |
+
.. versionadded:: 2.7
|
1596 |
+
"""
|
1597 |
+
return select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
1598 |
+
|
1599 |
+
|
1600 |
+
@async_variant(sync_do_reject) # type: ignore
|
1601 |
+
async def do_reject(
|
1602 |
+
context: "Context",
|
1603 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1604 |
+
*args: t.Any,
|
1605 |
+
**kwargs: t.Any,
|
1606 |
+
) -> "t.AsyncIterator[V]":
|
1607 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)
|
1608 |
+
|
1609 |
+
|
1610 |
+
@pass_context
|
1611 |
+
def sync_do_selectattr(
|
1612 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
1613 |
+
) -> "t.Iterator[V]":
|
1614 |
+
"""Filters a sequence of objects by applying a test to the specified
|
1615 |
+
attribute of each object, and only selecting the objects with the
|
1616 |
+
test succeeding.
|
1617 |
+
|
1618 |
+
If no test is specified, the attribute's value will be evaluated as
|
1619 |
+
a boolean.
|
1620 |
+
|
1621 |
+
Example usage:
|
1622 |
+
|
1623 |
+
.. sourcecode:: jinja
|
1624 |
+
|
1625 |
+
{{ users|selectattr("is_active") }}
|
1626 |
+
{{ users|selectattr("email", "none") }}
|
1627 |
+
|
1628 |
+
Similar to a generator comprehension such as:
|
1629 |
+
|
1630 |
+
.. code-block:: python
|
1631 |
+
|
1632 |
+
(u for user in users if user.is_active)
|
1633 |
+
(u for user in users if test_none(user.email))
|
1634 |
+
|
1635 |
+
.. versionadded:: 2.7
|
1636 |
+
"""
|
1637 |
+
return select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
1638 |
+
|
1639 |
+
|
1640 |
+
@async_variant(sync_do_selectattr) # type: ignore
|
1641 |
+
async def do_selectattr(
|
1642 |
+
context: "Context",
|
1643 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1644 |
+
*args: t.Any,
|
1645 |
+
**kwargs: t.Any,
|
1646 |
+
) -> "t.AsyncIterator[V]":
|
1647 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)
|
1648 |
+
|
1649 |
+
|
1650 |
+
@pass_context
|
1651 |
+
def sync_do_rejectattr(
|
1652 |
+
context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any
|
1653 |
+
) -> "t.Iterator[V]":
|
1654 |
+
"""Filters a sequence of objects by applying a test to the specified
|
1655 |
+
attribute of each object, and rejecting the objects with the test
|
1656 |
+
succeeding.
|
1657 |
+
|
1658 |
+
If no test is specified, the attribute's value will be evaluated as
|
1659 |
+
a boolean.
|
1660 |
+
|
1661 |
+
.. sourcecode:: jinja
|
1662 |
+
|
1663 |
+
{{ users|rejectattr("is_active") }}
|
1664 |
+
{{ users|rejectattr("email", "none") }}
|
1665 |
+
|
1666 |
+
Similar to a generator comprehension such as:
|
1667 |
+
|
1668 |
+
.. code-block:: python
|
1669 |
+
|
1670 |
+
(u for user in users if not user.is_active)
|
1671 |
+
(u for user in users if not test_none(user.email))
|
1672 |
+
|
1673 |
+
.. versionadded:: 2.7
|
1674 |
+
"""
|
1675 |
+
return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
1676 |
+
|
1677 |
+
|
1678 |
+
@async_variant(sync_do_rejectattr) # type: ignore
|
1679 |
+
async def do_rejectattr(
|
1680 |
+
context: "Context",
|
1681 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1682 |
+
*args: t.Any,
|
1683 |
+
**kwargs: t.Any,
|
1684 |
+
) -> "t.AsyncIterator[V]":
|
1685 |
+
return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)
|
1686 |
+
|
1687 |
+
|
1688 |
+
@pass_eval_context
|
1689 |
+
def do_tojson(
|
1690 |
+
eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None
|
1691 |
+
) -> Markup:
|
1692 |
+
"""Serialize an object to a string of JSON, and mark it safe to
|
1693 |
+
render in HTML. This filter is only for use in HTML documents.
|
1694 |
+
|
1695 |
+
The returned string is safe to render in HTML documents and
|
1696 |
+
``<script>`` tags. The exception is in HTML attributes that are
|
1697 |
+
double quoted; either use single quotes or the ``|forceescape``
|
1698 |
+
filter.
|
1699 |
+
|
1700 |
+
:param value: The object to serialize to JSON.
|
1701 |
+
:param indent: The ``indent`` parameter passed to ``dumps``, for
|
1702 |
+
pretty-printing the value.
|
1703 |
+
|
1704 |
+
.. versionadded:: 2.9
|
1705 |
+
"""
|
1706 |
+
policies = eval_ctx.environment.policies
|
1707 |
+
dumps = policies["json.dumps_function"]
|
1708 |
+
kwargs = policies["json.dumps_kwargs"]
|
1709 |
+
|
1710 |
+
if indent is not None:
|
1711 |
+
kwargs = kwargs.copy()
|
1712 |
+
kwargs["indent"] = indent
|
1713 |
+
|
1714 |
+
return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)
|
1715 |
+
|
1716 |
+
|
1717 |
+
def prepare_map(
|
1718 |
+
context: "Context", args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]
|
1719 |
+
) -> t.Callable[[t.Any], t.Any]:
|
1720 |
+
if not args and "attribute" in kwargs:
|
1721 |
+
attribute = kwargs.pop("attribute")
|
1722 |
+
default = kwargs.pop("default", None)
|
1723 |
+
|
1724 |
+
if kwargs:
|
1725 |
+
raise FilterArgumentError(
|
1726 |
+
f"Unexpected keyword argument {next(iter(kwargs))!r}"
|
1727 |
+
)
|
1728 |
+
|
1729 |
+
func = make_attrgetter(context.environment, attribute, default=default)
|
1730 |
+
else:
|
1731 |
+
try:
|
1732 |
+
name = args[0]
|
1733 |
+
args = args[1:]
|
1734 |
+
except LookupError:
|
1735 |
+
raise FilterArgumentError("map requires a filter argument") from None
|
1736 |
+
|
1737 |
+
def func(item: t.Any) -> t.Any:
|
1738 |
+
return context.environment.call_filter(
|
1739 |
+
name, item, args, kwargs, context=context
|
1740 |
+
)
|
1741 |
+
|
1742 |
+
return func
|
1743 |
+
|
1744 |
+
|
1745 |
+
def prepare_select_or_reject(
|
1746 |
+
context: "Context",
|
1747 |
+
args: t.Tuple[t.Any, ...],
|
1748 |
+
kwargs: t.Dict[str, t.Any],
|
1749 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
1750 |
+
lookup_attr: bool,
|
1751 |
+
) -> t.Callable[[t.Any], t.Any]:
|
1752 |
+
if lookup_attr:
|
1753 |
+
try:
|
1754 |
+
attr = args[0]
|
1755 |
+
except LookupError:
|
1756 |
+
raise FilterArgumentError("Missing parameter for attribute name") from None
|
1757 |
+
|
1758 |
+
transfunc = make_attrgetter(context.environment, attr)
|
1759 |
+
off = 1
|
1760 |
+
else:
|
1761 |
+
off = 0
|
1762 |
+
|
1763 |
+
def transfunc(x: V) -> V:
|
1764 |
+
return x
|
1765 |
+
|
1766 |
+
try:
|
1767 |
+
name = args[off]
|
1768 |
+
args = args[1 + off :]
|
1769 |
+
|
1770 |
+
def func(item: t.Any) -> t.Any:
|
1771 |
+
return context.environment.call_test(name, item, args, kwargs)
|
1772 |
+
|
1773 |
+
except LookupError:
|
1774 |
+
func = bool # type: ignore
|
1775 |
+
|
1776 |
+
return lambda item: modfunc(func(transfunc(item)))
|
1777 |
+
|
1778 |
+
|
1779 |
+
def select_or_reject(
|
1780 |
+
context: "Context",
|
1781 |
+
value: "t.Iterable[V]",
|
1782 |
+
args: t.Tuple[t.Any, ...],
|
1783 |
+
kwargs: t.Dict[str, t.Any],
|
1784 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
1785 |
+
lookup_attr: bool,
|
1786 |
+
) -> "t.Iterator[V]":
|
1787 |
+
if value:
|
1788 |
+
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
|
1789 |
+
|
1790 |
+
for item in value:
|
1791 |
+
if func(item):
|
1792 |
+
yield item
|
1793 |
+
|
1794 |
+
|
1795 |
+
async def async_select_or_reject(
|
1796 |
+
context: "Context",
|
1797 |
+
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
|
1798 |
+
args: t.Tuple[t.Any, ...],
|
1799 |
+
kwargs: t.Dict[str, t.Any],
|
1800 |
+
modfunc: t.Callable[[t.Any], t.Any],
|
1801 |
+
lookup_attr: bool,
|
1802 |
+
) -> "t.AsyncIterator[V]":
|
1803 |
+
if value:
|
1804 |
+
func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)
|
1805 |
+
|
1806 |
+
async for item in auto_aiter(value):
|
1807 |
+
if func(item):
|
1808 |
+
yield item
|
1809 |
+
|
1810 |
+
|
1811 |
+
FILTERS = {
|
1812 |
+
"abs": abs,
|
1813 |
+
"attr": do_attr,
|
1814 |
+
"batch": do_batch,
|
1815 |
+
"capitalize": do_capitalize,
|
1816 |
+
"center": do_center,
|
1817 |
+
"count": len,
|
1818 |
+
"d": do_default,
|
1819 |
+
"default": do_default,
|
1820 |
+
"dictsort": do_dictsort,
|
1821 |
+
"e": escape,
|
1822 |
+
"escape": escape,
|
1823 |
+
"filesizeformat": do_filesizeformat,
|
1824 |
+
"first": do_first,
|
1825 |
+
"float": do_float,
|
1826 |
+
"forceescape": do_forceescape,
|
1827 |
+
"format": do_format,
|
1828 |
+
"groupby": do_groupby,
|
1829 |
+
"indent": do_indent,
|
1830 |
+
"int": do_int,
|
1831 |
+
"join": do_join,
|
1832 |
+
"last": do_last,
|
1833 |
+
"length": len,
|
1834 |
+
"list": do_list,
|
1835 |
+
"lower": do_lower,
|
1836 |
+
"items": do_items,
|
1837 |
+
"map": do_map,
|
1838 |
+
"min": do_min,
|
1839 |
+
"max": do_max,
|
1840 |
+
"pprint": do_pprint,
|
1841 |
+
"random": do_random,
|
1842 |
+
"reject": do_reject,
|
1843 |
+
"rejectattr": do_rejectattr,
|
1844 |
+
"replace": do_replace,
|
1845 |
+
"reverse": do_reverse,
|
1846 |
+
"round": do_round,
|
1847 |
+
"safe": do_mark_safe,
|
1848 |
+
"select": do_select,
|
1849 |
+
"selectattr": do_selectattr,
|
1850 |
+
"slice": do_slice,
|
1851 |
+
"sort": do_sort,
|
1852 |
+
"string": soft_str,
|
1853 |
+
"striptags": do_striptags,
|
1854 |
+
"sum": do_sum,
|
1855 |
+
"title": do_title,
|
1856 |
+
"trim": do_trim,
|
1857 |
+
"truncate": do_truncate,
|
1858 |
+
"unique": do_unique,
|
1859 |
+
"upper": do_upper,
|
1860 |
+
"urlencode": do_urlencode,
|
1861 |
+
"urlize": do_urlize,
|
1862 |
+
"wordcount": do_wordcount,
|
1863 |
+
"wordwrap": do_wordwrap,
|
1864 |
+
"xmlattr": do_xmlattr,
|
1865 |
+
"tojson": do_tojson,
|
1866 |
+
}
|
llmeval-env/lib/python3.10/site-packages/jinja2/idtracking.py
ADDED
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
VAR_LOAD_PARAMETER = "param"
|
7 |
+
VAR_LOAD_RESOLVE = "resolve"
|
8 |
+
VAR_LOAD_ALIAS = "alias"
|
9 |
+
VAR_LOAD_UNDEFINED = "undefined"
|
10 |
+
|
11 |
+
|
12 |
+
def find_symbols(
|
13 |
+
nodes: t.Iterable[nodes.Node], parent_symbols: t.Optional["Symbols"] = None
|
14 |
+
) -> "Symbols":
|
15 |
+
sym = Symbols(parent=parent_symbols)
|
16 |
+
visitor = FrameSymbolVisitor(sym)
|
17 |
+
for node in nodes:
|
18 |
+
visitor.visit(node)
|
19 |
+
return sym
|
20 |
+
|
21 |
+
|
22 |
+
def symbols_for_node(
|
23 |
+
node: nodes.Node, parent_symbols: t.Optional["Symbols"] = None
|
24 |
+
) -> "Symbols":
|
25 |
+
sym = Symbols(parent=parent_symbols)
|
26 |
+
sym.analyze_node(node)
|
27 |
+
return sym
|
28 |
+
|
29 |
+
|
30 |
+
class Symbols:
|
31 |
+
def __init__(
|
32 |
+
self, parent: t.Optional["Symbols"] = None, level: t.Optional[int] = None
|
33 |
+
) -> None:
|
34 |
+
if level is None:
|
35 |
+
if parent is None:
|
36 |
+
level = 0
|
37 |
+
else:
|
38 |
+
level = parent.level + 1
|
39 |
+
|
40 |
+
self.level: int = level
|
41 |
+
self.parent = parent
|
42 |
+
self.refs: t.Dict[str, str] = {}
|
43 |
+
self.loads: t.Dict[str, t.Any] = {}
|
44 |
+
self.stores: t.Set[str] = set()
|
45 |
+
|
46 |
+
def analyze_node(self, node: nodes.Node, **kwargs: t.Any) -> None:
|
47 |
+
visitor = RootVisitor(self)
|
48 |
+
visitor.visit(node, **kwargs)
|
49 |
+
|
50 |
+
def _define_ref(
|
51 |
+
self, name: str, load: t.Optional[t.Tuple[str, t.Optional[str]]] = None
|
52 |
+
) -> str:
|
53 |
+
ident = f"l_{self.level}_{name}"
|
54 |
+
self.refs[name] = ident
|
55 |
+
if load is not None:
|
56 |
+
self.loads[ident] = load
|
57 |
+
return ident
|
58 |
+
|
59 |
+
def find_load(self, target: str) -> t.Optional[t.Any]:
|
60 |
+
if target in self.loads:
|
61 |
+
return self.loads[target]
|
62 |
+
|
63 |
+
if self.parent is not None:
|
64 |
+
return self.parent.find_load(target)
|
65 |
+
|
66 |
+
return None
|
67 |
+
|
68 |
+
def find_ref(self, name: str) -> t.Optional[str]:
|
69 |
+
if name in self.refs:
|
70 |
+
return self.refs[name]
|
71 |
+
|
72 |
+
if self.parent is not None:
|
73 |
+
return self.parent.find_ref(name)
|
74 |
+
|
75 |
+
return None
|
76 |
+
|
77 |
+
def ref(self, name: str) -> str:
|
78 |
+
rv = self.find_ref(name)
|
79 |
+
if rv is None:
|
80 |
+
raise AssertionError(
|
81 |
+
"Tried to resolve a name to a reference that was"
|
82 |
+
f" unknown to the frame ({name!r})"
|
83 |
+
)
|
84 |
+
return rv
|
85 |
+
|
86 |
+
def copy(self) -> "Symbols":
|
87 |
+
rv = object.__new__(self.__class__)
|
88 |
+
rv.__dict__.update(self.__dict__)
|
89 |
+
rv.refs = self.refs.copy()
|
90 |
+
rv.loads = self.loads.copy()
|
91 |
+
rv.stores = self.stores.copy()
|
92 |
+
return rv
|
93 |
+
|
94 |
+
def store(self, name: str) -> None:
|
95 |
+
self.stores.add(name)
|
96 |
+
|
97 |
+
# If we have not see the name referenced yet, we need to figure
|
98 |
+
# out what to set it to.
|
99 |
+
if name not in self.refs:
|
100 |
+
# If there is a parent scope we check if the name has a
|
101 |
+
# reference there. If it does it means we might have to alias
|
102 |
+
# to a variable there.
|
103 |
+
if self.parent is not None:
|
104 |
+
outer_ref = self.parent.find_ref(name)
|
105 |
+
if outer_ref is not None:
|
106 |
+
self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))
|
107 |
+
return
|
108 |
+
|
109 |
+
# Otherwise we can just set it to undefined.
|
110 |
+
self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))
|
111 |
+
|
112 |
+
def declare_parameter(self, name: str) -> str:
|
113 |
+
self.stores.add(name)
|
114 |
+
return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))
|
115 |
+
|
116 |
+
def load(self, name: str) -> None:
|
117 |
+
if self.find_ref(name) is None:
|
118 |
+
self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))
|
119 |
+
|
120 |
+
def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:
|
121 |
+
stores: t.Dict[str, int] = {}
|
122 |
+
for branch in branch_symbols:
|
123 |
+
for target in branch.stores:
|
124 |
+
if target in self.stores:
|
125 |
+
continue
|
126 |
+
stores[target] = stores.get(target, 0) + 1
|
127 |
+
|
128 |
+
for sym in branch_symbols:
|
129 |
+
self.refs.update(sym.refs)
|
130 |
+
self.loads.update(sym.loads)
|
131 |
+
self.stores.update(sym.stores)
|
132 |
+
|
133 |
+
for name, branch_count in stores.items():
|
134 |
+
if branch_count == len(branch_symbols):
|
135 |
+
continue
|
136 |
+
|
137 |
+
target = self.find_ref(name) # type: ignore
|
138 |
+
assert target is not None, "should not happen"
|
139 |
+
|
140 |
+
if self.parent is not None:
|
141 |
+
outer_target = self.parent.find_ref(name)
|
142 |
+
if outer_target is not None:
|
143 |
+
self.loads[target] = (VAR_LOAD_ALIAS, outer_target)
|
144 |
+
continue
|
145 |
+
self.loads[target] = (VAR_LOAD_RESOLVE, name)
|
146 |
+
|
147 |
+
def dump_stores(self) -> t.Dict[str, str]:
|
148 |
+
rv: t.Dict[str, str] = {}
|
149 |
+
node: t.Optional["Symbols"] = self
|
150 |
+
|
151 |
+
while node is not None:
|
152 |
+
for name in sorted(node.stores):
|
153 |
+
if name not in rv:
|
154 |
+
rv[name] = self.find_ref(name) # type: ignore
|
155 |
+
|
156 |
+
node = node.parent
|
157 |
+
|
158 |
+
return rv
|
159 |
+
|
160 |
+
def dump_param_targets(self) -> t.Set[str]:
|
161 |
+
rv = set()
|
162 |
+
node: t.Optional["Symbols"] = self
|
163 |
+
|
164 |
+
while node is not None:
|
165 |
+
for target, (instr, _) in self.loads.items():
|
166 |
+
if instr == VAR_LOAD_PARAMETER:
|
167 |
+
rv.add(target)
|
168 |
+
|
169 |
+
node = node.parent
|
170 |
+
|
171 |
+
return rv
|
172 |
+
|
173 |
+
|
174 |
+
class RootVisitor(NodeVisitor):
|
175 |
+
def __init__(self, symbols: "Symbols") -> None:
|
176 |
+
self.sym_visitor = FrameSymbolVisitor(symbols)
|
177 |
+
|
178 |
+
def _simple_visit(self, node: nodes.Node, **kwargs: t.Any) -> None:
|
179 |
+
for child in node.iter_child_nodes():
|
180 |
+
self.sym_visitor.visit(child)
|
181 |
+
|
182 |
+
visit_Template = _simple_visit
|
183 |
+
visit_Block = _simple_visit
|
184 |
+
visit_Macro = _simple_visit
|
185 |
+
visit_FilterBlock = _simple_visit
|
186 |
+
visit_Scope = _simple_visit
|
187 |
+
visit_If = _simple_visit
|
188 |
+
visit_ScopedEvalContextModifier = _simple_visit
|
189 |
+
|
190 |
+
def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:
|
191 |
+
for child in node.body:
|
192 |
+
self.sym_visitor.visit(child)
|
193 |
+
|
194 |
+
def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:
|
195 |
+
for child in node.iter_child_nodes(exclude=("call",)):
|
196 |
+
self.sym_visitor.visit(child)
|
197 |
+
|
198 |
+
def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:
|
199 |
+
for child in node.body:
|
200 |
+
self.sym_visitor.visit(child)
|
201 |
+
|
202 |
+
def visit_For(
|
203 |
+
self, node: nodes.For, for_branch: str = "body", **kwargs: t.Any
|
204 |
+
) -> None:
|
205 |
+
if for_branch == "body":
|
206 |
+
self.sym_visitor.visit(node.target, store_as_param=True)
|
207 |
+
branch = node.body
|
208 |
+
elif for_branch == "else":
|
209 |
+
branch = node.else_
|
210 |
+
elif for_branch == "test":
|
211 |
+
self.sym_visitor.visit(node.target, store_as_param=True)
|
212 |
+
if node.test is not None:
|
213 |
+
self.sym_visitor.visit(node.test)
|
214 |
+
return
|
215 |
+
else:
|
216 |
+
raise RuntimeError("Unknown for branch")
|
217 |
+
|
218 |
+
if branch:
|
219 |
+
for item in branch:
|
220 |
+
self.sym_visitor.visit(item)
|
221 |
+
|
222 |
+
def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:
|
223 |
+
for target in node.targets:
|
224 |
+
self.sym_visitor.visit(target)
|
225 |
+
for child in node.body:
|
226 |
+
self.sym_visitor.visit(child)
|
227 |
+
|
228 |
+
def generic_visit(self, node: nodes.Node, *args: t.Any, **kwargs: t.Any) -> None:
|
229 |
+
raise NotImplementedError(f"Cannot find symbols for {type(node).__name__!r}")
|
230 |
+
|
231 |
+
|
232 |
+
class FrameSymbolVisitor(NodeVisitor):
|
233 |
+
"""A visitor for `Frame.inspect`."""
|
234 |
+
|
235 |
+
def __init__(self, symbols: "Symbols") -> None:
|
236 |
+
self.symbols = symbols
|
237 |
+
|
238 |
+
def visit_Name(
|
239 |
+
self, node: nodes.Name, store_as_param: bool = False, **kwargs: t.Any
|
240 |
+
) -> None:
|
241 |
+
"""All assignments to names go through this function."""
|
242 |
+
if store_as_param or node.ctx == "param":
|
243 |
+
self.symbols.declare_parameter(node.name)
|
244 |
+
elif node.ctx == "store":
|
245 |
+
self.symbols.store(node.name)
|
246 |
+
elif node.ctx == "load":
|
247 |
+
self.symbols.load(node.name)
|
248 |
+
|
249 |
+
def visit_NSRef(self, node: nodes.NSRef, **kwargs: t.Any) -> None:
|
250 |
+
self.symbols.load(node.name)
|
251 |
+
|
252 |
+
def visit_If(self, node: nodes.If, **kwargs: t.Any) -> None:
|
253 |
+
self.visit(node.test, **kwargs)
|
254 |
+
original_symbols = self.symbols
|
255 |
+
|
256 |
+
def inner_visit(nodes: t.Iterable[nodes.Node]) -> "Symbols":
|
257 |
+
self.symbols = rv = original_symbols.copy()
|
258 |
+
|
259 |
+
for subnode in nodes:
|
260 |
+
self.visit(subnode, **kwargs)
|
261 |
+
|
262 |
+
self.symbols = original_symbols
|
263 |
+
return rv
|
264 |
+
|
265 |
+
body_symbols = inner_visit(node.body)
|
266 |
+
elif_symbols = inner_visit(node.elif_)
|
267 |
+
else_symbols = inner_visit(node.else_ or ())
|
268 |
+
self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])
|
269 |
+
|
270 |
+
def visit_Macro(self, node: nodes.Macro, **kwargs: t.Any) -> None:
|
271 |
+
self.symbols.store(node.name)
|
272 |
+
|
273 |
+
def visit_Import(self, node: nodes.Import, **kwargs: t.Any) -> None:
|
274 |
+
self.generic_visit(node, **kwargs)
|
275 |
+
self.symbols.store(node.target)
|
276 |
+
|
277 |
+
def visit_FromImport(self, node: nodes.FromImport, **kwargs: t.Any) -> None:
|
278 |
+
self.generic_visit(node, **kwargs)
|
279 |
+
|
280 |
+
for name in node.names:
|
281 |
+
if isinstance(name, tuple):
|
282 |
+
self.symbols.store(name[1])
|
283 |
+
else:
|
284 |
+
self.symbols.store(name)
|
285 |
+
|
286 |
+
def visit_Assign(self, node: nodes.Assign, **kwargs: t.Any) -> None:
|
287 |
+
"""Visit assignments in the correct order."""
|
288 |
+
self.visit(node.node, **kwargs)
|
289 |
+
self.visit(node.target, **kwargs)
|
290 |
+
|
291 |
+
def visit_For(self, node: nodes.For, **kwargs: t.Any) -> None:
|
292 |
+
"""Visiting stops at for blocks. However the block sequence
|
293 |
+
is visited as part of the outer scope.
|
294 |
+
"""
|
295 |
+
self.visit(node.iter, **kwargs)
|
296 |
+
|
297 |
+
def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:
|
298 |
+
self.visit(node.call, **kwargs)
|
299 |
+
|
300 |
+
def visit_FilterBlock(self, node: nodes.FilterBlock, **kwargs: t.Any) -> None:
|
301 |
+
self.visit(node.filter, **kwargs)
|
302 |
+
|
303 |
+
def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:
|
304 |
+
for target in node.values:
|
305 |
+
self.visit(target)
|
306 |
+
|
307 |
+
def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:
|
308 |
+
"""Stop visiting at block assigns."""
|
309 |
+
self.visit(node.target, **kwargs)
|
310 |
+
|
311 |
+
def visit_Scope(self, node: nodes.Scope, **kwargs: t.Any) -> None:
|
312 |
+
"""Stop visiting at scopes."""
|
313 |
+
|
314 |
+
def visit_Block(self, node: nodes.Block, **kwargs: t.Any) -> None:
|
315 |
+
"""Stop visiting at blocks."""
|
316 |
+
|
317 |
+
def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:
|
318 |
+
"""Do not visit into overlay scopes."""
|
llmeval-env/lib/python3.10/site-packages/jinja2/loaders.py
ADDED
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"""
|
4 |
+
|
5 |
+
import importlib.util
|
6 |
+
import os
|
7 |
+
import posixpath
|
8 |
+
import sys
|
9 |
+
import typing as t
|
10 |
+
import weakref
|
11 |
+
import zipimport
|
12 |
+
from collections import abc
|
13 |
+
from hashlib import sha1
|
14 |
+
from importlib import import_module
|
15 |
+
from types import ModuleType
|
16 |
+
|
17 |
+
from .exceptions import TemplateNotFound
|
18 |
+
from .utils import internalcode
|
19 |
+
|
20 |
+
if t.TYPE_CHECKING:
|
21 |
+
from .environment import Environment
|
22 |
+
from .environment import Template
|
23 |
+
|
24 |
+
|
25 |
+
def split_template_path(template: str) -> t.List[str]:
|
26 |
+
"""Split a path into segments and perform a sanity check. If it detects
|
27 |
+
'..' in the path it will raise a `TemplateNotFound` error.
|
28 |
+
"""
|
29 |
+
pieces = []
|
30 |
+
for piece in template.split("/"):
|
31 |
+
if (
|
32 |
+
os.path.sep in piece
|
33 |
+
or (os.path.altsep and os.path.altsep in piece)
|
34 |
+
or piece == os.path.pardir
|
35 |
+
):
|
36 |
+
raise TemplateNotFound(template)
|
37 |
+
elif piece and piece != ".":
|
38 |
+
pieces.append(piece)
|
39 |
+
return pieces
|
40 |
+
|
41 |
+
|
42 |
+
class BaseLoader:
|
43 |
+
"""Baseclass for all loaders. Subclass this and override `get_source` to
|
44 |
+
implement a custom loading mechanism. The environment provides a
|
45 |
+
`get_template` method that calls the loader's `load` method to get the
|
46 |
+
:class:`Template` object.
|
47 |
+
|
48 |
+
A very basic example for a loader that looks up templates on the file
|
49 |
+
system could look like this::
|
50 |
+
|
51 |
+
from jinja2 import BaseLoader, TemplateNotFound
|
52 |
+
from os.path import join, exists, getmtime
|
53 |
+
|
54 |
+
class MyLoader(BaseLoader):
|
55 |
+
|
56 |
+
def __init__(self, path):
|
57 |
+
self.path = path
|
58 |
+
|
59 |
+
def get_source(self, environment, template):
|
60 |
+
path = join(self.path, template)
|
61 |
+
if not exists(path):
|
62 |
+
raise TemplateNotFound(template)
|
63 |
+
mtime = getmtime(path)
|
64 |
+
with open(path) as f:
|
65 |
+
source = f.read()
|
66 |
+
return source, path, lambda: mtime == getmtime(path)
|
67 |
+
"""
|
68 |
+
|
69 |
+
#: if set to `False` it indicates that the loader cannot provide access
|
70 |
+
#: to the source of templates.
|
71 |
+
#:
|
72 |
+
#: .. versionadded:: 2.4
|
73 |
+
has_source_access = True
|
74 |
+
|
75 |
+
def get_source(
|
76 |
+
self, environment: "Environment", template: str
|
77 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
78 |
+
"""Get the template source, filename and reload helper for a template.
|
79 |
+
It's passed the environment and template name and has to return a
|
80 |
+
tuple in the form ``(source, filename, uptodate)`` or raise a
|
81 |
+
`TemplateNotFound` error if it can't locate the template.
|
82 |
+
|
83 |
+
The source part of the returned tuple must be the source of the
|
84 |
+
template as a string. The filename should be the name of the
|
85 |
+
file on the filesystem if it was loaded from there, otherwise
|
86 |
+
``None``. The filename is used by Python for the tracebacks
|
87 |
+
if no loader extension is used.
|
88 |
+
|
89 |
+
The last item in the tuple is the `uptodate` function. If auto
|
90 |
+
reloading is enabled it's always called to check if the template
|
91 |
+
changed. No arguments are passed so the function must store the
|
92 |
+
old state somewhere (for example in a closure). If it returns `False`
|
93 |
+
the template will be reloaded.
|
94 |
+
"""
|
95 |
+
if not self.has_source_access:
|
96 |
+
raise RuntimeError(
|
97 |
+
f"{type(self).__name__} cannot provide access to the source"
|
98 |
+
)
|
99 |
+
raise TemplateNotFound(template)
|
100 |
+
|
101 |
+
def list_templates(self) -> t.List[str]:
|
102 |
+
"""Iterates over all templates. If the loader does not support that
|
103 |
+
it should raise a :exc:`TypeError` which is the default behavior.
|
104 |
+
"""
|
105 |
+
raise TypeError("this loader cannot iterate over all templates")
|
106 |
+
|
107 |
+
@internalcode
|
108 |
+
def load(
|
109 |
+
self,
|
110 |
+
environment: "Environment",
|
111 |
+
name: str,
|
112 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
113 |
+
) -> "Template":
|
114 |
+
"""Loads a template. This method looks up the template in the cache
|
115 |
+
or loads one by calling :meth:`get_source`. Subclasses should not
|
116 |
+
override this method as loaders working on collections of other
|
117 |
+
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
|
118 |
+
will not call this method but `get_source` directly.
|
119 |
+
"""
|
120 |
+
code = None
|
121 |
+
if globals is None:
|
122 |
+
globals = {}
|
123 |
+
|
124 |
+
# first we try to get the source for this template together
|
125 |
+
# with the filename and the uptodate function.
|
126 |
+
source, filename, uptodate = self.get_source(environment, name)
|
127 |
+
|
128 |
+
# try to load the code from the bytecode cache if there is a
|
129 |
+
# bytecode cache configured.
|
130 |
+
bcc = environment.bytecode_cache
|
131 |
+
if bcc is not None:
|
132 |
+
bucket = bcc.get_bucket(environment, name, filename, source)
|
133 |
+
code = bucket.code
|
134 |
+
|
135 |
+
# if we don't have code so far (not cached, no longer up to
|
136 |
+
# date) etc. we compile the template
|
137 |
+
if code is None:
|
138 |
+
code = environment.compile(source, name, filename)
|
139 |
+
|
140 |
+
# if the bytecode cache is available and the bucket doesn't
|
141 |
+
# have a code so far, we give the bucket the new code and put
|
142 |
+
# it back to the bytecode cache.
|
143 |
+
if bcc is not None and bucket.code is None:
|
144 |
+
bucket.code = code
|
145 |
+
bcc.set_bucket(bucket)
|
146 |
+
|
147 |
+
return environment.template_class.from_code(
|
148 |
+
environment, code, globals, uptodate
|
149 |
+
)
|
150 |
+
|
151 |
+
|
152 |
+
class FileSystemLoader(BaseLoader):
|
153 |
+
"""Load templates from a directory in the file system.
|
154 |
+
|
155 |
+
The path can be relative or absolute. Relative paths are relative to
|
156 |
+
the current working directory.
|
157 |
+
|
158 |
+
.. code-block:: python
|
159 |
+
|
160 |
+
loader = FileSystemLoader("templates")
|
161 |
+
|
162 |
+
A list of paths can be given. The directories will be searched in
|
163 |
+
order, stopping at the first matching template.
|
164 |
+
|
165 |
+
.. code-block:: python
|
166 |
+
|
167 |
+
loader = FileSystemLoader(["/override/templates", "/default/templates"])
|
168 |
+
|
169 |
+
:param searchpath: A path, or list of paths, to the directory that
|
170 |
+
contains the templates.
|
171 |
+
:param encoding: Use this encoding to read the text from template
|
172 |
+
files.
|
173 |
+
:param followlinks: Follow symbolic links in the path.
|
174 |
+
|
175 |
+
.. versionchanged:: 2.8
|
176 |
+
Added the ``followlinks`` parameter.
|
177 |
+
"""
|
178 |
+
|
179 |
+
def __init__(
|
180 |
+
self,
|
181 |
+
searchpath: t.Union[
|
182 |
+
str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
|
183 |
+
],
|
184 |
+
encoding: str = "utf-8",
|
185 |
+
followlinks: bool = False,
|
186 |
+
) -> None:
|
187 |
+
if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
|
188 |
+
searchpath = [searchpath]
|
189 |
+
|
190 |
+
self.searchpath = [os.fspath(p) for p in searchpath]
|
191 |
+
self.encoding = encoding
|
192 |
+
self.followlinks = followlinks
|
193 |
+
|
194 |
+
def get_source(
|
195 |
+
self, environment: "Environment", template: str
|
196 |
+
) -> t.Tuple[str, str, t.Callable[[], bool]]:
|
197 |
+
pieces = split_template_path(template)
|
198 |
+
|
199 |
+
for searchpath in self.searchpath:
|
200 |
+
# Use posixpath even on Windows to avoid "drive:" or UNC
|
201 |
+
# segments breaking out of the search directory.
|
202 |
+
filename = posixpath.join(searchpath, *pieces)
|
203 |
+
|
204 |
+
if os.path.isfile(filename):
|
205 |
+
break
|
206 |
+
else:
|
207 |
+
raise TemplateNotFound(template)
|
208 |
+
|
209 |
+
with open(filename, encoding=self.encoding) as f:
|
210 |
+
contents = f.read()
|
211 |
+
|
212 |
+
mtime = os.path.getmtime(filename)
|
213 |
+
|
214 |
+
def uptodate() -> bool:
|
215 |
+
try:
|
216 |
+
return os.path.getmtime(filename) == mtime
|
217 |
+
except OSError:
|
218 |
+
return False
|
219 |
+
|
220 |
+
# Use normpath to convert Windows altsep to sep.
|
221 |
+
return contents, os.path.normpath(filename), uptodate
|
222 |
+
|
223 |
+
def list_templates(self) -> t.List[str]:
|
224 |
+
found = set()
|
225 |
+
for searchpath in self.searchpath:
|
226 |
+
walk_dir = os.walk(searchpath, followlinks=self.followlinks)
|
227 |
+
for dirpath, _, filenames in walk_dir:
|
228 |
+
for filename in filenames:
|
229 |
+
template = (
|
230 |
+
os.path.join(dirpath, filename)[len(searchpath) :]
|
231 |
+
.strip(os.path.sep)
|
232 |
+
.replace(os.path.sep, "/")
|
233 |
+
)
|
234 |
+
if template[:2] == "./":
|
235 |
+
template = template[2:]
|
236 |
+
if template not in found:
|
237 |
+
found.add(template)
|
238 |
+
return sorted(found)
|
239 |
+
|
240 |
+
|
241 |
+
class PackageLoader(BaseLoader):
|
242 |
+
"""Load templates from a directory in a Python package.
|
243 |
+
|
244 |
+
:param package_name: Import name of the package that contains the
|
245 |
+
template directory.
|
246 |
+
:param package_path: Directory within the imported package that
|
247 |
+
contains the templates.
|
248 |
+
:param encoding: Encoding of template files.
|
249 |
+
|
250 |
+
The following example looks up templates in the ``pages`` directory
|
251 |
+
within the ``project.ui`` package.
|
252 |
+
|
253 |
+
.. code-block:: python
|
254 |
+
|
255 |
+
loader = PackageLoader("project.ui", "pages")
|
256 |
+
|
257 |
+
Only packages installed as directories (standard pip behavior) or
|
258 |
+
zip/egg files (less common) are supported. The Python API for
|
259 |
+
introspecting data in packages is too limited to support other
|
260 |
+
installation methods the way this loader requires.
|
261 |
+
|
262 |
+
There is limited support for :pep:`420` namespace packages. The
|
263 |
+
template directory is assumed to only be in one namespace
|
264 |
+
contributor. Zip files contributing to a namespace are not
|
265 |
+
supported.
|
266 |
+
|
267 |
+
.. versionchanged:: 3.0
|
268 |
+
No longer uses ``setuptools`` as a dependency.
|
269 |
+
|
270 |
+
.. versionchanged:: 3.0
|
271 |
+
Limited PEP 420 namespace package support.
|
272 |
+
"""
|
273 |
+
|
274 |
+
def __init__(
|
275 |
+
self,
|
276 |
+
package_name: str,
|
277 |
+
package_path: "str" = "templates",
|
278 |
+
encoding: str = "utf-8",
|
279 |
+
) -> None:
|
280 |
+
package_path = os.path.normpath(package_path).rstrip(os.path.sep)
|
281 |
+
|
282 |
+
# normpath preserves ".", which isn't valid in zip paths.
|
283 |
+
if package_path == os.path.curdir:
|
284 |
+
package_path = ""
|
285 |
+
elif package_path[:2] == os.path.curdir + os.path.sep:
|
286 |
+
package_path = package_path[2:]
|
287 |
+
|
288 |
+
self.package_path = package_path
|
289 |
+
self.package_name = package_name
|
290 |
+
self.encoding = encoding
|
291 |
+
|
292 |
+
# Make sure the package exists. This also makes namespace
|
293 |
+
# packages work, otherwise get_loader returns None.
|
294 |
+
import_module(package_name)
|
295 |
+
spec = importlib.util.find_spec(package_name)
|
296 |
+
assert spec is not None, "An import spec was not found for the package."
|
297 |
+
loader = spec.loader
|
298 |
+
assert loader is not None, "A loader was not found for the package."
|
299 |
+
self._loader = loader
|
300 |
+
self._archive = None
|
301 |
+
template_root = None
|
302 |
+
|
303 |
+
if isinstance(loader, zipimport.zipimporter):
|
304 |
+
self._archive = loader.archive
|
305 |
+
pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
|
306 |
+
template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
|
307 |
+
else:
|
308 |
+
roots: t.List[str] = []
|
309 |
+
|
310 |
+
# One element for regular packages, multiple for namespace
|
311 |
+
# packages, or None for single module file.
|
312 |
+
if spec.submodule_search_locations:
|
313 |
+
roots.extend(spec.submodule_search_locations)
|
314 |
+
# A single module file, use the parent directory instead.
|
315 |
+
elif spec.origin is not None:
|
316 |
+
roots.append(os.path.dirname(spec.origin))
|
317 |
+
|
318 |
+
for root in roots:
|
319 |
+
root = os.path.join(root, package_path)
|
320 |
+
|
321 |
+
if os.path.isdir(root):
|
322 |
+
template_root = root
|
323 |
+
break
|
324 |
+
|
325 |
+
if template_root is None:
|
326 |
+
raise ValueError(
|
327 |
+
f"The {package_name!r} package was not installed in a"
|
328 |
+
" way that PackageLoader understands."
|
329 |
+
)
|
330 |
+
|
331 |
+
self._template_root = template_root
|
332 |
+
|
333 |
+
def get_source(
|
334 |
+
self, environment: "Environment", template: str
|
335 |
+
) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
|
336 |
+
# Use posixpath even on Windows to avoid "drive:" or UNC
|
337 |
+
# segments breaking out of the search directory. Use normpath to
|
338 |
+
# convert Windows altsep to sep.
|
339 |
+
p = os.path.normpath(
|
340 |
+
posixpath.join(self._template_root, *split_template_path(template))
|
341 |
+
)
|
342 |
+
up_to_date: t.Optional[t.Callable[[], bool]]
|
343 |
+
|
344 |
+
if self._archive is None:
|
345 |
+
# Package is a directory.
|
346 |
+
if not os.path.isfile(p):
|
347 |
+
raise TemplateNotFound(template)
|
348 |
+
|
349 |
+
with open(p, "rb") as f:
|
350 |
+
source = f.read()
|
351 |
+
|
352 |
+
mtime = os.path.getmtime(p)
|
353 |
+
|
354 |
+
def up_to_date() -> bool:
|
355 |
+
return os.path.isfile(p) and os.path.getmtime(p) == mtime
|
356 |
+
|
357 |
+
else:
|
358 |
+
# Package is a zip file.
|
359 |
+
try:
|
360 |
+
source = self._loader.get_data(p) # type: ignore
|
361 |
+
except OSError as e:
|
362 |
+
raise TemplateNotFound(template) from e
|
363 |
+
|
364 |
+
# Could use the zip's mtime for all template mtimes, but
|
365 |
+
# would need to safely reload the module if it's out of
|
366 |
+
# date, so just report it as always current.
|
367 |
+
up_to_date = None
|
368 |
+
|
369 |
+
return source.decode(self.encoding), p, up_to_date
|
370 |
+
|
371 |
+
def list_templates(self) -> t.List[str]:
|
372 |
+
results: t.List[str] = []
|
373 |
+
|
374 |
+
if self._archive is None:
|
375 |
+
# Package is a directory.
|
376 |
+
offset = len(self._template_root)
|
377 |
+
|
378 |
+
for dirpath, _, filenames in os.walk(self._template_root):
|
379 |
+
dirpath = dirpath[offset:].lstrip(os.path.sep)
|
380 |
+
results.extend(
|
381 |
+
os.path.join(dirpath, name).replace(os.path.sep, "/")
|
382 |
+
for name in filenames
|
383 |
+
)
|
384 |
+
else:
|
385 |
+
if not hasattr(self._loader, "_files"):
|
386 |
+
raise TypeError(
|
387 |
+
"This zip import does not have the required"
|
388 |
+
" metadata to list templates."
|
389 |
+
)
|
390 |
+
|
391 |
+
# Package is a zip file.
|
392 |
+
prefix = (
|
393 |
+
self._template_root[len(self._archive) :].lstrip(os.path.sep)
|
394 |
+
+ os.path.sep
|
395 |
+
)
|
396 |
+
offset = len(prefix)
|
397 |
+
|
398 |
+
for name in self._loader._files.keys():
|
399 |
+
# Find names under the templates directory that aren't directories.
|
400 |
+
if name.startswith(prefix) and name[-1] != os.path.sep:
|
401 |
+
results.append(name[offset:].replace(os.path.sep, "/"))
|
402 |
+
|
403 |
+
results.sort()
|
404 |
+
return results
|
405 |
+
|
406 |
+
|
407 |
+
class DictLoader(BaseLoader):
|
408 |
+
"""Loads a template from a Python dict mapping template names to
|
409 |
+
template source. This loader is useful for unittesting:
|
410 |
+
|
411 |
+
>>> loader = DictLoader({'index.html': 'source here'})
|
412 |
+
|
413 |
+
Because auto reloading is rarely useful this is disabled per default.
|
414 |
+
"""
|
415 |
+
|
416 |
+
def __init__(self, mapping: t.Mapping[str, str]) -> None:
|
417 |
+
self.mapping = mapping
|
418 |
+
|
419 |
+
def get_source(
|
420 |
+
self, environment: "Environment", template: str
|
421 |
+
) -> t.Tuple[str, None, t.Callable[[], bool]]:
|
422 |
+
if template in self.mapping:
|
423 |
+
source = self.mapping[template]
|
424 |
+
return source, None, lambda: source == self.mapping.get(template)
|
425 |
+
raise TemplateNotFound(template)
|
426 |
+
|
427 |
+
def list_templates(self) -> t.List[str]:
|
428 |
+
return sorted(self.mapping)
|
429 |
+
|
430 |
+
|
431 |
+
class FunctionLoader(BaseLoader):
|
432 |
+
"""A loader that is passed a function which does the loading. The
|
433 |
+
function receives the name of the template and has to return either
|
434 |
+
a string with the template source, a tuple in the form ``(source,
|
435 |
+
filename, uptodatefunc)`` or `None` if the template does not exist.
|
436 |
+
|
437 |
+
>>> def load_template(name):
|
438 |
+
... if name == 'index.html':
|
439 |
+
... return '...'
|
440 |
+
...
|
441 |
+
>>> loader = FunctionLoader(load_template)
|
442 |
+
|
443 |
+
The `uptodatefunc` is a function that is called if autoreload is enabled
|
444 |
+
and has to return `True` if the template is still up to date. For more
|
445 |
+
details have a look at :meth:`BaseLoader.get_source` which has the same
|
446 |
+
return value.
|
447 |
+
"""
|
448 |
+
|
449 |
+
def __init__(
|
450 |
+
self,
|
451 |
+
load_func: t.Callable[
|
452 |
+
[str],
|
453 |
+
t.Optional[
|
454 |
+
t.Union[
|
455 |
+
str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
|
456 |
+
]
|
457 |
+
],
|
458 |
+
],
|
459 |
+
) -> None:
|
460 |
+
self.load_func = load_func
|
461 |
+
|
462 |
+
def get_source(
|
463 |
+
self, environment: "Environment", template: str
|
464 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
465 |
+
rv = self.load_func(template)
|
466 |
+
|
467 |
+
if rv is None:
|
468 |
+
raise TemplateNotFound(template)
|
469 |
+
|
470 |
+
if isinstance(rv, str):
|
471 |
+
return rv, None, None
|
472 |
+
|
473 |
+
return rv
|
474 |
+
|
475 |
+
|
476 |
+
class PrefixLoader(BaseLoader):
|
477 |
+
"""A loader that is passed a dict of loaders where each loader is bound
|
478 |
+
to a prefix. The prefix is delimited from the template by a slash per
|
479 |
+
default, which can be changed by setting the `delimiter` argument to
|
480 |
+
something else::
|
481 |
+
|
482 |
+
loader = PrefixLoader({
|
483 |
+
'app1': PackageLoader('mypackage.app1'),
|
484 |
+
'app2': PackageLoader('mypackage.app2')
|
485 |
+
})
|
486 |
+
|
487 |
+
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
|
488 |
+
by loading ``'app2/index.html'`` the file from the second.
|
489 |
+
"""
|
490 |
+
|
491 |
+
def __init__(
|
492 |
+
self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
|
493 |
+
) -> None:
|
494 |
+
self.mapping = mapping
|
495 |
+
self.delimiter = delimiter
|
496 |
+
|
497 |
+
def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
|
498 |
+
try:
|
499 |
+
prefix, name = template.split(self.delimiter, 1)
|
500 |
+
loader = self.mapping[prefix]
|
501 |
+
except (ValueError, KeyError) as e:
|
502 |
+
raise TemplateNotFound(template) from e
|
503 |
+
return loader, name
|
504 |
+
|
505 |
+
def get_source(
|
506 |
+
self, environment: "Environment", template: str
|
507 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
508 |
+
loader, name = self.get_loader(template)
|
509 |
+
try:
|
510 |
+
return loader.get_source(environment, name)
|
511 |
+
except TemplateNotFound as e:
|
512 |
+
# re-raise the exception with the correct filename here.
|
513 |
+
# (the one that includes the prefix)
|
514 |
+
raise TemplateNotFound(template) from e
|
515 |
+
|
516 |
+
@internalcode
|
517 |
+
def load(
|
518 |
+
self,
|
519 |
+
environment: "Environment",
|
520 |
+
name: str,
|
521 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
522 |
+
) -> "Template":
|
523 |
+
loader, local_name = self.get_loader(name)
|
524 |
+
try:
|
525 |
+
return loader.load(environment, local_name, globals)
|
526 |
+
except TemplateNotFound as e:
|
527 |
+
# re-raise the exception with the correct filename here.
|
528 |
+
# (the one that includes the prefix)
|
529 |
+
raise TemplateNotFound(name) from e
|
530 |
+
|
531 |
+
def list_templates(self) -> t.List[str]:
|
532 |
+
result = []
|
533 |
+
for prefix, loader in self.mapping.items():
|
534 |
+
for template in loader.list_templates():
|
535 |
+
result.append(prefix + self.delimiter + template)
|
536 |
+
return result
|
537 |
+
|
538 |
+
|
539 |
+
class ChoiceLoader(BaseLoader):
|
540 |
+
"""This loader works like the `PrefixLoader` just that no prefix is
|
541 |
+
specified. If a template could not be found by one loader the next one
|
542 |
+
is tried.
|
543 |
+
|
544 |
+
>>> loader = ChoiceLoader([
|
545 |
+
... FileSystemLoader('/path/to/user/templates'),
|
546 |
+
... FileSystemLoader('/path/to/system/templates')
|
547 |
+
... ])
|
548 |
+
|
549 |
+
This is useful if you want to allow users to override builtin templates
|
550 |
+
from a different location.
|
551 |
+
"""
|
552 |
+
|
553 |
+
def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
|
554 |
+
self.loaders = loaders
|
555 |
+
|
556 |
+
def get_source(
|
557 |
+
self, environment: "Environment", template: str
|
558 |
+
) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
|
559 |
+
for loader in self.loaders:
|
560 |
+
try:
|
561 |
+
return loader.get_source(environment, template)
|
562 |
+
except TemplateNotFound:
|
563 |
+
pass
|
564 |
+
raise TemplateNotFound(template)
|
565 |
+
|
566 |
+
@internalcode
|
567 |
+
def load(
|
568 |
+
self,
|
569 |
+
environment: "Environment",
|
570 |
+
name: str,
|
571 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
572 |
+
) -> "Template":
|
573 |
+
for loader in self.loaders:
|
574 |
+
try:
|
575 |
+
return loader.load(environment, name, globals)
|
576 |
+
except TemplateNotFound:
|
577 |
+
pass
|
578 |
+
raise TemplateNotFound(name)
|
579 |
+
|
580 |
+
def list_templates(self) -> t.List[str]:
|
581 |
+
found = set()
|
582 |
+
for loader in self.loaders:
|
583 |
+
found.update(loader.list_templates())
|
584 |
+
return sorted(found)
|
585 |
+
|
586 |
+
|
587 |
+
class _TemplateModule(ModuleType):
|
588 |
+
"""Like a normal module but with support for weak references"""
|
589 |
+
|
590 |
+
|
591 |
+
class ModuleLoader(BaseLoader):
|
592 |
+
"""This loader loads templates from precompiled templates.
|
593 |
+
|
594 |
+
Example usage:
|
595 |
+
|
596 |
+
>>> loader = ChoiceLoader([
|
597 |
+
... ModuleLoader('/path/to/compiled/templates'),
|
598 |
+
... FileSystemLoader('/path/to/templates')
|
599 |
+
... ])
|
600 |
+
|
601 |
+
Templates can be precompiled with :meth:`Environment.compile_templates`.
|
602 |
+
"""
|
603 |
+
|
604 |
+
has_source_access = False
|
605 |
+
|
606 |
+
def __init__(
|
607 |
+
self,
|
608 |
+
path: t.Union[
|
609 |
+
str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
|
610 |
+
],
|
611 |
+
) -> None:
|
612 |
+
package_name = f"_jinja2_module_templates_{id(self):x}"
|
613 |
+
|
614 |
+
# create a fake module that looks for the templates in the
|
615 |
+
# path given.
|
616 |
+
mod = _TemplateModule(package_name)
|
617 |
+
|
618 |
+
if not isinstance(path, abc.Iterable) or isinstance(path, str):
|
619 |
+
path = [path]
|
620 |
+
|
621 |
+
mod.__path__ = [os.fspath(p) for p in path]
|
622 |
+
|
623 |
+
sys.modules[package_name] = weakref.proxy(
|
624 |
+
mod, lambda x: sys.modules.pop(package_name, None)
|
625 |
+
)
|
626 |
+
|
627 |
+
# the only strong reference, the sys.modules entry is weak
|
628 |
+
# so that the garbage collector can remove it once the
|
629 |
+
# loader that created it goes out of business.
|
630 |
+
self.module = mod
|
631 |
+
self.package_name = package_name
|
632 |
+
|
633 |
+
@staticmethod
|
634 |
+
def get_template_key(name: str) -> str:
|
635 |
+
return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
|
636 |
+
|
637 |
+
@staticmethod
|
638 |
+
def get_module_filename(name: str) -> str:
|
639 |
+
return ModuleLoader.get_template_key(name) + ".py"
|
640 |
+
|
641 |
+
@internalcode
|
642 |
+
def load(
|
643 |
+
self,
|
644 |
+
environment: "Environment",
|
645 |
+
name: str,
|
646 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
647 |
+
) -> "Template":
|
648 |
+
key = self.get_template_key(name)
|
649 |
+
module = f"{self.package_name}.{key}"
|
650 |
+
mod = getattr(self.module, module, None)
|
651 |
+
|
652 |
+
if mod is None:
|
653 |
+
try:
|
654 |
+
mod = __import__(module, None, None, ["root"])
|
655 |
+
except ImportError as e:
|
656 |
+
raise TemplateNotFound(name) from e
|
657 |
+
|
658 |
+
# remove the entry from sys.modules, we only want the attribute
|
659 |
+
# on the module object we have stored on the loader.
|
660 |
+
sys.modules.pop(module, None)
|
661 |
+
|
662 |
+
if globals is None:
|
663 |
+
globals = {}
|
664 |
+
|
665 |
+
return environment.template_class.from_module_dict(
|
666 |
+
environment, mod.__dict__, globals
|
667 |
+
)
|
llmeval-env/lib/python3.10/site-packages/jinja2/meta.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Functions that expose information about templates that might be
|
2 |
+
interesting for introspection.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import typing as t
|
6 |
+
|
7 |
+
from . import nodes
|
8 |
+
from .compiler import CodeGenerator
|
9 |
+
from .compiler import Frame
|
10 |
+
|
11 |
+
if t.TYPE_CHECKING:
|
12 |
+
from .environment import Environment
|
13 |
+
|
14 |
+
|
15 |
+
class TrackingCodeGenerator(CodeGenerator):
|
16 |
+
"""We abuse the code generator for introspection."""
|
17 |
+
|
18 |
+
def __init__(self, environment: "Environment") -> None:
|
19 |
+
super().__init__(environment, "<introspection>", "<introspection>")
|
20 |
+
self.undeclared_identifiers: t.Set[str] = set()
|
21 |
+
|
22 |
+
def write(self, x: str) -> None:
|
23 |
+
"""Don't write."""
|
24 |
+
|
25 |
+
def enter_frame(self, frame: Frame) -> None:
|
26 |
+
"""Remember all undeclared identifiers."""
|
27 |
+
super().enter_frame(frame)
|
28 |
+
|
29 |
+
for _, (action, param) in frame.symbols.loads.items():
|
30 |
+
if action == "resolve" and param not in self.environment.globals:
|
31 |
+
self.undeclared_identifiers.add(param)
|
32 |
+
|
33 |
+
|
34 |
+
def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]:
|
35 |
+
"""Returns a set of all variables in the AST that will be looked up from
|
36 |
+
the context at runtime. Because at compile time it's not known which
|
37 |
+
variables will be used depending on the path the execution takes at
|
38 |
+
runtime, all variables are returned.
|
39 |
+
|
40 |
+
>>> from jinja2 import Environment, meta
|
41 |
+
>>> env = Environment()
|
42 |
+
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
|
43 |
+
>>> meta.find_undeclared_variables(ast) == {'bar'}
|
44 |
+
True
|
45 |
+
|
46 |
+
.. admonition:: Implementation
|
47 |
+
|
48 |
+
Internally the code generator is used for finding undeclared variables.
|
49 |
+
This is good to know because the code generator might raise a
|
50 |
+
:exc:`TemplateAssertionError` during compilation and as a matter of
|
51 |
+
fact this function can currently raise that exception as well.
|
52 |
+
"""
|
53 |
+
codegen = TrackingCodeGenerator(ast.environment) # type: ignore
|
54 |
+
codegen.visit(ast)
|
55 |
+
return codegen.undeclared_identifiers
|
56 |
+
|
57 |
+
|
58 |
+
_ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)
|
59 |
+
_RefType = t.Union[nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include]
|
60 |
+
|
61 |
+
|
62 |
+
def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]:
|
63 |
+
"""Finds all the referenced templates from the AST. This will return an
|
64 |
+
iterator over all the hardcoded template extensions, inclusions and
|
65 |
+
imports. If dynamic inheritance or inclusion is used, `None` will be
|
66 |
+
yielded.
|
67 |
+
|
68 |
+
>>> from jinja2 import Environment, meta
|
69 |
+
>>> env = Environment()
|
70 |
+
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
|
71 |
+
>>> list(meta.find_referenced_templates(ast))
|
72 |
+
['layout.html', None]
|
73 |
+
|
74 |
+
This function is useful for dependency tracking. For example if you want
|
75 |
+
to rebuild parts of the website after a layout template has changed.
|
76 |
+
"""
|
77 |
+
template_name: t.Any
|
78 |
+
|
79 |
+
for node in ast.find_all(_ref_types):
|
80 |
+
template: nodes.Expr = node.template # type: ignore
|
81 |
+
|
82 |
+
if not isinstance(template, nodes.Const):
|
83 |
+
# a tuple with some non consts in there
|
84 |
+
if isinstance(template, (nodes.Tuple, nodes.List)):
|
85 |
+
for template_name in template.items:
|
86 |
+
# something const, only yield the strings and ignore
|
87 |
+
# non-string consts that really just make no sense
|
88 |
+
if isinstance(template_name, nodes.Const):
|
89 |
+
if isinstance(template_name.value, str):
|
90 |
+
yield template_name.value
|
91 |
+
# something dynamic in there
|
92 |
+
else:
|
93 |
+
yield None
|
94 |
+
# something dynamic we don't know about here
|
95 |
+
else:
|
96 |
+
yield None
|
97 |
+
continue
|
98 |
+
# constant is a basestring, direct template name
|
99 |
+
if isinstance(template.value, str):
|
100 |
+
yield template.value
|
101 |
+
# a tuple or list (latter *should* not happen) made of consts,
|
102 |
+
# yield the consts that are strings. We could warn here for
|
103 |
+
# non string values
|
104 |
+
elif isinstance(node, nodes.Include) and isinstance(
|
105 |
+
template.value, (tuple, list)
|
106 |
+
):
|
107 |
+
for template_name in template.value:
|
108 |
+
if isinstance(template_name, str):
|
109 |
+
yield template_name
|
110 |
+
# something else we don't care about, we could warn here
|
111 |
+
else:
|
112 |
+
yield None
|
llmeval-env/lib/python3.10/site-packages/jinja2/nativetypes.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from ast import literal_eval
|
3 |
+
from ast import parse
|
4 |
+
from itertools import chain
|
5 |
+
from itertools import islice
|
6 |
+
from types import GeneratorType
|
7 |
+
|
8 |
+
from . import nodes
|
9 |
+
from .compiler import CodeGenerator
|
10 |
+
from .compiler import Frame
|
11 |
+
from .compiler import has_safe_repr
|
12 |
+
from .environment import Environment
|
13 |
+
from .environment import Template
|
14 |
+
|
15 |
+
|
16 |
+
def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:
|
17 |
+
"""Return a native Python type from the list of compiled nodes. If
|
18 |
+
the result is a single node, its value is returned. Otherwise, the
|
19 |
+
nodes are concatenated as strings. If the result can be parsed with
|
20 |
+
:func:`ast.literal_eval`, the parsed value is returned. Otherwise,
|
21 |
+
the string is returned.
|
22 |
+
|
23 |
+
:param values: Iterable of outputs to concatenate.
|
24 |
+
"""
|
25 |
+
head = list(islice(values, 2))
|
26 |
+
|
27 |
+
if not head:
|
28 |
+
return None
|
29 |
+
|
30 |
+
if len(head) == 1:
|
31 |
+
raw = head[0]
|
32 |
+
if not isinstance(raw, str):
|
33 |
+
return raw
|
34 |
+
else:
|
35 |
+
if isinstance(values, GeneratorType):
|
36 |
+
values = chain(head, values)
|
37 |
+
raw = "".join([str(v) for v in values])
|
38 |
+
|
39 |
+
try:
|
40 |
+
return literal_eval(
|
41 |
+
# In Python 3.10+ ast.literal_eval removes leading spaces/tabs
|
42 |
+
# from the given string. For backwards compatibility we need to
|
43 |
+
# parse the string ourselves without removing leading spaces/tabs.
|
44 |
+
parse(raw, mode="eval")
|
45 |
+
)
|
46 |
+
except (ValueError, SyntaxError, MemoryError):
|
47 |
+
return raw
|
48 |
+
|
49 |
+
|
50 |
+
class NativeCodeGenerator(CodeGenerator):
|
51 |
+
"""A code generator which renders Python types by not adding
|
52 |
+
``str()`` around output nodes.
|
53 |
+
"""
|
54 |
+
|
55 |
+
@staticmethod
|
56 |
+
def _default_finalize(value: t.Any) -> t.Any:
|
57 |
+
return value
|
58 |
+
|
59 |
+
def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
|
60 |
+
return repr("".join([str(v) for v in group]))
|
61 |
+
|
62 |
+
def _output_child_to_const(
|
63 |
+
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
|
64 |
+
) -> t.Any:
|
65 |
+
const = node.as_const(frame.eval_ctx)
|
66 |
+
|
67 |
+
if not has_safe_repr(const):
|
68 |
+
raise nodes.Impossible()
|
69 |
+
|
70 |
+
if isinstance(node, nodes.TemplateData):
|
71 |
+
return const
|
72 |
+
|
73 |
+
return finalize.const(const) # type: ignore
|
74 |
+
|
75 |
+
def _output_child_pre(
|
76 |
+
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
|
77 |
+
) -> None:
|
78 |
+
if finalize.src is not None:
|
79 |
+
self.write(finalize.src)
|
80 |
+
|
81 |
+
def _output_child_post(
|
82 |
+
self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo
|
83 |
+
) -> None:
|
84 |
+
if finalize.src is not None:
|
85 |
+
self.write(")")
|
86 |
+
|
87 |
+
|
88 |
+
class NativeEnvironment(Environment):
|
89 |
+
"""An environment that renders templates to native Python types."""
|
90 |
+
|
91 |
+
code_generator_class = NativeCodeGenerator
|
92 |
+
concat = staticmethod(native_concat) # type: ignore
|
93 |
+
|
94 |
+
|
95 |
+
class NativeTemplate(Template):
|
96 |
+
environment_class = NativeEnvironment
|
97 |
+
|
98 |
+
def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
|
99 |
+
"""Render the template to produce a native Python type. If the
|
100 |
+
result is a single node, its value is returned. Otherwise, the
|
101 |
+
nodes are concatenated as strings. If the result can be parsed
|
102 |
+
with :func:`ast.literal_eval`, the parsed value is returned.
|
103 |
+
Otherwise, the string is returned.
|
104 |
+
"""
|
105 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
106 |
+
|
107 |
+
try:
|
108 |
+
return self.environment_class.concat( # type: ignore
|
109 |
+
self.root_render_func(ctx)
|
110 |
+
)
|
111 |
+
except Exception:
|
112 |
+
return self.environment.handle_exception()
|
113 |
+
|
114 |
+
async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
|
115 |
+
if not self.environment.is_async:
|
116 |
+
raise RuntimeError(
|
117 |
+
"The environment was not created with async mode enabled."
|
118 |
+
)
|
119 |
+
|
120 |
+
ctx = self.new_context(dict(*args, **kwargs))
|
121 |
+
|
122 |
+
try:
|
123 |
+
return self.environment_class.concat( # type: ignore
|
124 |
+
[n async for n in self.root_render_func(ctx)] # type: ignore
|
125 |
+
)
|
126 |
+
except Exception:
|
127 |
+
return self.environment.handle_exception()
|
128 |
+
|
129 |
+
|
130 |
+
NativeEnvironment.template_class = NativeTemplate
|
llmeval-env/lib/python3.10/site-packages/jinja2/nodes.py
ADDED
@@ -0,0 +1,1206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""AST nodes generated by the parser for the compiler. Also provides
|
2 |
+
some node tree helper functions used by the parser and compiler in order
|
3 |
+
to normalize nodes.
|
4 |
+
"""
|
5 |
+
|
6 |
+
import inspect
|
7 |
+
import operator
|
8 |
+
import typing as t
|
9 |
+
from collections import deque
|
10 |
+
|
11 |
+
from markupsafe import Markup
|
12 |
+
|
13 |
+
from .utils import _PassArg
|
14 |
+
|
15 |
+
if t.TYPE_CHECKING:
|
16 |
+
import typing_extensions as te
|
17 |
+
|
18 |
+
from .environment import Environment
|
19 |
+
|
20 |
+
_NodeBound = t.TypeVar("_NodeBound", bound="Node")
|
21 |
+
|
22 |
+
_binop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
|
23 |
+
"*": operator.mul,
|
24 |
+
"/": operator.truediv,
|
25 |
+
"//": operator.floordiv,
|
26 |
+
"**": operator.pow,
|
27 |
+
"%": operator.mod,
|
28 |
+
"+": operator.add,
|
29 |
+
"-": operator.sub,
|
30 |
+
}
|
31 |
+
|
32 |
+
_uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] = {
|
33 |
+
"not": operator.not_,
|
34 |
+
"+": operator.pos,
|
35 |
+
"-": operator.neg,
|
36 |
+
}
|
37 |
+
|
38 |
+
_cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
|
39 |
+
"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 |
+
}
|
48 |
+
|
49 |
+
|
50 |
+
class Impossible(Exception):
|
51 |
+
"""Raised if the node could not perform a requested action."""
|
52 |
+
|
53 |
+
|
54 |
+
class NodeType(type):
|
55 |
+
"""A metaclass for nodes that handles the field and attribute
|
56 |
+
inheritance. fields and attributes from the parent class are
|
57 |
+
automatically forwarded to the child."""
|
58 |
+
|
59 |
+
def __new__(mcs, name, bases, d): # type: ignore
|
60 |
+
for attr in "fields", "attributes":
|
61 |
+
storage: t.List[t.Tuple[str, ...]] = []
|
62 |
+
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)
|
69 |
+
|
70 |
+
|
71 |
+
class EvalContext:
|
72 |
+
"""Holds evaluation time information. Custom attributes can be attached
|
73 |
+
to it in extensions.
|
74 |
+
"""
|
75 |
+
|
76 |
+
def __init__(
|
77 |
+
self, environment: "Environment", template_name: t.Optional[str] = None
|
78 |
+
) -> None:
|
79 |
+
self.environment = environment
|
80 |
+
if callable(environment.autoescape):
|
81 |
+
self.autoescape = environment.autoescape(template_name)
|
82 |
+
else:
|
83 |
+
self.autoescape = environment.autoescape
|
84 |
+
self.volatile = False
|
85 |
+
|
86 |
+
def save(self) -> t.Mapping[str, t.Any]:
|
87 |
+
return self.__dict__.copy()
|
88 |
+
|
89 |
+
def revert(self, old: t.Mapping[str, t.Any]) -> None:
|
90 |
+
self.__dict__.clear()
|
91 |
+
self.__dict__.update(old)
|
92 |
+
|
93 |
+
|
94 |
+
def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:
|
95 |
+
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 ctx
|
103 |
+
|
104 |
+
|
105 |
+
class Node(metaclass=NodeType):
|
106 |
+
"""Baseclass for all Jinja nodes. There are a number of nodes available
|
107 |
+
of different types. There are four major types:
|
108 |
+
|
109 |
+
- :class:`Stmt`: statements
|
110 |
+
- :class:`Expr`: expressions
|
111 |
+
- :class:`Helper`: helper nodes
|
112 |
+
- :class:`Template`: the outermost wrapper node
|
113 |
+
|
114 |
+
All nodes have fields and attributes. Fields may be other nodes, lists,
|
115 |
+
or arbitrary values. Fields are passed to the constructor as regular
|
116 |
+
positional arguments, attributes as keyword arguments. Each node has
|
117 |
+
two attributes: `lineno` (the line number of the node) and `environment`.
|
118 |
+
The `environment` attribute is set at the end of the parsing process for
|
119 |
+
all nodes automatically.
|
120 |
+
"""
|
121 |
+
|
122 |
+
fields: t.Tuple[str, ...] = ()
|
123 |
+
attributes: t.Tuple[str, ...] = ("lineno", "environment")
|
124 |
+
abstract = True
|
125 |
+
|
126 |
+
lineno: int
|
127 |
+
environment: t.Optional["Environment"]
|
128 |
+
|
129 |
+
def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
|
130 |
+
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:
|
135 |
+
raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
|
136 |
+
raise TypeError(
|
137 |
+
f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
|
138 |
+
f" argument{'s' if len(self.fields) != 1 else ''}"
|
139 |
+
)
|
140 |
+
for name, arg in zip(self.fields, fields):
|
141 |
+
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}")
|
146 |
+
|
147 |
+
def iter_fields(
|
148 |
+
self,
|
149 |
+
exclude: t.Optional[t.Container[str]] = None,
|
150 |
+
only: t.Optional[t.Container[str]] = None,
|
151 |
+
) -> t.Iterator[t.Tuple[str, t.Any]]:
|
152 |
+
"""This method iterates over all fields that are defined and yields
|
153 |
+
``(key, value)`` tuples. Per default all fields are returned, but
|
154 |
+
it's possible to limit that to some fields by providing the `only`
|
155 |
+
parameter or to exclude some using the `exclude` parameter. Both
|
156 |
+
should be sets or tuples of field names.
|
157 |
+
"""
|
158 |
+
for name in self.fields:
|
159 |
+
if (
|
160 |
+
(exclude is None and only is None)
|
161 |
+
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 |
+
pass
|
168 |
+
|
169 |
+
def iter_child_nodes(
|
170 |
+
self,
|
171 |
+
exclude: t.Optional[t.Container[str]] = None,
|
172 |
+
only: t.Optional[t.Container[str]] = None,
|
173 |
+
) -> t.Iterator["Node"]:
|
174 |
+
"""Iterates over all direct child nodes of the node. This iterates
|
175 |
+
over all fields and yields the values of they are nodes. If the value
|
176 |
+
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 n
|
183 |
+
elif isinstance(item, Node):
|
184 |
+
yield item
|
185 |
+
|
186 |
+
def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
|
187 |
+
"""Find the first node of a given type. If no such node exists the
|
188 |
+
return value is `None`.
|
189 |
+
"""
|
190 |
+
for result in self.find_all(node_type):
|
191 |
+
return result
|
192 |
+
|
193 |
+
return None
|
194 |
+
|
195 |
+
def find_all(
|
196 |
+
self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
|
197 |
+
) -> t.Iterator[_NodeBound]:
|
198 |
+
"""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):
|
203 |
+
yield child # type: ignore
|
204 |
+
yield from child.find_all(node_type)
|
205 |
+
|
206 |
+
def set_ctx(self, ctx: str) -> "Node":
|
207 |
+
"""Reset the context of a node and all child nodes. Per default the
|
208 |
+
parser will all generate nodes that have a 'load' context as it's the
|
209 |
+
most common one. This method is used in the parser to set assignment
|
210 |
+
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:
|
216 |
+
node.ctx = ctx # type: ignore
|
217 |
+
todo.extend(node.iter_child_nodes())
|
218 |
+
return self
|
219 |
+
|
220 |
+
def set_lineno(self, lineno: int, override: bool = False) -> "Node":
|
221 |
+
"""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 = lineno
|
228 |
+
todo.extend(node.iter_child_nodes())
|
229 |
+
return self
|
230 |
+
|
231 |
+
def set_environment(self, environment: "Environment") -> "Node":
|
232 |
+
"""Set the environment for all nodes."""
|
233 |
+
todo = deque([self])
|
234 |
+
while todo:
|
235 |
+
node = todo.popleft()
|
236 |
+
node.environment = environment
|
237 |
+
todo.extend(node.iter_child_nodes())
|
238 |
+
return self
|
239 |
+
|
240 |
+
def __eq__(self, other: t.Any) -> bool:
|
241 |
+
if type(self) is not type(other):
|
242 |
+
return NotImplemented
|
243 |
+
|
244 |
+
return tuple(self.iter_fields()) == tuple(other.iter_fields())
|
245 |
+
|
246 |
+
__hash__ = object.__hash__
|
247 |
+
|
248 |
+
def __repr__(self) -> str:
|
249 |
+
args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
|
250 |
+
return f"{type(self).__name__}({args_str})"
|
251 |
+
|
252 |
+
def dump(self) -> str:
|
253 |
+
def _dump(node: t.Union[Node, t.Any]) -> None:
|
254 |
+
if not isinstance(node, Node):
|
255 |
+
buf.append(repr(node))
|
256 |
+
return
|
257 |
+
|
258 |
+
buf.append(f"nodes.{type(node).__name__}(")
|
259 |
+
if not node.fields:
|
260 |
+
buf.append(")")
|
261 |
+
return
|
262 |
+
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(")")
|
276 |
+
|
277 |
+
buf: t.List[str] = []
|
278 |
+
_dump(self)
|
279 |
+
return "".join(buf)
|
280 |
+
|
281 |
+
|
282 |
+
class Stmt(Node):
|
283 |
+
"""Base node for all statements."""
|
284 |
+
|
285 |
+
abstract = True
|
286 |
+
|
287 |
+
|
288 |
+
class Helper(Node):
|
289 |
+
"""Nodes that exist in a specific context only."""
|
290 |
+
|
291 |
+
abstract = True
|
292 |
+
|
293 |
+
|
294 |
+
class Template(Node):
|
295 |
+
"""Node that represents a template. This must be the outermost node that
|
296 |
+
is passed to the compiler.
|
297 |
+
"""
|
298 |
+
|
299 |
+
fields = ("body",)
|
300 |
+
body: t.List[Node]
|
301 |
+
|
302 |
+
|
303 |
+
class 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 |
+
"""
|
307 |
+
|
308 |
+
fields = ("nodes",)
|
309 |
+
nodes: t.List["Expr"]
|
310 |
+
|
311 |
+
|
312 |
+
class Extends(Stmt):
|
313 |
+
"""Represents an extends statement."""
|
314 |
+
|
315 |
+
fields = ("template",)
|
316 |
+
template: "Expr"
|
317 |
+
|
318 |
+
|
319 |
+
class For(Stmt):
|
320 |
+
"""The for loop. `target` is the target for the iteration (usually a
|
321 |
+
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
|
322 |
+
of nodes that are used as loop-body, and `else_` a list of nodes for the
|
323 |
+
`else` block. If no else node exists it has to be an empty list.
|
324 |
+
|
325 |
+
For filtered nodes an expression can be stored as `test`, otherwise `None`.
|
326 |
+
"""
|
327 |
+
|
328 |
+
fields = ("target", "iter", "body", "else_", "test", "recursive")
|
329 |
+
target: Node
|
330 |
+
iter: Node
|
331 |
+
body: t.List[Node]
|
332 |
+
else_: t.List[Node]
|
333 |
+
test: t.Optional[Node]
|
334 |
+
recursive: bool
|
335 |
+
|
336 |
+
|
337 |
+
class If(Stmt):
|
338 |
+
"""If `test` is true, `body` is rendered, else `else_`."""
|
339 |
+
|
340 |
+
fields = ("test", "body", "elif_", "else_")
|
341 |
+
test: Node
|
342 |
+
body: t.List[Node]
|
343 |
+
elif_: t.List["If"]
|
344 |
+
else_: t.List[Node]
|
345 |
+
|
346 |
+
|
347 |
+
class Macro(Stmt):
|
348 |
+
"""A macro definition. `name` is the name of the macro, `args` a list of
|
349 |
+
arguments and `defaults` a list of defaults if there are any. `body` is
|
350 |
+
a list of nodes for the macro body.
|
351 |
+
"""
|
352 |
+
|
353 |
+
fields = ("name", "args", "defaults", "body")
|
354 |
+
name: str
|
355 |
+
args: t.List["Name"]
|
356 |
+
defaults: t.List["Expr"]
|
357 |
+
body: t.List[Node]
|
358 |
+
|
359 |
+
|
360 |
+
class CallBlock(Stmt):
|
361 |
+
"""Like a macro without a name but a call instead. `call` is called with
|
362 |
+
the unnamed macro as `caller` argument this node holds.
|
363 |
+
"""
|
364 |
+
|
365 |
+
fields = ("call", "args", "defaults", "body")
|
366 |
+
call: "Call"
|
367 |
+
args: t.List["Name"]
|
368 |
+
defaults: t.List["Expr"]
|
369 |
+
body: t.List[Node]
|
370 |
+
|
371 |
+
|
372 |
+
class FilterBlock(Stmt):
|
373 |
+
"""Node for filter sections."""
|
374 |
+
|
375 |
+
fields = ("body", "filter")
|
376 |
+
body: t.List[Node]
|
377 |
+
filter: "Filter"
|
378 |
+
|
379 |
+
|
380 |
+
class With(Stmt):
|
381 |
+
"""Specific node for with statements. In older versions of Jinja the
|
382 |
+
with statement was implemented on the base of the `Scope` node instead.
|
383 |
+
|
384 |
+
.. versionadded:: 2.9.3
|
385 |
+
"""
|
386 |
+
|
387 |
+
fields = ("targets", "values", "body")
|
388 |
+
targets: t.List["Expr"]
|
389 |
+
values: t.List["Expr"]
|
390 |
+
body: t.List[Node]
|
391 |
+
|
392 |
+
|
393 |
+
class Block(Stmt):
|
394 |
+
"""A node that represents a block.
|
395 |
+
|
396 |
+
.. versionchanged:: 3.0.0
|
397 |
+
the `required` field was added.
|
398 |
+
"""
|
399 |
+
|
400 |
+
fields = ("name", "body", "scoped", "required")
|
401 |
+
name: str
|
402 |
+
body: t.List[Node]
|
403 |
+
scoped: bool
|
404 |
+
required: bool
|
405 |
+
|
406 |
+
|
407 |
+
class Include(Stmt):
|
408 |
+
"""A node that represents the include tag."""
|
409 |
+
|
410 |
+
fields = ("template", "with_context", "ignore_missing")
|
411 |
+
template: "Expr"
|
412 |
+
with_context: bool
|
413 |
+
ignore_missing: bool
|
414 |
+
|
415 |
+
|
416 |
+
class Import(Stmt):
|
417 |
+
"""A node that represents the import tag."""
|
418 |
+
|
419 |
+
fields = ("template", "target", "with_context")
|
420 |
+
template: "Expr"
|
421 |
+
target: str
|
422 |
+
with_context: bool
|
423 |
+
|
424 |
+
|
425 |
+
class FromImport(Stmt):
|
426 |
+
"""A node that represents the from import tag. It's important to not
|
427 |
+
pass unsafe names to the name attribute. The compiler translates the
|
428 |
+
attribute lookups directly into getattr calls and does *not* use the
|
429 |
+
subscript callback of the interface. As exported variables may not
|
430 |
+
start with double underscores (which the parser asserts) this is not a
|
431 |
+
problem for regular Jinja code, but if this node is used in an extension
|
432 |
+
extra care must be taken.
|
433 |
+
|
434 |
+
The list of names may contain tuples if aliases are wanted.
|
435 |
+
"""
|
436 |
+
|
437 |
+
fields = ("template", "names", "with_context")
|
438 |
+
template: "Expr"
|
439 |
+
names: t.List[t.Union[str, t.Tuple[str, str]]]
|
440 |
+
with_context: bool
|
441 |
+
|
442 |
+
|
443 |
+
class ExprStmt(Stmt):
|
444 |
+
"""A statement that evaluates an expression and discards the result."""
|
445 |
+
|
446 |
+
fields = ("node",)
|
447 |
+
node: Node
|
448 |
+
|
449 |
+
|
450 |
+
class Assign(Stmt):
|
451 |
+
"""Assigns an expression to a target."""
|
452 |
+
|
453 |
+
fields = ("target", "node")
|
454 |
+
target: "Expr"
|
455 |
+
node: Node
|
456 |
+
|
457 |
+
|
458 |
+
class AssignBlock(Stmt):
|
459 |
+
"""Assigns a block to a target."""
|
460 |
+
|
461 |
+
fields = ("target", "filter", "body")
|
462 |
+
target: "Expr"
|
463 |
+
filter: t.Optional["Filter"]
|
464 |
+
body: t.List[Node]
|
465 |
+
|
466 |
+
|
467 |
+
class Expr(Node):
|
468 |
+
"""Baseclass for all expressions."""
|
469 |
+
|
470 |
+
abstract = True
|
471 |
+
|
472 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
473 |
+
"""Return the value of the expression as constant or raise
|
474 |
+
:exc:`Impossible` if this was not possible.
|
475 |
+
|
476 |
+
An :class:`EvalContext` can be provided, if none is given
|
477 |
+
a default context is created which requires the nodes to have
|
478 |
+
an attached environment.
|
479 |
+
|
480 |
+
.. versionchanged:: 2.4
|
481 |
+
the `eval_ctx` parameter was added.
|
482 |
+
"""
|
483 |
+
raise Impossible()
|
484 |
+
|
485 |
+
def can_assign(self) -> bool:
|
486 |
+
"""Check if it's possible to assign something to this node."""
|
487 |
+
return False
|
488 |
+
|
489 |
+
|
490 |
+
class BinExpr(Expr):
|
491 |
+
"""Baseclass for all binary expressions."""
|
492 |
+
|
493 |
+
fields = ("left", "right")
|
494 |
+
left: Expr
|
495 |
+
right: Expr
|
496 |
+
operator: str
|
497 |
+
abstract = True
|
498 |
+
|
499 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
500 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
501 |
+
|
502 |
+
# intercepted operators cannot be folded at compile time
|
503 |
+
if (
|
504 |
+
eval_ctx.environment.sandboxed
|
505 |
+
and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
|
506 |
+
):
|
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))
|
511 |
+
except Exception as e:
|
512 |
+
raise Impossible() from e
|
513 |
+
|
514 |
+
|
515 |
+
class UnaryExpr(Expr):
|
516 |
+
"""Baseclass for all unary expressions."""
|
517 |
+
|
518 |
+
fields = ("node",)
|
519 |
+
node: Expr
|
520 |
+
operator: str
|
521 |
+
abstract = True
|
522 |
+
|
523 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
524 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
525 |
+
|
526 |
+
# intercepted operators cannot be folded at compile time
|
527 |
+
if (
|
528 |
+
eval_ctx.environment.sandboxed
|
529 |
+
and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
|
530 |
+
):
|
531 |
+
raise Impossible()
|
532 |
+
f = _uaop_to_func[self.operator]
|
533 |
+
try:
|
534 |
+
return f(self.node.as_const(eval_ctx))
|
535 |
+
except Exception as e:
|
536 |
+
raise Impossible() from e
|
537 |
+
|
538 |
+
|
539 |
+
class 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:
|
542 |
+
|
543 |
+
- `store`: store a value in the name
|
544 |
+
- `load`: load that name
|
545 |
+
- `param`: like `store` but if the name was defined as function parameter.
|
546 |
+
"""
|
547 |
+
|
548 |
+
fields = ("name", "ctx")
|
549 |
+
name: str
|
550 |
+
ctx: str
|
551 |
+
|
552 |
+
def can_assign(self) -> bool:
|
553 |
+
return self.name not in {"true", "false", "none", "True", "False", "None"}
|
554 |
+
|
555 |
+
|
556 |
+
class NSRef(Expr):
|
557 |
+
"""Reference to a namespace value assignment"""
|
558 |
+
|
559 |
+
fields = ("name", "attr")
|
560 |
+
name: str
|
561 |
+
attr: str
|
562 |
+
|
563 |
+
def can_assign(self) -> bool:
|
564 |
+
# We don't need any special checks here; NSRef assignments have a
|
565 |
+
# runtime check to ensure the target is a namespace object which will
|
566 |
+
# have been checked already as it is created using a normal assignment
|
567 |
+
# which goes through a `Name` node.
|
568 |
+
return True
|
569 |
+
|
570 |
+
|
571 |
+
class Literal(Expr):
|
572 |
+
"""Baseclass for literals."""
|
573 |
+
|
574 |
+
abstract = True
|
575 |
+
|
576 |
+
|
577 |
+
class Const(Literal):
|
578 |
+
"""All constant values. The parser will return this node for simple
|
579 |
+
constants such as ``42`` or ``"foo"`` but it can be used to store more
|
580 |
+
complex values such as lists too. Only constants with a safe
|
581 |
+
representation (objects where ``eval(repr(x)) == x`` is true).
|
582 |
+
"""
|
583 |
+
|
584 |
+
fields = ("value",)
|
585 |
+
value: t.Any
|
586 |
+
|
587 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
588 |
+
return self.value
|
589 |
+
|
590 |
+
@classmethod
|
591 |
+
def from_untrusted(
|
592 |
+
cls,
|
593 |
+
value: t.Any,
|
594 |
+
lineno: t.Optional[int] = None,
|
595 |
+
environment: "t.Optional[Environment]" = None,
|
596 |
+
) -> "Const":
|
597 |
+
"""Return a const object if the value is representable as
|
598 |
+
constant value in the generated code, otherwise it will raise
|
599 |
+
an `Impossible` exception.
|
600 |
+
"""
|
601 |
+
from .compiler import has_safe_repr
|
602 |
+
|
603 |
+
if not has_safe_repr(value):
|
604 |
+
raise Impossible()
|
605 |
+
return cls(value, lineno=lineno, environment=environment)
|
606 |
+
|
607 |
+
|
608 |
+
class TemplateData(Literal):
|
609 |
+
"""A constant template string."""
|
610 |
+
|
611 |
+
fields = ("data",)
|
612 |
+
data: str
|
613 |
+
|
614 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
|
615 |
+
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.data
|
621 |
+
|
622 |
+
|
623 |
+
class Tuple(Literal):
|
624 |
+
"""For loop unpacking and some other things like multiple arguments
|
625 |
+
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
|
626 |
+
is used for loading the names or storing.
|
627 |
+
"""
|
628 |
+
|
629 |
+
fields = ("items", "ctx")
|
630 |
+
items: t.List[Expr]
|
631 |
+
ctx: str
|
632 |
+
|
633 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:
|
634 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
635 |
+
return tuple(x.as_const(eval_ctx) for x in self.items)
|
636 |
+
|
637 |
+
def can_assign(self) -> bool:
|
638 |
+
for item in self.items:
|
639 |
+
if not item.can_assign():
|
640 |
+
return False
|
641 |
+
return True
|
642 |
+
|
643 |
+
|
644 |
+
class List(Literal):
|
645 |
+
"""Any list literal such as ``[1, 2, 3]``"""
|
646 |
+
|
647 |
+
fields = ("items",)
|
648 |
+
items: t.List[Expr]
|
649 |
+
|
650 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:
|
651 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
652 |
+
return [x.as_const(eval_ctx) for x in self.items]
|
653 |
+
|
654 |
+
|
655 |
+
class Dict(Literal):
|
656 |
+
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
|
657 |
+
:class:`Pair` nodes.
|
658 |
+
"""
|
659 |
+
|
660 |
+
fields = ("items",)
|
661 |
+
items: t.List["Pair"]
|
662 |
+
|
663 |
+
def as_const(
|
664 |
+
self, eval_ctx: t.Optional[EvalContext] = None
|
665 |
+
) -> t.Dict[t.Any, t.Any]:
|
666 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
667 |
+
return dict(x.as_const(eval_ctx) for x in self.items)
|
668 |
+
|
669 |
+
|
670 |
+
class Pair(Helper):
|
671 |
+
"""A key, value pair for dicts."""
|
672 |
+
|
673 |
+
fields = ("key", "value")
|
674 |
+
key: Expr
|
675 |
+
value: Expr
|
676 |
+
|
677 |
+
def as_const(
|
678 |
+
self, eval_ctx: t.Optional[EvalContext] = None
|
679 |
+
) -> t.Tuple[t.Any, t.Any]:
|
680 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
681 |
+
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
|
682 |
+
|
683 |
+
|
684 |
+
class Keyword(Helper):
|
685 |
+
"""A key, value pair for keyword arguments where key is a string."""
|
686 |
+
|
687 |
+
fields = ("key", "value")
|
688 |
+
key: str
|
689 |
+
value: Expr
|
690 |
+
|
691 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
|
692 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
693 |
+
return self.key, self.value.as_const(eval_ctx)
|
694 |
+
|
695 |
+
|
696 |
+
class CondExpr(Expr):
|
697 |
+
"""A conditional expression (inline if expression). (``{{
|
698 |
+
foo if bar else baz }}``)
|
699 |
+
"""
|
700 |
+
|
701 |
+
fields = ("test", "expr1", "expr2")
|
702 |
+
test: Expr
|
703 |
+
expr1: Expr
|
704 |
+
expr2: t.Optional[Expr]
|
705 |
+
|
706 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
707 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
708 |
+
if self.test.as_const(eval_ctx):
|
709 |
+
return self.expr1.as_const(eval_ctx)
|
710 |
+
|
711 |
+
# if we evaluate to an undefined object, we better do that at runtime
|
712 |
+
if self.expr2 is None:
|
713 |
+
raise Impossible()
|
714 |
+
|
715 |
+
return self.expr2.as_const(eval_ctx)
|
716 |
+
|
717 |
+
|
718 |
+
def args_as_const(
|
719 |
+
node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
|
720 |
+
) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
|
721 |
+
args = [x.as_const(eval_ctx) for x in node.args]
|
722 |
+
kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
|
723 |
+
|
724 |
+
if node.dyn_args is not None:
|
725 |
+
try:
|
726 |
+
args.extend(node.dyn_args.as_const(eval_ctx))
|
727 |
+
except Exception as e:
|
728 |
+
raise Impossible() from e
|
729 |
+
|
730 |
+
if node.dyn_kwargs is not None:
|
731 |
+
try:
|
732 |
+
kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
|
733 |
+
except Exception as e:
|
734 |
+
raise Impossible() from e
|
735 |
+
|
736 |
+
return args, kwargs
|
737 |
+
|
738 |
+
|
739 |
+
class _FilterTestCommon(Expr):
|
740 |
+
fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
|
741 |
+
node: Expr
|
742 |
+
name: str
|
743 |
+
args: t.List[Expr]
|
744 |
+
kwargs: t.List[Pair]
|
745 |
+
dyn_args: t.Optional[Expr]
|
746 |
+
dyn_kwargs: t.Optional[Expr]
|
747 |
+
abstract = True
|
748 |
+
_is_filter = True
|
749 |
+
|
750 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
751 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
752 |
+
|
753 |
+
if eval_ctx.volatile:
|
754 |
+
raise Impossible()
|
755 |
+
|
756 |
+
if self._is_filter:
|
757 |
+
env_map = eval_ctx.environment.filters
|
758 |
+
else:
|
759 |
+
env_map = eval_ctx.environment.tests
|
760 |
+
|
761 |
+
func = env_map.get(self.name)
|
762 |
+
pass_arg = _PassArg.from_obj(func) # type: ignore
|
763 |
+
|
764 |
+
if func is None or pass_arg is _PassArg.context:
|
765 |
+
raise Impossible()
|
766 |
+
|
767 |
+
if eval_ctx.environment.is_async and (
|
768 |
+
getattr(func, "jinja_async_variant", False) is True
|
769 |
+
or inspect.iscoroutinefunction(func)
|
770 |
+
):
|
771 |
+
raise Impossible()
|
772 |
+
|
773 |
+
args, kwargs = args_as_const(self, eval_ctx)
|
774 |
+
args.insert(0, self.node.as_const(eval_ctx))
|
775 |
+
|
776 |
+
if pass_arg is _PassArg.eval_context:
|
777 |
+
args.insert(0, eval_ctx)
|
778 |
+
elif pass_arg is _PassArg.environment:
|
779 |
+
args.insert(0, eval_ctx.environment)
|
780 |
+
|
781 |
+
try:
|
782 |
+
return func(*args, **kwargs)
|
783 |
+
except Exception as e:
|
784 |
+
raise Impossible() from e
|
785 |
+
|
786 |
+
|
787 |
+
class Filter(_FilterTestCommon):
|
788 |
+
"""Apply a filter to an expression. ``name`` is the name of the
|
789 |
+
filter, the other fields are the same as :class:`Call`.
|
790 |
+
|
791 |
+
If ``node`` is ``None``, the filter is being used in a filter block
|
792 |
+
and is applied to the content of the block.
|
793 |
+
"""
|
794 |
+
|
795 |
+
node: t.Optional[Expr] # type: ignore
|
796 |
+
|
797 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
798 |
+
if self.node is None:
|
799 |
+
raise Impossible()
|
800 |
+
|
801 |
+
return super().as_const(eval_ctx=eval_ctx)
|
802 |
+
|
803 |
+
|
804 |
+
class Test(_FilterTestCommon):
|
805 |
+
"""Apply a test to an expression. ``name`` is the name of the test,
|
806 |
+
the other field are the same as :class:`Call`.
|
807 |
+
|
808 |
+
.. versionchanged:: 3.0
|
809 |
+
``as_const`` shares the same logic for filters and tests. Tests
|
810 |
+
check for volatile, async, and ``@pass_context`` etc.
|
811 |
+
decorators.
|
812 |
+
"""
|
813 |
+
|
814 |
+
_is_filter = False
|
815 |
+
|
816 |
+
|
817 |
+
class Call(Expr):
|
818 |
+
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
|
819 |
+
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
|
820 |
+
and `dyn_kwargs` has to be either `None` or a node that is used as
|
821 |
+
node for dynamic positional (``*args``) or keyword (``**kwargs``)
|
822 |
+
arguments.
|
823 |
+
"""
|
824 |
+
|
825 |
+
fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")
|
826 |
+
node: Expr
|
827 |
+
args: t.List[Expr]
|
828 |
+
kwargs: t.List[Keyword]
|
829 |
+
dyn_args: t.Optional[Expr]
|
830 |
+
dyn_kwargs: t.Optional[Expr]
|
831 |
+
|
832 |
+
|
833 |
+
class Getitem(Expr):
|
834 |
+
"""Get an attribute or item from an expression and prefer the item."""
|
835 |
+
|
836 |
+
fields = ("node", "arg", "ctx")
|
837 |
+
node: Expr
|
838 |
+
arg: Expr
|
839 |
+
ctx: str
|
840 |
+
|
841 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
842 |
+
if self.ctx != "load":
|
843 |
+
raise Impossible()
|
844 |
+
|
845 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
846 |
+
|
847 |
+
try:
|
848 |
+
return eval_ctx.environment.getitem(
|
849 |
+
self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
|
850 |
+
)
|
851 |
+
except Exception as e:
|
852 |
+
raise Impossible() from e
|
853 |
+
|
854 |
+
|
855 |
+
class Getattr(Expr):
|
856 |
+
"""Get an attribute or item from an expression that is a ascii-only
|
857 |
+
bytestring and prefer the attribute.
|
858 |
+
"""
|
859 |
+
|
860 |
+
fields = ("node", "attr", "ctx")
|
861 |
+
node: Expr
|
862 |
+
attr: str
|
863 |
+
ctx: str
|
864 |
+
|
865 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
866 |
+
if self.ctx != "load":
|
867 |
+
raise Impossible()
|
868 |
+
|
869 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
870 |
+
|
871 |
+
try:
|
872 |
+
return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
|
873 |
+
except Exception as e:
|
874 |
+
raise Impossible() from e
|
875 |
+
|
876 |
+
|
877 |
+
class Slice(Expr):
|
878 |
+
"""Represents a slice object. This must only be used as argument for
|
879 |
+
:class:`Subscript`.
|
880 |
+
"""
|
881 |
+
|
882 |
+
fields = ("start", "stop", "step")
|
883 |
+
start: t.Optional[Expr]
|
884 |
+
stop: t.Optional[Expr]
|
885 |
+
step: t.Optional[Expr]
|
886 |
+
|
887 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
|
888 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
889 |
+
|
890 |
+
def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
|
891 |
+
if obj is None:
|
892 |
+
return None
|
893 |
+
return obj.as_const(eval_ctx)
|
894 |
+
|
895 |
+
return slice(const(self.start), const(self.stop), const(self.step))
|
896 |
+
|
897 |
+
|
898 |
+
class Concat(Expr):
|
899 |
+
"""Concatenates the list of expressions provided after converting
|
900 |
+
them to strings.
|
901 |
+
"""
|
902 |
+
|
903 |
+
fields = ("nodes",)
|
904 |
+
nodes: t.List[Expr]
|
905 |
+
|
906 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
|
907 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
908 |
+
return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
|
909 |
+
|
910 |
+
|
911 |
+
class Compare(Expr):
|
912 |
+
"""Compares an expression with some other expressions. `ops` must be a
|
913 |
+
list of :class:`Operand`\\s.
|
914 |
+
"""
|
915 |
+
|
916 |
+
fields = ("expr", "ops")
|
917 |
+
expr: Expr
|
918 |
+
ops: t.List["Operand"]
|
919 |
+
|
920 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
921 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
922 |
+
result = value = self.expr.as_const(eval_ctx)
|
923 |
+
|
924 |
+
try:
|
925 |
+
for op in self.ops:
|
926 |
+
new_value = op.expr.as_const(eval_ctx)
|
927 |
+
result = _cmpop_to_func[op.op](value, new_value)
|
928 |
+
|
929 |
+
if not result:
|
930 |
+
return False
|
931 |
+
|
932 |
+
value = new_value
|
933 |
+
except Exception as e:
|
934 |
+
raise Impossible() from e
|
935 |
+
|
936 |
+
return result
|
937 |
+
|
938 |
+
|
939 |
+
class Operand(Helper):
|
940 |
+
"""Holds an operator and an expression."""
|
941 |
+
|
942 |
+
fields = ("op", "expr")
|
943 |
+
op: str
|
944 |
+
expr: Expr
|
945 |
+
|
946 |
+
|
947 |
+
class Mul(BinExpr):
|
948 |
+
"""Multiplies the left with the right node."""
|
949 |
+
|
950 |
+
operator = "*"
|
951 |
+
|
952 |
+
|
953 |
+
class Div(BinExpr):
|
954 |
+
"""Divides the left by the right node."""
|
955 |
+
|
956 |
+
operator = "/"
|
957 |
+
|
958 |
+
|
959 |
+
class FloorDiv(BinExpr):
|
960 |
+
"""Divides the left by the right node and converts the
|
961 |
+
result into an integer by truncating.
|
962 |
+
"""
|
963 |
+
|
964 |
+
operator = "//"
|
965 |
+
|
966 |
+
|
967 |
+
class Add(BinExpr):
|
968 |
+
"""Add the left to the right node."""
|
969 |
+
|
970 |
+
operator = "+"
|
971 |
+
|
972 |
+
|
973 |
+
class Sub(BinExpr):
|
974 |
+
"""Subtract the right from the left node."""
|
975 |
+
|
976 |
+
operator = "-"
|
977 |
+
|
978 |
+
|
979 |
+
class Mod(BinExpr):
|
980 |
+
"""Left modulo right."""
|
981 |
+
|
982 |
+
operator = "%"
|
983 |
+
|
984 |
+
|
985 |
+
class Pow(BinExpr):
|
986 |
+
"""Left to the power of right."""
|
987 |
+
|
988 |
+
operator = "**"
|
989 |
+
|
990 |
+
|
991 |
+
class And(BinExpr):
|
992 |
+
"""Short circuited AND."""
|
993 |
+
|
994 |
+
operator = "and"
|
995 |
+
|
996 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
997 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
998 |
+
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
|
999 |
+
|
1000 |
+
|
1001 |
+
class Or(BinExpr):
|
1002 |
+
"""Short circuited OR."""
|
1003 |
+
|
1004 |
+
operator = "or"
|
1005 |
+
|
1006 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
|
1007 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
1008 |
+
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
|
1009 |
+
|
1010 |
+
|
1011 |
+
class Not(UnaryExpr):
|
1012 |
+
"""Negate the expression."""
|
1013 |
+
|
1014 |
+
operator = "not"
|
1015 |
+
|
1016 |
+
|
1017 |
+
class Neg(UnaryExpr):
|
1018 |
+
"""Make the expression negative."""
|
1019 |
+
|
1020 |
+
operator = "-"
|
1021 |
+
|
1022 |
+
|
1023 |
+
class Pos(UnaryExpr):
|
1024 |
+
"""Make the expression positive (noop for most expressions)"""
|
1025 |
+
|
1026 |
+
operator = "+"
|
1027 |
+
|
1028 |
+
|
1029 |
+
# Helpers for extensions
|
1030 |
+
|
1031 |
+
|
1032 |
+
class EnvironmentAttribute(Expr):
|
1033 |
+
"""Loads an attribute from the environment object. This is useful for
|
1034 |
+
extensions that want to call a callback stored on the environment.
|
1035 |
+
"""
|
1036 |
+
|
1037 |
+
fields = ("name",)
|
1038 |
+
name: str
|
1039 |
+
|
1040 |
+
|
1041 |
+
class ExtensionAttribute(Expr):
|
1042 |
+
"""Returns the attribute of an extension bound to the environment.
|
1043 |
+
The identifier is the identifier of the :class:`Extension`.
|
1044 |
+
|
1045 |
+
This node is usually constructed by calling the
|
1046 |
+
:meth:`~jinja2.ext.Extension.attr` method on an extension.
|
1047 |
+
"""
|
1048 |
+
|
1049 |
+
fields = ("identifier", "name")
|
1050 |
+
identifier: str
|
1051 |
+
name: str
|
1052 |
+
|
1053 |
+
|
1054 |
+
class ImportedName(Expr):
|
1055 |
+
"""If created with an import name the import name is returned on node
|
1056 |
+
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
|
1057 |
+
function from the cgi module on evaluation. Imports are optimized by the
|
1058 |
+
compiler so there is no need to assign them to local variables.
|
1059 |
+
"""
|
1060 |
+
|
1061 |
+
fields = ("importname",)
|
1062 |
+
importname: str
|
1063 |
+
|
1064 |
+
|
1065 |
+
class InternalName(Expr):
|
1066 |
+
"""An internal name in the compiler. You cannot create these nodes
|
1067 |
+
yourself but the parser provides a
|
1068 |
+
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
|
1069 |
+
a new identifier for you. This identifier is not available from the
|
1070 |
+
template and is not treated specially by the compiler.
|
1071 |
+
"""
|
1072 |
+
|
1073 |
+
fields = ("name",)
|
1074 |
+
name: str
|
1075 |
+
|
1076 |
+
def __init__(self) -> None:
|
1077 |
+
raise TypeError(
|
1078 |
+
"Can't create internal names. Use the "
|
1079 |
+
"`free_identifier` method on a parser."
|
1080 |
+
)
|
1081 |
+
|
1082 |
+
|
1083 |
+
class MarkSafe(Expr):
|
1084 |
+
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
|
1085 |
+
|
1086 |
+
fields = ("expr",)
|
1087 |
+
expr: Expr
|
1088 |
+
|
1089 |
+
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
|
1090 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
1091 |
+
return Markup(self.expr.as_const(eval_ctx))
|
1092 |
+
|
1093 |
+
|
1094 |
+
class MarkSafeIfAutoescape(Expr):
|
1095 |
+
"""Mark the wrapped expression as safe (wrap it as `Markup`) but
|
1096 |
+
only if autoescaping is active.
|
1097 |
+
|
1098 |
+
.. versionadded:: 2.5
|
1099 |
+
"""
|
1100 |
+
|
1101 |
+
fields = ("expr",)
|
1102 |
+
expr: Expr
|
1103 |
+
|
1104 |
+
def as_const(
|
1105 |
+
self, eval_ctx: t.Optional[EvalContext] = None
|
1106 |
+
) -> t.Union[Markup, t.Any]:
|
1107 |
+
eval_ctx = get_eval_context(self, eval_ctx)
|
1108 |
+
if eval_ctx.volatile:
|
1109 |
+
raise Impossible()
|
1110 |
+
expr = self.expr.as_const(eval_ctx)
|
1111 |
+
if eval_ctx.autoescape:
|
1112 |
+
return Markup(expr)
|
1113 |
+
return expr
|
1114 |
+
|
1115 |
+
|
1116 |
+
class ContextReference(Expr):
|
1117 |
+
"""Returns the current template context. It can be used like a
|
1118 |
+
:class:`Name` node, with a ``'load'`` ctx and will return the
|
1119 |
+
current :class:`~jinja2.runtime.Context` object.
|
1120 |
+
|
1121 |
+
Here an example that assigns the current template name to a
|
1122 |
+
variable named `foo`::
|
1123 |
+
|
1124 |
+
Assign(Name('foo', ctx='store'),
|
1125 |
+
Getattr(ContextReference(), 'name'))
|
1126 |
+
|
1127 |
+
This is basically equivalent to using the
|
1128 |
+
:func:`~jinja2.pass_context` decorator when using the high-level
|
1129 |
+
API, which causes a reference to the context to be passed as the
|
1130 |
+
first argument to a function.
|
1131 |
+
"""
|
1132 |
+
|
1133 |
+
|
1134 |
+
class DerivedContextReference(Expr):
|
1135 |
+
"""Return the current template context including locals. Behaves
|
1136 |
+
exactly like :class:`ContextReference`, but includes local
|
1137 |
+
variables, such as from a ``for`` loop.
|
1138 |
+
|
1139 |
+
.. versionadded:: 2.11
|
1140 |
+
"""
|
1141 |
+
|
1142 |
+
|
1143 |
+
class Continue(Stmt):
|
1144 |
+
"""Continue a loop."""
|
1145 |
+
|
1146 |
+
|
1147 |
+
class Break(Stmt):
|
1148 |
+
"""Break a loop."""
|
1149 |
+
|
1150 |
+
|
1151 |
+
class Scope(Stmt):
|
1152 |
+
"""An artificial scope."""
|
1153 |
+
|
1154 |
+
fields = ("body",)
|
1155 |
+
body: t.List[Node]
|
1156 |
+
|
1157 |
+
|
1158 |
+
class OverlayScope(Stmt):
|
1159 |
+
"""An overlay scope for extensions. This is a largely unoptimized scope
|
1160 |
+
that however can be used to introduce completely arbitrary variables into
|
1161 |
+
a sub scope from a dictionary or dictionary like object. The `context`
|
1162 |
+
field has to evaluate to a dictionary object.
|
1163 |
+
|
1164 |
+
Example usage::
|
1165 |
+
|
1166 |
+
OverlayScope(context=self.call_method('get_context'),
|
1167 |
+
body=[...])
|
1168 |
+
|
1169 |
+
.. versionadded:: 2.10
|
1170 |
+
"""
|
1171 |
+
|
1172 |
+
fields = ("context", "body")
|
1173 |
+
context: Expr
|
1174 |
+
body: t.List[Node]
|
1175 |
+
|
1176 |
+
|
1177 |
+
class EvalContextModifier(Stmt):
|
1178 |
+
"""Modifies the eval context. For each option that should be modified,
|
1179 |
+
a :class:`Keyword` has to be added to the :attr:`options` list.
|
1180 |
+
|
1181 |
+
Example to change the `autoescape` setting::
|
1182 |
+
|
1183 |
+
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
|
1184 |
+
"""
|
1185 |
+
|
1186 |
+
fields = ("options",)
|
1187 |
+
options: t.List[Keyword]
|
1188 |
+
|
1189 |
+
|
1190 |
+
class ScopedEvalContextModifier(EvalContextModifier):
|
1191 |
+
"""Modifies the eval context and reverts it later. Works exactly like
|
1192 |
+
:class:`EvalContextModifier` but will only modify the
|
1193 |
+
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
|
1194 |
+
"""
|
1195 |
+
|
1196 |
+
fields = ("body",)
|
1197 |
+
body: t.List[Node]
|
1198 |
+
|
1199 |
+
|
1200 |
+
# make sure nobody creates custom nodes
|
1201 |
+
def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
|
1202 |
+
raise TypeError("can't create custom node types")
|
1203 |
+
|
1204 |
+
|
1205 |
+
NodeType.__new__ = staticmethod(_failing_new) # type: ignore
|
1206 |
+
del _failing_new
|
llmeval-env/lib/python3.10/site-packages/jinja2/optimizer.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The optimizer tries to constant fold expressions and modify the AST
|
2 |
+
in place so that it should be faster to evaluate.
|
3 |
+
|
4 |
+
Because the AST does not contain all the scoping information and the
|
5 |
+
compiler has to find that out, we cannot do all the optimizations we
|
6 |
+
want. For example, loop unrolling doesn't work because unrolled loops
|
7 |
+
would have a different scope. The solution would be a second syntax tree
|
8 |
+
that stored the scoping rules.
|
9 |
+
"""
|
10 |
+
|
11 |
+
import typing as t
|
12 |
+
|
13 |
+
from . import nodes
|
14 |
+
from .visitor import NodeTransformer
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
from .environment import Environment
|
18 |
+
|
19 |
+
|
20 |
+
def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node:
|
21 |
+
"""The context hint can be used to perform an static optimization
|
22 |
+
based on the context given."""
|
23 |
+
optimizer = Optimizer(environment)
|
24 |
+
return t.cast(nodes.Node, optimizer.visit(node))
|
25 |
+
|
26 |
+
|
27 |
+
class Optimizer(NodeTransformer):
|
28 |
+
def __init__(self, environment: "t.Optional[Environment]") -> None:
|
29 |
+
self.environment = environment
|
30 |
+
|
31 |
+
def generic_visit(
|
32 |
+
self, node: nodes.Node, *args: t.Any, **kwargs: t.Any
|
33 |
+
) -> nodes.Node:
|
34 |
+
node = super().generic_visit(node, *args, **kwargs)
|
35 |
+
|
36 |
+
# Do constant folding. Some other nodes besides Expr have
|
37 |
+
# as_const, but folding them causes errors later on.
|
38 |
+
if isinstance(node, nodes.Expr):
|
39 |
+
try:
|
40 |
+
return nodes.Const.from_untrusted(
|
41 |
+
node.as_const(args[0] if args else None),
|
42 |
+
lineno=node.lineno,
|
43 |
+
environment=self.environment,
|
44 |
+
)
|
45 |
+
except nodes.Impossible:
|
46 |
+
pass
|
47 |
+
|
48 |
+
return node
|
llmeval-env/lib/python3.10/site-packages/jinja2/parser.py
ADDED
@@ -0,0 +1,1041 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Parse tokens from the lexer into nodes for the compiler."""
|
2 |
+
|
3 |
+
import typing
|
4 |
+
import typing as t
|
5 |
+
|
6 |
+
from . import nodes
|
7 |
+
from .exceptions import TemplateAssertionError
|
8 |
+
from .exceptions import TemplateSyntaxError
|
9 |
+
from .lexer import describe_token
|
10 |
+
from .lexer import describe_token_expr
|
11 |
+
|
12 |
+
if t.TYPE_CHECKING:
|
13 |
+
import typing_extensions as te
|
14 |
+
|
15 |
+
from .environment import Environment
|
16 |
+
|
17 |
+
_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)
|
18 |
+
_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)
|
19 |
+
|
20 |
+
_statement_keywords = frozenset(
|
21 |
+
[
|
22 |
+
"for",
|
23 |
+
"if",
|
24 |
+
"block",
|
25 |
+
"extends",
|
26 |
+
"print",
|
27 |
+
"macro",
|
28 |
+
"include",
|
29 |
+
"from",
|
30 |
+
"import",
|
31 |
+
"set",
|
32 |
+
"with",
|
33 |
+
"autoescape",
|
34 |
+
]
|
35 |
+
)
|
36 |
+
_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])
|
37 |
+
|
38 |
+
_math_nodes: t.Dict[str, t.Type[nodes.Expr]] = {
|
39 |
+
"add": nodes.Add,
|
40 |
+
"sub": nodes.Sub,
|
41 |
+
"mul": nodes.Mul,
|
42 |
+
"div": nodes.Div,
|
43 |
+
"floordiv": nodes.FloorDiv,
|
44 |
+
"mod": nodes.Mod,
|
45 |
+
}
|
46 |
+
|
47 |
+
|
48 |
+
class Parser:
|
49 |
+
"""This is the central parsing class Jinja uses. It's passed to
|
50 |
+
extensions and can be used to parse expressions or statements.
|
51 |
+
"""
|
52 |
+
|
53 |
+
def __init__(
|
54 |
+
self,
|
55 |
+
environment: "Environment",
|
56 |
+
source: str,
|
57 |
+
name: t.Optional[str] = None,
|
58 |
+
filename: t.Optional[str] = None,
|
59 |
+
state: t.Optional[str] = None,
|
60 |
+
) -> None:
|
61 |
+
self.environment = environment
|
62 |
+
self.stream = environment._tokenize(source, name, filename, state)
|
63 |
+
self.name = name
|
64 |
+
self.filename = filename
|
65 |
+
self.closed = False
|
66 |
+
self.extensions: t.Dict[
|
67 |
+
str, t.Callable[["Parser"], t.Union[nodes.Node, t.List[nodes.Node]]]
|
68 |
+
] = {}
|
69 |
+
for extension in environment.iter_extensions():
|
70 |
+
for tag in extension.tags:
|
71 |
+
self.extensions[tag] = extension.parse
|
72 |
+
self._last_identifier = 0
|
73 |
+
self._tag_stack: t.List[str] = []
|
74 |
+
self._end_token_stack: t.List[t.Tuple[str, ...]] = []
|
75 |
+
|
76 |
+
def fail(
|
77 |
+
self,
|
78 |
+
msg: str,
|
79 |
+
lineno: t.Optional[int] = None,
|
80 |
+
exc: t.Type[TemplateSyntaxError] = TemplateSyntaxError,
|
81 |
+
) -> "te.NoReturn":
|
82 |
+
"""Convenience method that raises `exc` with the message, passed
|
83 |
+
line number or last line number as well as the current name and
|
84 |
+
filename.
|
85 |
+
"""
|
86 |
+
if lineno is None:
|
87 |
+
lineno = self.stream.current.lineno
|
88 |
+
raise exc(msg, lineno, self.name, self.filename)
|
89 |
+
|
90 |
+
def _fail_ut_eof(
|
91 |
+
self,
|
92 |
+
name: t.Optional[str],
|
93 |
+
end_token_stack: t.List[t.Tuple[str, ...]],
|
94 |
+
lineno: t.Optional[int],
|
95 |
+
) -> "te.NoReturn":
|
96 |
+
expected: t.Set[str] = set()
|
97 |
+
for exprs in end_token_stack:
|
98 |
+
expected.update(map(describe_token_expr, exprs))
|
99 |
+
if end_token_stack:
|
100 |
+
currently_looking: t.Optional[str] = " or ".join(
|
101 |
+
map(repr, map(describe_token_expr, end_token_stack[-1]))
|
102 |
+
)
|
103 |
+
else:
|
104 |
+
currently_looking = None
|
105 |
+
|
106 |
+
if name is None:
|
107 |
+
message = ["Unexpected end of template."]
|
108 |
+
else:
|
109 |
+
message = [f"Encountered unknown tag {name!r}."]
|
110 |
+
|
111 |
+
if currently_looking:
|
112 |
+
if name is not None and name in expected:
|
113 |
+
message.append(
|
114 |
+
"You probably made a nesting mistake. Jinja is expecting this tag,"
|
115 |
+
f" but currently looking for {currently_looking}."
|
116 |
+
)
|
117 |
+
else:
|
118 |
+
message.append(
|
119 |
+
f"Jinja was looking for the following tags: {currently_looking}."
|
120 |
+
)
|
121 |
+
|
122 |
+
if self._tag_stack:
|
123 |
+
message.append(
|
124 |
+
"The innermost block that needs to be closed is"
|
125 |
+
f" {self._tag_stack[-1]!r}."
|
126 |
+
)
|
127 |
+
|
128 |
+
self.fail(" ".join(message), lineno)
|
129 |
+
|
130 |
+
def fail_unknown_tag(
|
131 |
+
self, name: str, lineno: t.Optional[int] = None
|
132 |
+
) -> "te.NoReturn":
|
133 |
+
"""Called if the parser encounters an unknown tag. Tries to fail
|
134 |
+
with a human readable error message that could help to identify
|
135 |
+
the problem.
|
136 |
+
"""
|
137 |
+
self._fail_ut_eof(name, self._end_token_stack, lineno)
|
138 |
+
|
139 |
+
def fail_eof(
|
140 |
+
self,
|
141 |
+
end_tokens: t.Optional[t.Tuple[str, ...]] = None,
|
142 |
+
lineno: t.Optional[int] = None,
|
143 |
+
) -> "te.NoReturn":
|
144 |
+
"""Like fail_unknown_tag but for end of template situations."""
|
145 |
+
stack = list(self._end_token_stack)
|
146 |
+
if end_tokens is not None:
|
147 |
+
stack.append(end_tokens)
|
148 |
+
self._fail_ut_eof(None, stack, lineno)
|
149 |
+
|
150 |
+
def is_tuple_end(
|
151 |
+
self, extra_end_rules: t.Optional[t.Tuple[str, ...]] = None
|
152 |
+
) -> bool:
|
153 |
+
"""Are we at the end of a tuple?"""
|
154 |
+
if self.stream.current.type in ("variable_end", "block_end", "rparen"):
|
155 |
+
return True
|
156 |
+
elif extra_end_rules is not None:
|
157 |
+
return self.stream.current.test_any(extra_end_rules) # type: ignore
|
158 |
+
return False
|
159 |
+
|
160 |
+
def free_identifier(self, lineno: t.Optional[int] = None) -> nodes.InternalName:
|
161 |
+
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
|
162 |
+
self._last_identifier += 1
|
163 |
+
rv = object.__new__(nodes.InternalName)
|
164 |
+
nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)
|
165 |
+
return rv
|
166 |
+
|
167 |
+
def parse_statement(self) -> t.Union[nodes.Node, t.List[nodes.Node]]:
|
168 |
+
"""Parse a single statement."""
|
169 |
+
token = self.stream.current
|
170 |
+
if token.type != "name":
|
171 |
+
self.fail("tag name expected", token.lineno)
|
172 |
+
self._tag_stack.append(token.value)
|
173 |
+
pop_tag = True
|
174 |
+
try:
|
175 |
+
if token.value in _statement_keywords:
|
176 |
+
f = getattr(self, f"parse_{self.stream.current.value}")
|
177 |
+
return f() # type: ignore
|
178 |
+
if token.value == "call":
|
179 |
+
return self.parse_call_block()
|
180 |
+
if token.value == "filter":
|
181 |
+
return self.parse_filter_block()
|
182 |
+
ext = self.extensions.get(token.value)
|
183 |
+
if ext is not None:
|
184 |
+
return ext(self)
|
185 |
+
|
186 |
+
# did not work out, remove the token we pushed by accident
|
187 |
+
# from the stack so that the unknown tag fail function can
|
188 |
+
# produce a proper error message.
|
189 |
+
self._tag_stack.pop()
|
190 |
+
pop_tag = False
|
191 |
+
self.fail_unknown_tag(token.value, token.lineno)
|
192 |
+
finally:
|
193 |
+
if pop_tag:
|
194 |
+
self._tag_stack.pop()
|
195 |
+
|
196 |
+
def parse_statements(
|
197 |
+
self, end_tokens: t.Tuple[str, ...], drop_needle: bool = False
|
198 |
+
) -> t.List[nodes.Node]:
|
199 |
+
"""Parse multiple statements into a list until one of the end tokens
|
200 |
+
is reached. This is used to parse the body of statements as it also
|
201 |
+
parses template data if appropriate. The parser checks first if the
|
202 |
+
current token is a colon and skips it if there is one. Then it checks
|
203 |
+
for the block end and parses until if one of the `end_tokens` is
|
204 |
+
reached. Per default the active token in the stream at the end of
|
205 |
+
the call is the matched end token. If this is not wanted `drop_needle`
|
206 |
+
can be set to `True` and the end token is removed.
|
207 |
+
"""
|
208 |
+
# the first token may be a colon for python compatibility
|
209 |
+
self.stream.skip_if("colon")
|
210 |
+
|
211 |
+
# in the future it would be possible to add whole code sections
|
212 |
+
# by adding some sort of end of statement token and parsing those here.
|
213 |
+
self.stream.expect("block_end")
|
214 |
+
result = self.subparse(end_tokens)
|
215 |
+
|
216 |
+
# we reached the end of the template too early, the subparser
|
217 |
+
# does not check for this, so we do that now
|
218 |
+
if self.stream.current.type == "eof":
|
219 |
+
self.fail_eof(end_tokens)
|
220 |
+
|
221 |
+
if drop_needle:
|
222 |
+
next(self.stream)
|
223 |
+
return result
|
224 |
+
|
225 |
+
def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:
|
226 |
+
"""Parse an assign statement."""
|
227 |
+
lineno = next(self.stream).lineno
|
228 |
+
target = self.parse_assign_target(with_namespace=True)
|
229 |
+
if self.stream.skip_if("assign"):
|
230 |
+
expr = self.parse_tuple()
|
231 |
+
return nodes.Assign(target, expr, lineno=lineno)
|
232 |
+
filter_node = self.parse_filter(None)
|
233 |
+
body = self.parse_statements(("name:endset",), drop_needle=True)
|
234 |
+
return nodes.AssignBlock(target, filter_node, body, lineno=lineno)
|
235 |
+
|
236 |
+
def parse_for(self) -> nodes.For:
|
237 |
+
"""Parse a for loop."""
|
238 |
+
lineno = self.stream.expect("name:for").lineno
|
239 |
+
target = self.parse_assign_target(extra_end_rules=("name:in",))
|
240 |
+
self.stream.expect("name:in")
|
241 |
+
iter = self.parse_tuple(
|
242 |
+
with_condexpr=False, extra_end_rules=("name:recursive",)
|
243 |
+
)
|
244 |
+
test = None
|
245 |
+
if self.stream.skip_if("name:if"):
|
246 |
+
test = self.parse_expression()
|
247 |
+
recursive = self.stream.skip_if("name:recursive")
|
248 |
+
body = self.parse_statements(("name:endfor", "name:else"))
|
249 |
+
if next(self.stream).value == "endfor":
|
250 |
+
else_ = []
|
251 |
+
else:
|
252 |
+
else_ = self.parse_statements(("name:endfor",), drop_needle=True)
|
253 |
+
return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)
|
254 |
+
|
255 |
+
def parse_if(self) -> nodes.If:
|
256 |
+
"""Parse an if construct."""
|
257 |
+
node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)
|
258 |
+
while True:
|
259 |
+
node.test = self.parse_tuple(with_condexpr=False)
|
260 |
+
node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))
|
261 |
+
node.elif_ = []
|
262 |
+
node.else_ = []
|
263 |
+
token = next(self.stream)
|
264 |
+
if token.test("name:elif"):
|
265 |
+
node = nodes.If(lineno=self.stream.current.lineno)
|
266 |
+
result.elif_.append(node)
|
267 |
+
continue
|
268 |
+
elif token.test("name:else"):
|
269 |
+
result.else_ = self.parse_statements(("name:endif",), drop_needle=True)
|
270 |
+
break
|
271 |
+
return result
|
272 |
+
|
273 |
+
def parse_with(self) -> nodes.With:
|
274 |
+
node = nodes.With(lineno=next(self.stream).lineno)
|
275 |
+
targets: t.List[nodes.Expr] = []
|
276 |
+
values: t.List[nodes.Expr] = []
|
277 |
+
while self.stream.current.type != "block_end":
|
278 |
+
if targets:
|
279 |
+
self.stream.expect("comma")
|
280 |
+
target = self.parse_assign_target()
|
281 |
+
target.set_ctx("param")
|
282 |
+
targets.append(target)
|
283 |
+
self.stream.expect("assign")
|
284 |
+
values.append(self.parse_expression())
|
285 |
+
node.targets = targets
|
286 |
+
node.values = values
|
287 |
+
node.body = self.parse_statements(("name:endwith",), drop_needle=True)
|
288 |
+
return node
|
289 |
+
|
290 |
+
def parse_autoescape(self) -> nodes.Scope:
|
291 |
+
node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)
|
292 |
+
node.options = [nodes.Keyword("autoescape", self.parse_expression())]
|
293 |
+
node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)
|
294 |
+
return nodes.Scope([node])
|
295 |
+
|
296 |
+
def parse_block(self) -> nodes.Block:
|
297 |
+
node = nodes.Block(lineno=next(self.stream).lineno)
|
298 |
+
node.name = self.stream.expect("name").value
|
299 |
+
node.scoped = self.stream.skip_if("name:scoped")
|
300 |
+
node.required = self.stream.skip_if("name:required")
|
301 |
+
|
302 |
+
# common problem people encounter when switching from django
|
303 |
+
# to jinja. we do not support hyphens in block names, so let's
|
304 |
+
# raise a nicer error message in that case.
|
305 |
+
if self.stream.current.type == "sub":
|
306 |
+
self.fail(
|
307 |
+
"Block names in Jinja have to be valid Python identifiers and may not"
|
308 |
+
" contain hyphens, use an underscore instead."
|
309 |
+
)
|
310 |
+
|
311 |
+
node.body = self.parse_statements(("name:endblock",), drop_needle=True)
|
312 |
+
|
313 |
+
# enforce that required blocks only contain whitespace or comments
|
314 |
+
# by asserting that the body, if not empty, is just TemplateData nodes
|
315 |
+
# with whitespace data
|
316 |
+
if node.required:
|
317 |
+
for body_node in node.body:
|
318 |
+
if not isinstance(body_node, nodes.Output) or any(
|
319 |
+
not isinstance(output_node, nodes.TemplateData)
|
320 |
+
or not output_node.data.isspace()
|
321 |
+
for output_node in body_node.nodes
|
322 |
+
):
|
323 |
+
self.fail("Required blocks can only contain comments or whitespace")
|
324 |
+
|
325 |
+
self.stream.skip_if("name:" + node.name)
|
326 |
+
return node
|
327 |
+
|
328 |
+
def parse_extends(self) -> nodes.Extends:
|
329 |
+
node = nodes.Extends(lineno=next(self.stream).lineno)
|
330 |
+
node.template = self.parse_expression()
|
331 |
+
return node
|
332 |
+
|
333 |
+
def parse_import_context(
|
334 |
+
self, node: _ImportInclude, default: bool
|
335 |
+
) -> _ImportInclude:
|
336 |
+
if self.stream.current.test_any(
|
337 |
+
"name:with", "name:without"
|
338 |
+
) and self.stream.look().test("name:context"):
|
339 |
+
node.with_context = next(self.stream).value == "with"
|
340 |
+
self.stream.skip()
|
341 |
+
else:
|
342 |
+
node.with_context = default
|
343 |
+
return node
|
344 |
+
|
345 |
+
def parse_include(self) -> nodes.Include:
|
346 |
+
node = nodes.Include(lineno=next(self.stream).lineno)
|
347 |
+
node.template = self.parse_expression()
|
348 |
+
if self.stream.current.test("name:ignore") and self.stream.look().test(
|
349 |
+
"name:missing"
|
350 |
+
):
|
351 |
+
node.ignore_missing = True
|
352 |
+
self.stream.skip(2)
|
353 |
+
else:
|
354 |
+
node.ignore_missing = False
|
355 |
+
return self.parse_import_context(node, True)
|
356 |
+
|
357 |
+
def parse_import(self) -> nodes.Import:
|
358 |
+
node = nodes.Import(lineno=next(self.stream).lineno)
|
359 |
+
node.template = self.parse_expression()
|
360 |
+
self.stream.expect("name:as")
|
361 |
+
node.target = self.parse_assign_target(name_only=True).name
|
362 |
+
return self.parse_import_context(node, False)
|
363 |
+
|
364 |
+
def parse_from(self) -> nodes.FromImport:
|
365 |
+
node = nodes.FromImport(lineno=next(self.stream).lineno)
|
366 |
+
node.template = self.parse_expression()
|
367 |
+
self.stream.expect("name:import")
|
368 |
+
node.names = []
|
369 |
+
|
370 |
+
def parse_context() -> bool:
|
371 |
+
if self.stream.current.value in {
|
372 |
+
"with",
|
373 |
+
"without",
|
374 |
+
} and self.stream.look().test("name:context"):
|
375 |
+
node.with_context = next(self.stream).value == "with"
|
376 |
+
self.stream.skip()
|
377 |
+
return True
|
378 |
+
return False
|
379 |
+
|
380 |
+
while True:
|
381 |
+
if node.names:
|
382 |
+
self.stream.expect("comma")
|
383 |
+
if self.stream.current.type == "name":
|
384 |
+
if parse_context():
|
385 |
+
break
|
386 |
+
target = self.parse_assign_target(name_only=True)
|
387 |
+
if target.name.startswith("_"):
|
388 |
+
self.fail(
|
389 |
+
"names starting with an underline can not be imported",
|
390 |
+
target.lineno,
|
391 |
+
exc=TemplateAssertionError,
|
392 |
+
)
|
393 |
+
if self.stream.skip_if("name:as"):
|
394 |
+
alias = self.parse_assign_target(name_only=True)
|
395 |
+
node.names.append((target.name, alias.name))
|
396 |
+
else:
|
397 |
+
node.names.append(target.name)
|
398 |
+
if parse_context() or self.stream.current.type != "comma":
|
399 |
+
break
|
400 |
+
else:
|
401 |
+
self.stream.expect("name")
|
402 |
+
if not hasattr(node, "with_context"):
|
403 |
+
node.with_context = False
|
404 |
+
return node
|
405 |
+
|
406 |
+
def parse_signature(self, node: _MacroCall) -> None:
|
407 |
+
args = node.args = []
|
408 |
+
defaults = node.defaults = []
|
409 |
+
self.stream.expect("lparen")
|
410 |
+
while self.stream.current.type != "rparen":
|
411 |
+
if args:
|
412 |
+
self.stream.expect("comma")
|
413 |
+
arg = self.parse_assign_target(name_only=True)
|
414 |
+
arg.set_ctx("param")
|
415 |
+
if self.stream.skip_if("assign"):
|
416 |
+
defaults.append(self.parse_expression())
|
417 |
+
elif defaults:
|
418 |
+
self.fail("non-default argument follows default argument")
|
419 |
+
args.append(arg)
|
420 |
+
self.stream.expect("rparen")
|
421 |
+
|
422 |
+
def parse_call_block(self) -> nodes.CallBlock:
|
423 |
+
node = nodes.CallBlock(lineno=next(self.stream).lineno)
|
424 |
+
if self.stream.current.type == "lparen":
|
425 |
+
self.parse_signature(node)
|
426 |
+
else:
|
427 |
+
node.args = []
|
428 |
+
node.defaults = []
|
429 |
+
|
430 |
+
call_node = self.parse_expression()
|
431 |
+
if not isinstance(call_node, nodes.Call):
|
432 |
+
self.fail("expected call", node.lineno)
|
433 |
+
node.call = call_node
|
434 |
+
node.body = self.parse_statements(("name:endcall",), drop_needle=True)
|
435 |
+
return node
|
436 |
+
|
437 |
+
def parse_filter_block(self) -> nodes.FilterBlock:
|
438 |
+
node = nodes.FilterBlock(lineno=next(self.stream).lineno)
|
439 |
+
node.filter = self.parse_filter(None, start_inline=True) # type: ignore
|
440 |
+
node.body = self.parse_statements(("name:endfilter",), drop_needle=True)
|
441 |
+
return node
|
442 |
+
|
443 |
+
def parse_macro(self) -> nodes.Macro:
|
444 |
+
node = nodes.Macro(lineno=next(self.stream).lineno)
|
445 |
+
node.name = self.parse_assign_target(name_only=True).name
|
446 |
+
self.parse_signature(node)
|
447 |
+
node.body = self.parse_statements(("name:endmacro",), drop_needle=True)
|
448 |
+
return node
|
449 |
+
|
450 |
+
def parse_print(self) -> nodes.Output:
|
451 |
+
node = nodes.Output(lineno=next(self.stream).lineno)
|
452 |
+
node.nodes = []
|
453 |
+
while self.stream.current.type != "block_end":
|
454 |
+
if node.nodes:
|
455 |
+
self.stream.expect("comma")
|
456 |
+
node.nodes.append(self.parse_expression())
|
457 |
+
return node
|
458 |
+
|
459 |
+
@typing.overload
|
460 |
+
def parse_assign_target(
|
461 |
+
self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...
|
462 |
+
) -> nodes.Name: ...
|
463 |
+
|
464 |
+
@typing.overload
|
465 |
+
def parse_assign_target(
|
466 |
+
self,
|
467 |
+
with_tuple: bool = True,
|
468 |
+
name_only: bool = False,
|
469 |
+
extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,
|
470 |
+
with_namespace: bool = False,
|
471 |
+
) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...
|
472 |
+
|
473 |
+
def parse_assign_target(
|
474 |
+
self,
|
475 |
+
with_tuple: bool = True,
|
476 |
+
name_only: bool = False,
|
477 |
+
extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,
|
478 |
+
with_namespace: bool = False,
|
479 |
+
) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:
|
480 |
+
"""Parse an assignment target. As Jinja allows assignments to
|
481 |
+
tuples, this function can parse all allowed assignment targets. Per
|
482 |
+
default assignments to tuples are parsed, that can be disable however
|
483 |
+
by setting `with_tuple` to `False`. If only assignments to names are
|
484 |
+
wanted `name_only` can be set to `True`. The `extra_end_rules`
|
485 |
+
parameter is forwarded to the tuple parsing function. If
|
486 |
+
`with_namespace` is enabled, a namespace assignment may be parsed.
|
487 |
+
"""
|
488 |
+
target: nodes.Expr
|
489 |
+
|
490 |
+
if with_namespace and self.stream.look().type == "dot":
|
491 |
+
token = self.stream.expect("name")
|
492 |
+
next(self.stream) # dot
|
493 |
+
attr = self.stream.expect("name")
|
494 |
+
target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)
|
495 |
+
elif name_only:
|
496 |
+
token = self.stream.expect("name")
|
497 |
+
target = nodes.Name(token.value, "store", lineno=token.lineno)
|
498 |
+
else:
|
499 |
+
if with_tuple:
|
500 |
+
target = self.parse_tuple(
|
501 |
+
simplified=True, extra_end_rules=extra_end_rules
|
502 |
+
)
|
503 |
+
else:
|
504 |
+
target = self.parse_primary()
|
505 |
+
|
506 |
+
target.set_ctx("store")
|
507 |
+
|
508 |
+
if not target.can_assign():
|
509 |
+
self.fail(
|
510 |
+
f"can't assign to {type(target).__name__.lower()!r}", target.lineno
|
511 |
+
)
|
512 |
+
|
513 |
+
return target # type: ignore
|
514 |
+
|
515 |
+
def parse_expression(self, with_condexpr: bool = True) -> nodes.Expr:
|
516 |
+
"""Parse an expression. Per default all expressions are parsed, if
|
517 |
+
the optional `with_condexpr` parameter is set to `False` conditional
|
518 |
+
expressions are not parsed.
|
519 |
+
"""
|
520 |
+
if with_condexpr:
|
521 |
+
return self.parse_condexpr()
|
522 |
+
return self.parse_or()
|
523 |
+
|
524 |
+
def parse_condexpr(self) -> nodes.Expr:
|
525 |
+
lineno = self.stream.current.lineno
|
526 |
+
expr1 = self.parse_or()
|
527 |
+
expr3: t.Optional[nodes.Expr]
|
528 |
+
|
529 |
+
while self.stream.skip_if("name:if"):
|
530 |
+
expr2 = self.parse_or()
|
531 |
+
if self.stream.skip_if("name:else"):
|
532 |
+
expr3 = self.parse_condexpr()
|
533 |
+
else:
|
534 |
+
expr3 = None
|
535 |
+
expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
|
536 |
+
lineno = self.stream.current.lineno
|
537 |
+
return expr1
|
538 |
+
|
539 |
+
def parse_or(self) -> nodes.Expr:
|
540 |
+
lineno = self.stream.current.lineno
|
541 |
+
left = self.parse_and()
|
542 |
+
while self.stream.skip_if("name:or"):
|
543 |
+
right = self.parse_and()
|
544 |
+
left = nodes.Or(left, right, lineno=lineno)
|
545 |
+
lineno = self.stream.current.lineno
|
546 |
+
return left
|
547 |
+
|
548 |
+
def parse_and(self) -> nodes.Expr:
|
549 |
+
lineno = self.stream.current.lineno
|
550 |
+
left = self.parse_not()
|
551 |
+
while self.stream.skip_if("name:and"):
|
552 |
+
right = self.parse_not()
|
553 |
+
left = nodes.And(left, right, lineno=lineno)
|
554 |
+
lineno = self.stream.current.lineno
|
555 |
+
return left
|
556 |
+
|
557 |
+
def parse_not(self) -> nodes.Expr:
|
558 |
+
if self.stream.current.test("name:not"):
|
559 |
+
lineno = next(self.stream).lineno
|
560 |
+
return nodes.Not(self.parse_not(), lineno=lineno)
|
561 |
+
return self.parse_compare()
|
562 |
+
|
563 |
+
def parse_compare(self) -> nodes.Expr:
|
564 |
+
lineno = self.stream.current.lineno
|
565 |
+
expr = self.parse_math1()
|
566 |
+
ops = []
|
567 |
+
while True:
|
568 |
+
token_type = self.stream.current.type
|
569 |
+
if token_type in _compare_operators:
|
570 |
+
next(self.stream)
|
571 |
+
ops.append(nodes.Operand(token_type, self.parse_math1()))
|
572 |
+
elif self.stream.skip_if("name:in"):
|
573 |
+
ops.append(nodes.Operand("in", self.parse_math1()))
|
574 |
+
elif self.stream.current.test("name:not") and self.stream.look().test(
|
575 |
+
"name:in"
|
576 |
+
):
|
577 |
+
self.stream.skip(2)
|
578 |
+
ops.append(nodes.Operand("notin", self.parse_math1()))
|
579 |
+
else:
|
580 |
+
break
|
581 |
+
lineno = self.stream.current.lineno
|
582 |
+
if not ops:
|
583 |
+
return expr
|
584 |
+
return nodes.Compare(expr, ops, lineno=lineno)
|
585 |
+
|
586 |
+
def parse_math1(self) -> nodes.Expr:
|
587 |
+
lineno = self.stream.current.lineno
|
588 |
+
left = self.parse_concat()
|
589 |
+
while self.stream.current.type in ("add", "sub"):
|
590 |
+
cls = _math_nodes[self.stream.current.type]
|
591 |
+
next(self.stream)
|
592 |
+
right = self.parse_concat()
|
593 |
+
left = cls(left, right, lineno=lineno)
|
594 |
+
lineno = self.stream.current.lineno
|
595 |
+
return left
|
596 |
+
|
597 |
+
def parse_concat(self) -> nodes.Expr:
|
598 |
+
lineno = self.stream.current.lineno
|
599 |
+
args = [self.parse_math2()]
|
600 |
+
while self.stream.current.type == "tilde":
|
601 |
+
next(self.stream)
|
602 |
+
args.append(self.parse_math2())
|
603 |
+
if len(args) == 1:
|
604 |
+
return args[0]
|
605 |
+
return nodes.Concat(args, lineno=lineno)
|
606 |
+
|
607 |
+
def parse_math2(self) -> nodes.Expr:
|
608 |
+
lineno = self.stream.current.lineno
|
609 |
+
left = self.parse_pow()
|
610 |
+
while self.stream.current.type in ("mul", "div", "floordiv", "mod"):
|
611 |
+
cls = _math_nodes[self.stream.current.type]
|
612 |
+
next(self.stream)
|
613 |
+
right = self.parse_pow()
|
614 |
+
left = cls(left, right, lineno=lineno)
|
615 |
+
lineno = self.stream.current.lineno
|
616 |
+
return left
|
617 |
+
|
618 |
+
def parse_pow(self) -> nodes.Expr:
|
619 |
+
lineno = self.stream.current.lineno
|
620 |
+
left = self.parse_unary()
|
621 |
+
while self.stream.current.type == "pow":
|
622 |
+
next(self.stream)
|
623 |
+
right = self.parse_unary()
|
624 |
+
left = nodes.Pow(left, right, lineno=lineno)
|
625 |
+
lineno = self.stream.current.lineno
|
626 |
+
return left
|
627 |
+
|
628 |
+
def parse_unary(self, with_filter: bool = True) -> nodes.Expr:
|
629 |
+
token_type = self.stream.current.type
|
630 |
+
lineno = self.stream.current.lineno
|
631 |
+
node: nodes.Expr
|
632 |
+
|
633 |
+
if token_type == "sub":
|
634 |
+
next(self.stream)
|
635 |
+
node = nodes.Neg(self.parse_unary(False), lineno=lineno)
|
636 |
+
elif token_type == "add":
|
637 |
+
next(self.stream)
|
638 |
+
node = nodes.Pos(self.parse_unary(False), lineno=lineno)
|
639 |
+
else:
|
640 |
+
node = self.parse_primary()
|
641 |
+
node = self.parse_postfix(node)
|
642 |
+
if with_filter:
|
643 |
+
node = self.parse_filter_expr(node)
|
644 |
+
return node
|
645 |
+
|
646 |
+
def parse_primary(self) -> nodes.Expr:
|
647 |
+
token = self.stream.current
|
648 |
+
node: nodes.Expr
|
649 |
+
if token.type == "name":
|
650 |
+
if token.value in ("true", "false", "True", "False"):
|
651 |
+
node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)
|
652 |
+
elif token.value in ("none", "None"):
|
653 |
+
node = nodes.Const(None, lineno=token.lineno)
|
654 |
+
else:
|
655 |
+
node = nodes.Name(token.value, "load", lineno=token.lineno)
|
656 |
+
next(self.stream)
|
657 |
+
elif token.type == "string":
|
658 |
+
next(self.stream)
|
659 |
+
buf = [token.value]
|
660 |
+
lineno = token.lineno
|
661 |
+
while self.stream.current.type == "string":
|
662 |
+
buf.append(self.stream.current.value)
|
663 |
+
next(self.stream)
|
664 |
+
node = nodes.Const("".join(buf), lineno=lineno)
|
665 |
+
elif token.type in ("integer", "float"):
|
666 |
+
next(self.stream)
|
667 |
+
node = nodes.Const(token.value, lineno=token.lineno)
|
668 |
+
elif token.type == "lparen":
|
669 |
+
next(self.stream)
|
670 |
+
node = self.parse_tuple(explicit_parentheses=True)
|
671 |
+
self.stream.expect("rparen")
|
672 |
+
elif token.type == "lbracket":
|
673 |
+
node = self.parse_list()
|
674 |
+
elif token.type == "lbrace":
|
675 |
+
node = self.parse_dict()
|
676 |
+
else:
|
677 |
+
self.fail(f"unexpected {describe_token(token)!r}", token.lineno)
|
678 |
+
return node
|
679 |
+
|
680 |
+
def parse_tuple(
|
681 |
+
self,
|
682 |
+
simplified: bool = False,
|
683 |
+
with_condexpr: bool = True,
|
684 |
+
extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,
|
685 |
+
explicit_parentheses: bool = False,
|
686 |
+
) -> t.Union[nodes.Tuple, nodes.Expr]:
|
687 |
+
"""Works like `parse_expression` but if multiple expressions are
|
688 |
+
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
|
689 |
+
This method could also return a regular expression instead of a tuple
|
690 |
+
if no commas where found.
|
691 |
+
|
692 |
+
The default parsing mode is a full tuple. If `simplified` is `True`
|
693 |
+
only names and literals are parsed. The `no_condexpr` parameter is
|
694 |
+
forwarded to :meth:`parse_expression`.
|
695 |
+
|
696 |
+
Because tuples do not require delimiters and may end in a bogus comma
|
697 |
+
an extra hint is needed that marks the end of a tuple. For example
|
698 |
+
for loops support tuples between `for` and `in`. In that case the
|
699 |
+
`extra_end_rules` is set to ``['name:in']``.
|
700 |
+
|
701 |
+
`explicit_parentheses` is true if the parsing was triggered by an
|
702 |
+
expression in parentheses. This is used to figure out if an empty
|
703 |
+
tuple is a valid expression or not.
|
704 |
+
"""
|
705 |
+
lineno = self.stream.current.lineno
|
706 |
+
if simplified:
|
707 |
+
parse = self.parse_primary
|
708 |
+
elif with_condexpr:
|
709 |
+
parse = self.parse_expression
|
710 |
+
else:
|
711 |
+
|
712 |
+
def parse() -> nodes.Expr:
|
713 |
+
return self.parse_expression(with_condexpr=False)
|
714 |
+
|
715 |
+
args: t.List[nodes.Expr] = []
|
716 |
+
is_tuple = False
|
717 |
+
|
718 |
+
while True:
|
719 |
+
if args:
|
720 |
+
self.stream.expect("comma")
|
721 |
+
if self.is_tuple_end(extra_end_rules):
|
722 |
+
break
|
723 |
+
args.append(parse())
|
724 |
+
if self.stream.current.type == "comma":
|
725 |
+
is_tuple = True
|
726 |
+
else:
|
727 |
+
break
|
728 |
+
lineno = self.stream.current.lineno
|
729 |
+
|
730 |
+
if not is_tuple:
|
731 |
+
if args:
|
732 |
+
return args[0]
|
733 |
+
|
734 |
+
# if we don't have explicit parentheses, an empty tuple is
|
735 |
+
# not a valid expression. This would mean nothing (literally
|
736 |
+
# nothing) in the spot of an expression would be an empty
|
737 |
+
# tuple.
|
738 |
+
if not explicit_parentheses:
|
739 |
+
self.fail(
|
740 |
+
"Expected an expression,"
|
741 |
+
f" got {describe_token(self.stream.current)!r}"
|
742 |
+
)
|
743 |
+
|
744 |
+
return nodes.Tuple(args, "load", lineno=lineno)
|
745 |
+
|
746 |
+
def parse_list(self) -> nodes.List:
|
747 |
+
token = self.stream.expect("lbracket")
|
748 |
+
items: t.List[nodes.Expr] = []
|
749 |
+
while self.stream.current.type != "rbracket":
|
750 |
+
if items:
|
751 |
+
self.stream.expect("comma")
|
752 |
+
if self.stream.current.type == "rbracket":
|
753 |
+
break
|
754 |
+
items.append(self.parse_expression())
|
755 |
+
self.stream.expect("rbracket")
|
756 |
+
return nodes.List(items, lineno=token.lineno)
|
757 |
+
|
758 |
+
def parse_dict(self) -> nodes.Dict:
|
759 |
+
token = self.stream.expect("lbrace")
|
760 |
+
items: t.List[nodes.Pair] = []
|
761 |
+
while self.stream.current.type != "rbrace":
|
762 |
+
if items:
|
763 |
+
self.stream.expect("comma")
|
764 |
+
if self.stream.current.type == "rbrace":
|
765 |
+
break
|
766 |
+
key = self.parse_expression()
|
767 |
+
self.stream.expect("colon")
|
768 |
+
value = self.parse_expression()
|
769 |
+
items.append(nodes.Pair(key, value, lineno=key.lineno))
|
770 |
+
self.stream.expect("rbrace")
|
771 |
+
return nodes.Dict(items, lineno=token.lineno)
|
772 |
+
|
773 |
+
def parse_postfix(self, node: nodes.Expr) -> nodes.Expr:
|
774 |
+
while True:
|
775 |
+
token_type = self.stream.current.type
|
776 |
+
if token_type == "dot" or token_type == "lbracket":
|
777 |
+
node = self.parse_subscript(node)
|
778 |
+
# calls are valid both after postfix expressions (getattr
|
779 |
+
# and getitem) as well as filters and tests
|
780 |
+
elif token_type == "lparen":
|
781 |
+
node = self.parse_call(node)
|
782 |
+
else:
|
783 |
+
break
|
784 |
+
return node
|
785 |
+
|
786 |
+
def parse_filter_expr(self, node: nodes.Expr) -> nodes.Expr:
|
787 |
+
while True:
|
788 |
+
token_type = self.stream.current.type
|
789 |
+
if token_type == "pipe":
|
790 |
+
node = self.parse_filter(node) # type: ignore
|
791 |
+
elif token_type == "name" and self.stream.current.value == "is":
|
792 |
+
node = self.parse_test(node)
|
793 |
+
# calls are valid both after postfix expressions (getattr
|
794 |
+
# and getitem) as well as filters and tests
|
795 |
+
elif token_type == "lparen":
|
796 |
+
node = self.parse_call(node)
|
797 |
+
else:
|
798 |
+
break
|
799 |
+
return node
|
800 |
+
|
801 |
+
def parse_subscript(
|
802 |
+
self, node: nodes.Expr
|
803 |
+
) -> t.Union[nodes.Getattr, nodes.Getitem]:
|
804 |
+
token = next(self.stream)
|
805 |
+
arg: nodes.Expr
|
806 |
+
|
807 |
+
if token.type == "dot":
|
808 |
+
attr_token = self.stream.current
|
809 |
+
next(self.stream)
|
810 |
+
if attr_token.type == "name":
|
811 |
+
return nodes.Getattr(
|
812 |
+
node, attr_token.value, "load", lineno=token.lineno
|
813 |
+
)
|
814 |
+
elif attr_token.type != "integer":
|
815 |
+
self.fail("expected name or number", attr_token.lineno)
|
816 |
+
arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
|
817 |
+
return nodes.Getitem(node, arg, "load", lineno=token.lineno)
|
818 |
+
if token.type == "lbracket":
|
819 |
+
args: t.List[nodes.Expr] = []
|
820 |
+
while self.stream.current.type != "rbracket":
|
821 |
+
if args:
|
822 |
+
self.stream.expect("comma")
|
823 |
+
args.append(self.parse_subscribed())
|
824 |
+
self.stream.expect("rbracket")
|
825 |
+
if len(args) == 1:
|
826 |
+
arg = args[0]
|
827 |
+
else:
|
828 |
+
arg = nodes.Tuple(args, "load", lineno=token.lineno)
|
829 |
+
return nodes.Getitem(node, arg, "load", lineno=token.lineno)
|
830 |
+
self.fail("expected subscript expression", token.lineno)
|
831 |
+
|
832 |
+
def parse_subscribed(self) -> nodes.Expr:
|
833 |
+
lineno = self.stream.current.lineno
|
834 |
+
args: t.List[t.Optional[nodes.Expr]]
|
835 |
+
|
836 |
+
if self.stream.current.type == "colon":
|
837 |
+
next(self.stream)
|
838 |
+
args = [None]
|
839 |
+
else:
|
840 |
+
node = self.parse_expression()
|
841 |
+
if self.stream.current.type != "colon":
|
842 |
+
return node
|
843 |
+
next(self.stream)
|
844 |
+
args = [node]
|
845 |
+
|
846 |
+
if self.stream.current.type == "colon":
|
847 |
+
args.append(None)
|
848 |
+
elif self.stream.current.type not in ("rbracket", "comma"):
|
849 |
+
args.append(self.parse_expression())
|
850 |
+
else:
|
851 |
+
args.append(None)
|
852 |
+
|
853 |
+
if self.stream.current.type == "colon":
|
854 |
+
next(self.stream)
|
855 |
+
if self.stream.current.type not in ("rbracket", "comma"):
|
856 |
+
args.append(self.parse_expression())
|
857 |
+
else:
|
858 |
+
args.append(None)
|
859 |
+
else:
|
860 |
+
args.append(None)
|
861 |
+
|
862 |
+
return nodes.Slice(lineno=lineno, *args) # noqa: B026
|
863 |
+
|
864 |
+
def parse_call_args(
|
865 |
+
self,
|
866 |
+
) -> t.Tuple[
|
867 |
+
t.List[nodes.Expr],
|
868 |
+
t.List[nodes.Keyword],
|
869 |
+
t.Optional[nodes.Expr],
|
870 |
+
t.Optional[nodes.Expr],
|
871 |
+
]:
|
872 |
+
token = self.stream.expect("lparen")
|
873 |
+
args = []
|
874 |
+
kwargs = []
|
875 |
+
dyn_args = None
|
876 |
+
dyn_kwargs = None
|
877 |
+
require_comma = False
|
878 |
+
|
879 |
+
def ensure(expr: bool) -> None:
|
880 |
+
if not expr:
|
881 |
+
self.fail("invalid syntax for function call expression", token.lineno)
|
882 |
+
|
883 |
+
while self.stream.current.type != "rparen":
|
884 |
+
if require_comma:
|
885 |
+
self.stream.expect("comma")
|
886 |
+
|
887 |
+
# support for trailing comma
|
888 |
+
if self.stream.current.type == "rparen":
|
889 |
+
break
|
890 |
+
|
891 |
+
if self.stream.current.type == "mul":
|
892 |
+
ensure(dyn_args is None and dyn_kwargs is None)
|
893 |
+
next(self.stream)
|
894 |
+
dyn_args = self.parse_expression()
|
895 |
+
elif self.stream.current.type == "pow":
|
896 |
+
ensure(dyn_kwargs is None)
|
897 |
+
next(self.stream)
|
898 |
+
dyn_kwargs = self.parse_expression()
|
899 |
+
else:
|
900 |
+
if (
|
901 |
+
self.stream.current.type == "name"
|
902 |
+
and self.stream.look().type == "assign"
|
903 |
+
):
|
904 |
+
# Parsing a kwarg
|
905 |
+
ensure(dyn_kwargs is None)
|
906 |
+
key = self.stream.current.value
|
907 |
+
self.stream.skip(2)
|
908 |
+
value = self.parse_expression()
|
909 |
+
kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))
|
910 |
+
else:
|
911 |
+
# Parsing an arg
|
912 |
+
ensure(dyn_args is None and dyn_kwargs is None and not kwargs)
|
913 |
+
args.append(self.parse_expression())
|
914 |
+
|
915 |
+
require_comma = True
|
916 |
+
|
917 |
+
self.stream.expect("rparen")
|
918 |
+
return args, kwargs, dyn_args, dyn_kwargs
|
919 |
+
|
920 |
+
def parse_call(self, node: nodes.Expr) -> nodes.Call:
|
921 |
+
# The lparen will be expected in parse_call_args, but the lineno
|
922 |
+
# needs to be recorded before the stream is advanced.
|
923 |
+
token = self.stream.current
|
924 |
+
args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()
|
925 |
+
return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)
|
926 |
+
|
927 |
+
def parse_filter(
|
928 |
+
self, node: t.Optional[nodes.Expr], start_inline: bool = False
|
929 |
+
) -> t.Optional[nodes.Expr]:
|
930 |
+
while self.stream.current.type == "pipe" or start_inline:
|
931 |
+
if not start_inline:
|
932 |
+
next(self.stream)
|
933 |
+
token = self.stream.expect("name")
|
934 |
+
name = token.value
|
935 |
+
while self.stream.current.type == "dot":
|
936 |
+
next(self.stream)
|
937 |
+
name += "." + self.stream.expect("name").value
|
938 |
+
if self.stream.current.type == "lparen":
|
939 |
+
args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()
|
940 |
+
else:
|
941 |
+
args = []
|
942 |
+
kwargs = []
|
943 |
+
dyn_args = dyn_kwargs = None
|
944 |
+
node = nodes.Filter(
|
945 |
+
node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno
|
946 |
+
)
|
947 |
+
start_inline = False
|
948 |
+
return node
|
949 |
+
|
950 |
+
def parse_test(self, node: nodes.Expr) -> nodes.Expr:
|
951 |
+
token = next(self.stream)
|
952 |
+
if self.stream.current.test("name:not"):
|
953 |
+
next(self.stream)
|
954 |
+
negated = True
|
955 |
+
else:
|
956 |
+
negated = False
|
957 |
+
name = self.stream.expect("name").value
|
958 |
+
while self.stream.current.type == "dot":
|
959 |
+
next(self.stream)
|
960 |
+
name += "." + self.stream.expect("name").value
|
961 |
+
dyn_args = dyn_kwargs = None
|
962 |
+
kwargs: t.List[nodes.Keyword] = []
|
963 |
+
if self.stream.current.type == "lparen":
|
964 |
+
args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()
|
965 |
+
elif self.stream.current.type in {
|
966 |
+
"name",
|
967 |
+
"string",
|
968 |
+
"integer",
|
969 |
+
"float",
|
970 |
+
"lparen",
|
971 |
+
"lbracket",
|
972 |
+
"lbrace",
|
973 |
+
} and not self.stream.current.test_any("name:else", "name:or", "name:and"):
|
974 |
+
if self.stream.current.test("name:is"):
|
975 |
+
self.fail("You cannot chain multiple tests with is")
|
976 |
+
arg_node = self.parse_primary()
|
977 |
+
arg_node = self.parse_postfix(arg_node)
|
978 |
+
args = [arg_node]
|
979 |
+
else:
|
980 |
+
args = []
|
981 |
+
node = nodes.Test(
|
982 |
+
node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno
|
983 |
+
)
|
984 |
+
if negated:
|
985 |
+
node = nodes.Not(node, lineno=token.lineno)
|
986 |
+
return node
|
987 |
+
|
988 |
+
def subparse(
|
989 |
+
self, end_tokens: t.Optional[t.Tuple[str, ...]] = None
|
990 |
+
) -> t.List[nodes.Node]:
|
991 |
+
body: t.List[nodes.Node] = []
|
992 |
+
data_buffer: t.List[nodes.Node] = []
|
993 |
+
add_data = data_buffer.append
|
994 |
+
|
995 |
+
if end_tokens is not None:
|
996 |
+
self._end_token_stack.append(end_tokens)
|
997 |
+
|
998 |
+
def flush_data() -> None:
|
999 |
+
if data_buffer:
|
1000 |
+
lineno = data_buffer[0].lineno
|
1001 |
+
body.append(nodes.Output(data_buffer[:], lineno=lineno))
|
1002 |
+
del data_buffer[:]
|
1003 |
+
|
1004 |
+
try:
|
1005 |
+
while self.stream:
|
1006 |
+
token = self.stream.current
|
1007 |
+
if token.type == "data":
|
1008 |
+
if token.value:
|
1009 |
+
add_data(nodes.TemplateData(token.value, lineno=token.lineno))
|
1010 |
+
next(self.stream)
|
1011 |
+
elif token.type == "variable_begin":
|
1012 |
+
next(self.stream)
|
1013 |
+
add_data(self.parse_tuple(with_condexpr=True))
|
1014 |
+
self.stream.expect("variable_end")
|
1015 |
+
elif token.type == "block_begin":
|
1016 |
+
flush_data()
|
1017 |
+
next(self.stream)
|
1018 |
+
if end_tokens is not None and self.stream.current.test_any(
|
1019 |
+
*end_tokens
|
1020 |
+
):
|
1021 |
+
return body
|
1022 |
+
rv = self.parse_statement()
|
1023 |
+
if isinstance(rv, list):
|
1024 |
+
body.extend(rv)
|
1025 |
+
else:
|
1026 |
+
body.append(rv)
|
1027 |
+
self.stream.expect("block_end")
|
1028 |
+
else:
|
1029 |
+
raise AssertionError("internal parsing error")
|
1030 |
+
|
1031 |
+
flush_data()
|
1032 |
+
finally:
|
1033 |
+
if end_tokens is not None:
|
1034 |
+
self._end_token_stack.pop()
|
1035 |
+
return body
|
1036 |
+
|
1037 |
+
def parse(self) -> nodes.Template:
|
1038 |
+
"""Parse the whole template into a `Template` node."""
|
1039 |
+
result = nodes.Template(self.subparse(), lineno=1)
|
1040 |
+
result.set_environment(self.environment)
|
1041 |
+
return result
|
llmeval-env/lib/python3.10/site-packages/jinja2/py.typed
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/jinja2/runtime.py
ADDED
@@ -0,0 +1,1056 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The runtime functions and state used by compiled templates."""
|
2 |
+
|
3 |
+
import functools
|
4 |
+
import sys
|
5 |
+
import typing as t
|
6 |
+
from collections import abc
|
7 |
+
from itertools import chain
|
8 |
+
|
9 |
+
from markupsafe import escape # noqa: F401
|
10 |
+
from markupsafe import Markup
|
11 |
+
from markupsafe import soft_str
|
12 |
+
|
13 |
+
from .async_utils import auto_aiter
|
14 |
+
from .async_utils import auto_await # noqa: F401
|
15 |
+
from .exceptions import TemplateNotFound # noqa: F401
|
16 |
+
from .exceptions import TemplateRuntimeError # noqa: F401
|
17 |
+
from .exceptions import UndefinedError
|
18 |
+
from .nodes import EvalContext
|
19 |
+
from .utils import _PassArg
|
20 |
+
from .utils import concat
|
21 |
+
from .utils import internalcode
|
22 |
+
from .utils import missing
|
23 |
+
from .utils import Namespace # noqa: F401
|
24 |
+
from .utils import object_type_repr
|
25 |
+
from .utils import pass_eval_context
|
26 |
+
|
27 |
+
V = t.TypeVar("V")
|
28 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
29 |
+
|
30 |
+
if t.TYPE_CHECKING:
|
31 |
+
import logging
|
32 |
+
|
33 |
+
import typing_extensions as te
|
34 |
+
|
35 |
+
from .environment import Environment
|
36 |
+
|
37 |
+
class LoopRenderFunc(te.Protocol):
|
38 |
+
def __call__(
|
39 |
+
self,
|
40 |
+
reciter: t.Iterable[V],
|
41 |
+
loop_render_func: "LoopRenderFunc",
|
42 |
+
depth: int = 0,
|
43 |
+
) -> str: ...
|
44 |
+
|
45 |
+
|
46 |
+
# these variables are exported to the template runtime
|
47 |
+
exported = [
|
48 |
+
"LoopContext",
|
49 |
+
"TemplateReference",
|
50 |
+
"Macro",
|
51 |
+
"Markup",
|
52 |
+
"TemplateRuntimeError",
|
53 |
+
"missing",
|
54 |
+
"escape",
|
55 |
+
"markup_join",
|
56 |
+
"str_join",
|
57 |
+
"identity",
|
58 |
+
"TemplateNotFound",
|
59 |
+
"Namespace",
|
60 |
+
"Undefined",
|
61 |
+
"internalcode",
|
62 |
+
]
|
63 |
+
async_exported = [
|
64 |
+
"AsyncLoopContext",
|
65 |
+
"auto_aiter",
|
66 |
+
"auto_await",
|
67 |
+
]
|
68 |
+
|
69 |
+
|
70 |
+
def identity(x: V) -> V:
|
71 |
+
"""Returns its argument. Useful for certain things in the
|
72 |
+
environment.
|
73 |
+
"""
|
74 |
+
return x
|
75 |
+
|
76 |
+
|
77 |
+
def markup_join(seq: t.Iterable[t.Any]) -> str:
|
78 |
+
"""Concatenation that escapes if necessary and converts to string."""
|
79 |
+
buf = []
|
80 |
+
iterator = map(soft_str, seq)
|
81 |
+
for arg in iterator:
|
82 |
+
buf.append(arg)
|
83 |
+
if hasattr(arg, "__html__"):
|
84 |
+
return Markup("").join(chain(buf, iterator))
|
85 |
+
return concat(buf)
|
86 |
+
|
87 |
+
|
88 |
+
def str_join(seq: t.Iterable[t.Any]) -> str:
|
89 |
+
"""Simple args to string conversion and concatenation."""
|
90 |
+
return concat(map(str, seq))
|
91 |
+
|
92 |
+
|
93 |
+
def new_context(
|
94 |
+
environment: "Environment",
|
95 |
+
template_name: t.Optional[str],
|
96 |
+
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
|
97 |
+
vars: t.Optional[t.Dict[str, t.Any]] = None,
|
98 |
+
shared: bool = False,
|
99 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
100 |
+
locals: t.Optional[t.Mapping[str, t.Any]] = None,
|
101 |
+
) -> "Context":
|
102 |
+
"""Internal helper for context creation."""
|
103 |
+
if vars is None:
|
104 |
+
vars = {}
|
105 |
+
if shared:
|
106 |
+
parent = vars
|
107 |
+
else:
|
108 |
+
parent = dict(globals or (), **vars)
|
109 |
+
if locals:
|
110 |
+
# if the parent is shared a copy should be created because
|
111 |
+
# we don't want to modify the dict passed
|
112 |
+
if shared:
|
113 |
+
parent = dict(parent)
|
114 |
+
for key, value in locals.items():
|
115 |
+
if value is not missing:
|
116 |
+
parent[key] = value
|
117 |
+
return environment.context_class(
|
118 |
+
environment, parent, template_name, blocks, globals=globals
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
class TemplateReference:
|
123 |
+
"""The `self` in templates."""
|
124 |
+
|
125 |
+
def __init__(self, context: "Context") -> None:
|
126 |
+
self.__context = context
|
127 |
+
|
128 |
+
def __getitem__(self, name: str) -> t.Any:
|
129 |
+
blocks = self.__context.blocks[name]
|
130 |
+
return BlockReference(name, self.__context, blocks, 0)
|
131 |
+
|
132 |
+
def __repr__(self) -> str:
|
133 |
+
return f"<{type(self).__name__} {self.__context.name!r}>"
|
134 |
+
|
135 |
+
|
136 |
+
def _dict_method_all(dict_method: F) -> F:
|
137 |
+
@functools.wraps(dict_method)
|
138 |
+
def f_all(self: "Context") -> t.Any:
|
139 |
+
return dict_method(self.get_all())
|
140 |
+
|
141 |
+
return t.cast(F, f_all)
|
142 |
+
|
143 |
+
|
144 |
+
@abc.Mapping.register
|
145 |
+
class Context:
|
146 |
+
"""The template context holds the variables of a template. It stores the
|
147 |
+
values passed to the template and also the names the template exports.
|
148 |
+
Creating instances is neither supported nor useful as it's created
|
149 |
+
automatically at various stages of the template evaluation and should not
|
150 |
+
be created by hand.
|
151 |
+
|
152 |
+
The context is immutable. Modifications on :attr:`parent` **must not**
|
153 |
+
happen and modifications on :attr:`vars` are allowed from generated
|
154 |
+
template code only. Template filters and global functions marked as
|
155 |
+
:func:`pass_context` get the active context passed as first argument
|
156 |
+
and are allowed to access the context read-only.
|
157 |
+
|
158 |
+
The template context supports read only dict operations (`get`,
|
159 |
+
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
|
160 |
+
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
|
161 |
+
method that doesn't fail with a `KeyError` but returns an
|
162 |
+
:class:`Undefined` object for missing variables.
|
163 |
+
"""
|
164 |
+
|
165 |
+
def __init__(
|
166 |
+
self,
|
167 |
+
environment: "Environment",
|
168 |
+
parent: t.Dict[str, t.Any],
|
169 |
+
name: t.Optional[str],
|
170 |
+
blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],
|
171 |
+
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
|
172 |
+
):
|
173 |
+
self.parent = parent
|
174 |
+
self.vars: t.Dict[str, t.Any] = {}
|
175 |
+
self.environment: "Environment" = environment
|
176 |
+
self.eval_ctx = EvalContext(self.environment, name)
|
177 |
+
self.exported_vars: t.Set[str] = set()
|
178 |
+
self.name = name
|
179 |
+
self.globals_keys = set() if globals is None else set(globals)
|
180 |
+
|
181 |
+
# create the initial mapping of blocks. Whenever template inheritance
|
182 |
+
# takes place the runtime will update this mapping with the new blocks
|
183 |
+
# from the template.
|
184 |
+
self.blocks = {k: [v] for k, v in blocks.items()}
|
185 |
+
|
186 |
+
def super(
|
187 |
+
self, name: str, current: t.Callable[["Context"], t.Iterator[str]]
|
188 |
+
) -> t.Union["BlockReference", "Undefined"]:
|
189 |
+
"""Render a parent block."""
|
190 |
+
try:
|
191 |
+
blocks = self.blocks[name]
|
192 |
+
index = blocks.index(current) + 1
|
193 |
+
blocks[index]
|
194 |
+
except LookupError:
|
195 |
+
return self.environment.undefined(
|
196 |
+
f"there is no parent block called {name!r}.", name="super"
|
197 |
+
)
|
198 |
+
return BlockReference(name, self, blocks, index)
|
199 |
+
|
200 |
+
def get(self, key: str, default: t.Any = None) -> t.Any:
|
201 |
+
"""Look up a variable by name, or return a default if the key is
|
202 |
+
not found.
|
203 |
+
|
204 |
+
:param key: The variable name to look up.
|
205 |
+
:param default: The value to return if the key is not found.
|
206 |
+
"""
|
207 |
+
try:
|
208 |
+
return self[key]
|
209 |
+
except KeyError:
|
210 |
+
return default
|
211 |
+
|
212 |
+
def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:
|
213 |
+
"""Look up a variable by name, or return an :class:`Undefined`
|
214 |
+
object if the key is not found.
|
215 |
+
|
216 |
+
If you need to add custom behavior, override
|
217 |
+
:meth:`resolve_or_missing`, not this method. The various lookup
|
218 |
+
functions use that method, not this one.
|
219 |
+
|
220 |
+
:param key: The variable name to look up.
|
221 |
+
"""
|
222 |
+
rv = self.resolve_or_missing(key)
|
223 |
+
|
224 |
+
if rv is missing:
|
225 |
+
return self.environment.undefined(name=key)
|
226 |
+
|
227 |
+
return rv
|
228 |
+
|
229 |
+
def resolve_or_missing(self, key: str) -> t.Any:
|
230 |
+
"""Look up a variable by name, or return a ``missing`` sentinel
|
231 |
+
if the key is not found.
|
232 |
+
|
233 |
+
Override this method to add custom lookup behavior.
|
234 |
+
:meth:`resolve`, :meth:`get`, and :meth:`__getitem__` use this
|
235 |
+
method. Don't call this method directly.
|
236 |
+
|
237 |
+
:param key: The variable name to look up.
|
238 |
+
"""
|
239 |
+
if key in self.vars:
|
240 |
+
return self.vars[key]
|
241 |
+
|
242 |
+
if key in self.parent:
|
243 |
+
return self.parent[key]
|
244 |
+
|
245 |
+
return missing
|
246 |
+
|
247 |
+
def get_exported(self) -> t.Dict[str, t.Any]:
|
248 |
+
"""Get a new dict with the exported variables."""
|
249 |
+
return {k: self.vars[k] for k in self.exported_vars}
|
250 |
+
|
251 |
+
def get_all(self) -> t.Dict[str, t.Any]:
|
252 |
+
"""Return the complete context as dict including the exported
|
253 |
+
variables. For optimizations reasons this might not return an
|
254 |
+
actual copy so be careful with using it.
|
255 |
+
"""
|
256 |
+
if not self.vars:
|
257 |
+
return self.parent
|
258 |
+
if not self.parent:
|
259 |
+
return self.vars
|
260 |
+
return dict(self.parent, **self.vars)
|
261 |
+
|
262 |
+
@internalcode
|
263 |
+
def call(
|
264 |
+
__self,
|
265 |
+
__obj: t.Callable[..., t.Any],
|
266 |
+
*args: t.Any,
|
267 |
+
**kwargs: t.Any, # noqa: B902
|
268 |
+
) -> t.Union[t.Any, "Undefined"]:
|
269 |
+
"""Call the callable with the arguments and keyword arguments
|
270 |
+
provided but inject the active context or environment as first
|
271 |
+
argument if the callable has :func:`pass_context` or
|
272 |
+
:func:`pass_environment`.
|
273 |
+
"""
|
274 |
+
if __debug__:
|
275 |
+
__traceback_hide__ = True # noqa
|
276 |
+
|
277 |
+
# Allow callable classes to take a context
|
278 |
+
if (
|
279 |
+
hasattr(__obj, "__call__") # noqa: B004
|
280 |
+
and _PassArg.from_obj(__obj.__call__) is not None
|
281 |
+
):
|
282 |
+
__obj = __obj.__call__
|
283 |
+
|
284 |
+
pass_arg = _PassArg.from_obj(__obj)
|
285 |
+
|
286 |
+
if pass_arg is _PassArg.context:
|
287 |
+
# the active context should have access to variables set in
|
288 |
+
# loops and blocks without mutating the context itself
|
289 |
+
if kwargs.get("_loop_vars"):
|
290 |
+
__self = __self.derived(kwargs["_loop_vars"])
|
291 |
+
if kwargs.get("_block_vars"):
|
292 |
+
__self = __self.derived(kwargs["_block_vars"])
|
293 |
+
args = (__self,) + args
|
294 |
+
elif pass_arg is _PassArg.eval_context:
|
295 |
+
args = (__self.eval_ctx,) + args
|
296 |
+
elif pass_arg is _PassArg.environment:
|
297 |
+
args = (__self.environment,) + args
|
298 |
+
|
299 |
+
kwargs.pop("_block_vars", None)
|
300 |
+
kwargs.pop("_loop_vars", None)
|
301 |
+
|
302 |
+
try:
|
303 |
+
return __obj(*args, **kwargs)
|
304 |
+
except StopIteration:
|
305 |
+
return __self.environment.undefined(
|
306 |
+
"value was undefined because a callable raised a"
|
307 |
+
" StopIteration exception"
|
308 |
+
)
|
309 |
+
|
310 |
+
def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":
|
311 |
+
"""Internal helper function to create a derived context. This is
|
312 |
+
used in situations where the system needs a new context in the same
|
313 |
+
template that is independent.
|
314 |
+
"""
|
315 |
+
context = new_context(
|
316 |
+
self.environment, self.name, {}, self.get_all(), True, None, locals
|
317 |
+
)
|
318 |
+
context.eval_ctx = self.eval_ctx
|
319 |
+
context.blocks.update((k, list(v)) for k, v in self.blocks.items())
|
320 |
+
return context
|
321 |
+
|
322 |
+
keys = _dict_method_all(dict.keys)
|
323 |
+
values = _dict_method_all(dict.values)
|
324 |
+
items = _dict_method_all(dict.items)
|
325 |
+
|
326 |
+
def __contains__(self, name: str) -> bool:
|
327 |
+
return name in self.vars or name in self.parent
|
328 |
+
|
329 |
+
def __getitem__(self, key: str) -> t.Any:
|
330 |
+
"""Look up a variable by name with ``[]`` syntax, or raise a
|
331 |
+
``KeyError`` if the key is not found.
|
332 |
+
"""
|
333 |
+
item = self.resolve_or_missing(key)
|
334 |
+
|
335 |
+
if item is missing:
|
336 |
+
raise KeyError(key)
|
337 |
+
|
338 |
+
return item
|
339 |
+
|
340 |
+
def __repr__(self) -> str:
|
341 |
+
return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"
|
342 |
+
|
343 |
+
|
344 |
+
class BlockReference:
|
345 |
+
"""One block on a template reference."""
|
346 |
+
|
347 |
+
def __init__(
|
348 |
+
self,
|
349 |
+
name: str,
|
350 |
+
context: "Context",
|
351 |
+
stack: t.List[t.Callable[["Context"], t.Iterator[str]]],
|
352 |
+
depth: int,
|
353 |
+
) -> None:
|
354 |
+
self.name = name
|
355 |
+
self._context = context
|
356 |
+
self._stack = stack
|
357 |
+
self._depth = depth
|
358 |
+
|
359 |
+
@property
|
360 |
+
def super(self) -> t.Union["BlockReference", "Undefined"]:
|
361 |
+
"""Super the block."""
|
362 |
+
if self._depth + 1 >= len(self._stack):
|
363 |
+
return self._context.environment.undefined(
|
364 |
+
f"there is no parent block called {self.name!r}.", name="super"
|
365 |
+
)
|
366 |
+
return BlockReference(self.name, self._context, self._stack, self._depth + 1)
|
367 |
+
|
368 |
+
@internalcode
|
369 |
+
async def _async_call(self) -> str:
|
370 |
+
rv = concat(
|
371 |
+
[x async for x in self._stack[self._depth](self._context)] # type: ignore
|
372 |
+
)
|
373 |
+
|
374 |
+
if self._context.eval_ctx.autoescape:
|
375 |
+
return Markup(rv)
|
376 |
+
|
377 |
+
return rv
|
378 |
+
|
379 |
+
@internalcode
|
380 |
+
def __call__(self) -> str:
|
381 |
+
if self._context.environment.is_async:
|
382 |
+
return self._async_call() # type: ignore
|
383 |
+
|
384 |
+
rv = concat(self._stack[self._depth](self._context))
|
385 |
+
|
386 |
+
if self._context.eval_ctx.autoescape:
|
387 |
+
return Markup(rv)
|
388 |
+
|
389 |
+
return rv
|
390 |
+
|
391 |
+
|
392 |
+
class LoopContext:
|
393 |
+
"""A wrapper iterable for dynamic ``for`` loops, with information
|
394 |
+
about the loop and iteration.
|
395 |
+
"""
|
396 |
+
|
397 |
+
#: Current iteration of the loop, starting at 0.
|
398 |
+
index0 = -1
|
399 |
+
|
400 |
+
_length: t.Optional[int] = None
|
401 |
+
_after: t.Any = missing
|
402 |
+
_current: t.Any = missing
|
403 |
+
_before: t.Any = missing
|
404 |
+
_last_changed_value: t.Any = missing
|
405 |
+
|
406 |
+
def __init__(
|
407 |
+
self,
|
408 |
+
iterable: t.Iterable[V],
|
409 |
+
undefined: t.Type["Undefined"],
|
410 |
+
recurse: t.Optional["LoopRenderFunc"] = None,
|
411 |
+
depth0: int = 0,
|
412 |
+
) -> None:
|
413 |
+
"""
|
414 |
+
:param iterable: Iterable to wrap.
|
415 |
+
:param undefined: :class:`Undefined` class to use for next and
|
416 |
+
previous items.
|
417 |
+
:param recurse: The function to render the loop body when the
|
418 |
+
loop is marked recursive.
|
419 |
+
:param depth0: Incremented when looping recursively.
|
420 |
+
"""
|
421 |
+
self._iterable = iterable
|
422 |
+
self._iterator = self._to_iterator(iterable)
|
423 |
+
self._undefined = undefined
|
424 |
+
self._recurse = recurse
|
425 |
+
#: How many levels deep a recursive loop currently is, starting at 0.
|
426 |
+
self.depth0 = depth0
|
427 |
+
|
428 |
+
@staticmethod
|
429 |
+
def _to_iterator(iterable: t.Iterable[V]) -> t.Iterator[V]:
|
430 |
+
return iter(iterable)
|
431 |
+
|
432 |
+
@property
|
433 |
+
def length(self) -> int:
|
434 |
+
"""Length of the iterable.
|
435 |
+
|
436 |
+
If the iterable is a generator or otherwise does not have a
|
437 |
+
size, it is eagerly evaluated to get a size.
|
438 |
+
"""
|
439 |
+
if self._length is not None:
|
440 |
+
return self._length
|
441 |
+
|
442 |
+
try:
|
443 |
+
self._length = len(self._iterable) # type: ignore
|
444 |
+
except TypeError:
|
445 |
+
iterable = list(self._iterator)
|
446 |
+
self._iterator = self._to_iterator(iterable)
|
447 |
+
self._length = len(iterable) + self.index + (self._after is not missing)
|
448 |
+
|
449 |
+
return self._length
|
450 |
+
|
451 |
+
def __len__(self) -> int:
|
452 |
+
return self.length
|
453 |
+
|
454 |
+
@property
|
455 |
+
def depth(self) -> int:
|
456 |
+
"""How many levels deep a recursive loop currently is, starting at 1."""
|
457 |
+
return self.depth0 + 1
|
458 |
+
|
459 |
+
@property
|
460 |
+
def index(self) -> int:
|
461 |
+
"""Current iteration of the loop, starting at 1."""
|
462 |
+
return self.index0 + 1
|
463 |
+
|
464 |
+
@property
|
465 |
+
def revindex0(self) -> int:
|
466 |
+
"""Number of iterations from the end of the loop, ending at 0.
|
467 |
+
|
468 |
+
Requires calculating :attr:`length`.
|
469 |
+
"""
|
470 |
+
return self.length - self.index
|
471 |
+
|
472 |
+
@property
|
473 |
+
def revindex(self) -> int:
|
474 |
+
"""Number of iterations from the end of the loop, ending at 1.
|
475 |
+
|
476 |
+
Requires calculating :attr:`length`.
|
477 |
+
"""
|
478 |
+
return self.length - self.index0
|
479 |
+
|
480 |
+
@property
|
481 |
+
def first(self) -> bool:
|
482 |
+
"""Whether this is the first iteration of the loop."""
|
483 |
+
return self.index0 == 0
|
484 |
+
|
485 |
+
def _peek_next(self) -> t.Any:
|
486 |
+
"""Return the next element in the iterable, or :data:`missing`
|
487 |
+
if the iterable is exhausted. Only peeks one item ahead, caching
|
488 |
+
the result in :attr:`_last` for use in subsequent checks. The
|
489 |
+
cache is reset when :meth:`__next__` is called.
|
490 |
+
"""
|
491 |
+
if self._after is not missing:
|
492 |
+
return self._after
|
493 |
+
|
494 |
+
self._after = next(self._iterator, missing)
|
495 |
+
return self._after
|
496 |
+
|
497 |
+
@property
|
498 |
+
def last(self) -> bool:
|
499 |
+
"""Whether this is the last iteration of the loop.
|
500 |
+
|
501 |
+
Causes the iterable to advance early. See
|
502 |
+
:func:`itertools.groupby` for issues this can cause.
|
503 |
+
The :func:`groupby` filter avoids that issue.
|
504 |
+
"""
|
505 |
+
return self._peek_next() is missing
|
506 |
+
|
507 |
+
@property
|
508 |
+
def previtem(self) -> t.Union[t.Any, "Undefined"]:
|
509 |
+
"""The item in the previous iteration. Undefined during the
|
510 |
+
first iteration.
|
511 |
+
"""
|
512 |
+
if self.first:
|
513 |
+
return self._undefined("there is no previous item")
|
514 |
+
|
515 |
+
return self._before
|
516 |
+
|
517 |
+
@property
|
518 |
+
def nextitem(self) -> t.Union[t.Any, "Undefined"]:
|
519 |
+
"""The item in the next iteration. Undefined during the last
|
520 |
+
iteration.
|
521 |
+
|
522 |
+
Causes the iterable to advance early. See
|
523 |
+
:func:`itertools.groupby` for issues this can cause.
|
524 |
+
The :func:`jinja-filters.groupby` filter avoids that issue.
|
525 |
+
"""
|
526 |
+
rv = self._peek_next()
|
527 |
+
|
528 |
+
if rv is missing:
|
529 |
+
return self._undefined("there is no next item")
|
530 |
+
|
531 |
+
return rv
|
532 |
+
|
533 |
+
def cycle(self, *args: V) -> V:
|
534 |
+
"""Return a value from the given args, cycling through based on
|
535 |
+
the current :attr:`index0`.
|
536 |
+
|
537 |
+
:param args: One or more values to cycle through.
|
538 |
+
"""
|
539 |
+
if not args:
|
540 |
+
raise TypeError("no items for cycling given")
|
541 |
+
|
542 |
+
return args[self.index0 % len(args)]
|
543 |
+
|
544 |
+
def changed(self, *value: t.Any) -> bool:
|
545 |
+
"""Return ``True`` if previously called with a different value
|
546 |
+
(including when called for the first time).
|
547 |
+
|
548 |
+
:param value: One or more values to compare to the last call.
|
549 |
+
"""
|
550 |
+
if self._last_changed_value != value:
|
551 |
+
self._last_changed_value = value
|
552 |
+
return True
|
553 |
+
|
554 |
+
return False
|
555 |
+
|
556 |
+
def __iter__(self) -> "LoopContext":
|
557 |
+
return self
|
558 |
+
|
559 |
+
def __next__(self) -> t.Tuple[t.Any, "LoopContext"]:
|
560 |
+
if self._after is not missing:
|
561 |
+
rv = self._after
|
562 |
+
self._after = missing
|
563 |
+
else:
|
564 |
+
rv = next(self._iterator)
|
565 |
+
|
566 |
+
self.index0 += 1
|
567 |
+
self._before = self._current
|
568 |
+
self._current = rv
|
569 |
+
return rv, self
|
570 |
+
|
571 |
+
@internalcode
|
572 |
+
def __call__(self, iterable: t.Iterable[V]) -> str:
|
573 |
+
"""When iterating over nested data, render the body of the loop
|
574 |
+
recursively with the given inner iterable data.
|
575 |
+
|
576 |
+
The loop must have the ``recursive`` marker for this to work.
|
577 |
+
"""
|
578 |
+
if self._recurse is None:
|
579 |
+
raise TypeError(
|
580 |
+
"The loop must have the 'recursive' marker to be called recursively."
|
581 |
+
)
|
582 |
+
|
583 |
+
return self._recurse(iterable, self._recurse, depth=self.depth)
|
584 |
+
|
585 |
+
def __repr__(self) -> str:
|
586 |
+
return f"<{type(self).__name__} {self.index}/{self.length}>"
|
587 |
+
|
588 |
+
|
589 |
+
class AsyncLoopContext(LoopContext):
|
590 |
+
_iterator: t.AsyncIterator[t.Any] # type: ignore
|
591 |
+
|
592 |
+
@staticmethod
|
593 |
+
def _to_iterator( # type: ignore
|
594 |
+
iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]],
|
595 |
+
) -> t.AsyncIterator[V]:
|
596 |
+
return auto_aiter(iterable)
|
597 |
+
|
598 |
+
@property
|
599 |
+
async def length(self) -> int: # type: ignore
|
600 |
+
if self._length is not None:
|
601 |
+
return self._length
|
602 |
+
|
603 |
+
try:
|
604 |
+
self._length = len(self._iterable) # type: ignore
|
605 |
+
except TypeError:
|
606 |
+
iterable = [x async for x in self._iterator]
|
607 |
+
self._iterator = self._to_iterator(iterable)
|
608 |
+
self._length = len(iterable) + self.index + (self._after is not missing)
|
609 |
+
|
610 |
+
return self._length
|
611 |
+
|
612 |
+
@property
|
613 |
+
async def revindex0(self) -> int: # type: ignore
|
614 |
+
return await self.length - self.index
|
615 |
+
|
616 |
+
@property
|
617 |
+
async def revindex(self) -> int: # type: ignore
|
618 |
+
return await self.length - self.index0
|
619 |
+
|
620 |
+
async def _peek_next(self) -> t.Any:
|
621 |
+
if self._after is not missing:
|
622 |
+
return self._after
|
623 |
+
|
624 |
+
try:
|
625 |
+
self._after = await self._iterator.__anext__()
|
626 |
+
except StopAsyncIteration:
|
627 |
+
self._after = missing
|
628 |
+
|
629 |
+
return self._after
|
630 |
+
|
631 |
+
@property
|
632 |
+
async def last(self) -> bool: # type: ignore
|
633 |
+
return await self._peek_next() is missing
|
634 |
+
|
635 |
+
@property
|
636 |
+
async def nextitem(self) -> t.Union[t.Any, "Undefined"]:
|
637 |
+
rv = await self._peek_next()
|
638 |
+
|
639 |
+
if rv is missing:
|
640 |
+
return self._undefined("there is no next item")
|
641 |
+
|
642 |
+
return rv
|
643 |
+
|
644 |
+
def __aiter__(self) -> "AsyncLoopContext":
|
645 |
+
return self
|
646 |
+
|
647 |
+
async def __anext__(self) -> t.Tuple[t.Any, "AsyncLoopContext"]:
|
648 |
+
if self._after is not missing:
|
649 |
+
rv = self._after
|
650 |
+
self._after = missing
|
651 |
+
else:
|
652 |
+
rv = await self._iterator.__anext__()
|
653 |
+
|
654 |
+
self.index0 += 1
|
655 |
+
self._before = self._current
|
656 |
+
self._current = rv
|
657 |
+
return rv, self
|
658 |
+
|
659 |
+
|
660 |
+
class Macro:
|
661 |
+
"""Wraps a macro function."""
|
662 |
+
|
663 |
+
def __init__(
|
664 |
+
self,
|
665 |
+
environment: "Environment",
|
666 |
+
func: t.Callable[..., str],
|
667 |
+
name: str,
|
668 |
+
arguments: t.List[str],
|
669 |
+
catch_kwargs: bool,
|
670 |
+
catch_varargs: bool,
|
671 |
+
caller: bool,
|
672 |
+
default_autoescape: t.Optional[bool] = None,
|
673 |
+
):
|
674 |
+
self._environment = environment
|
675 |
+
self._func = func
|
676 |
+
self._argument_count = len(arguments)
|
677 |
+
self.name = name
|
678 |
+
self.arguments = arguments
|
679 |
+
self.catch_kwargs = catch_kwargs
|
680 |
+
self.catch_varargs = catch_varargs
|
681 |
+
self.caller = caller
|
682 |
+
self.explicit_caller = "caller" in arguments
|
683 |
+
|
684 |
+
if default_autoescape is None:
|
685 |
+
if callable(environment.autoescape):
|
686 |
+
default_autoescape = environment.autoescape(None)
|
687 |
+
else:
|
688 |
+
default_autoescape = environment.autoescape
|
689 |
+
|
690 |
+
self._default_autoescape = default_autoescape
|
691 |
+
|
692 |
+
@internalcode
|
693 |
+
@pass_eval_context
|
694 |
+
def __call__(self, *args: t.Any, **kwargs: t.Any) -> str:
|
695 |
+
# This requires a bit of explanation, In the past we used to
|
696 |
+
# decide largely based on compile-time information if a macro is
|
697 |
+
# safe or unsafe. While there was a volatile mode it was largely
|
698 |
+
# unused for deciding on escaping. This turns out to be
|
699 |
+
# problematic for macros because whether a macro is safe depends not
|
700 |
+
# on the escape mode when it was defined, but rather when it was used.
|
701 |
+
#
|
702 |
+
# Because however we export macros from the module system and
|
703 |
+
# there are historic callers that do not pass an eval context (and
|
704 |
+
# will continue to not pass one), we need to perform an instance
|
705 |
+
# check here.
|
706 |
+
#
|
707 |
+
# This is considered safe because an eval context is not a valid
|
708 |
+
# argument to callables otherwise anyway. Worst case here is
|
709 |
+
# that if no eval context is passed we fall back to the compile
|
710 |
+
# time autoescape flag.
|
711 |
+
if args and isinstance(args[0], EvalContext):
|
712 |
+
autoescape = args[0].autoescape
|
713 |
+
args = args[1:]
|
714 |
+
else:
|
715 |
+
autoescape = self._default_autoescape
|
716 |
+
|
717 |
+
# try to consume the positional arguments
|
718 |
+
arguments = list(args[: self._argument_count])
|
719 |
+
off = len(arguments)
|
720 |
+
|
721 |
+
# For information why this is necessary refer to the handling
|
722 |
+
# of caller in the `macro_body` handler in the compiler.
|
723 |
+
found_caller = False
|
724 |
+
|
725 |
+
# if the number of arguments consumed is not the number of
|
726 |
+
# arguments expected we start filling in keyword arguments
|
727 |
+
# and defaults.
|
728 |
+
if off != self._argument_count:
|
729 |
+
for name in self.arguments[len(arguments) :]:
|
730 |
+
try:
|
731 |
+
value = kwargs.pop(name)
|
732 |
+
except KeyError:
|
733 |
+
value = missing
|
734 |
+
if name == "caller":
|
735 |
+
found_caller = True
|
736 |
+
arguments.append(value)
|
737 |
+
else:
|
738 |
+
found_caller = self.explicit_caller
|
739 |
+
|
740 |
+
# it's important that the order of these arguments does not change
|
741 |
+
# if not also changed in the compiler's `function_scoping` method.
|
742 |
+
# the order is caller, keyword arguments, positional arguments!
|
743 |
+
if self.caller and not found_caller:
|
744 |
+
caller = kwargs.pop("caller", None)
|
745 |
+
if caller is None:
|
746 |
+
caller = self._environment.undefined("No caller defined", name="caller")
|
747 |
+
arguments.append(caller)
|
748 |
+
|
749 |
+
if self.catch_kwargs:
|
750 |
+
arguments.append(kwargs)
|
751 |
+
elif kwargs:
|
752 |
+
if "caller" in kwargs:
|
753 |
+
raise TypeError(
|
754 |
+
f"macro {self.name!r} was invoked with two values for the special"
|
755 |
+
" caller argument. This is most likely a bug."
|
756 |
+
)
|
757 |
+
raise TypeError(
|
758 |
+
f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"
|
759 |
+
)
|
760 |
+
if self.catch_varargs:
|
761 |
+
arguments.append(args[self._argument_count :])
|
762 |
+
elif len(args) > self._argument_count:
|
763 |
+
raise TypeError(
|
764 |
+
f"macro {self.name!r} takes not more than"
|
765 |
+
f" {len(self.arguments)} argument(s)"
|
766 |
+
)
|
767 |
+
|
768 |
+
return self._invoke(arguments, autoescape)
|
769 |
+
|
770 |
+
async def _async_invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:
|
771 |
+
rv = await self._func(*arguments) # type: ignore
|
772 |
+
|
773 |
+
if autoescape:
|
774 |
+
return Markup(rv)
|
775 |
+
|
776 |
+
return rv # type: ignore
|
777 |
+
|
778 |
+
def _invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:
|
779 |
+
if self._environment.is_async:
|
780 |
+
return self._async_invoke(arguments, autoescape) # type: ignore
|
781 |
+
|
782 |
+
rv = self._func(*arguments)
|
783 |
+
|
784 |
+
if autoescape:
|
785 |
+
rv = Markup(rv)
|
786 |
+
|
787 |
+
return rv
|
788 |
+
|
789 |
+
def __repr__(self) -> str:
|
790 |
+
name = "anonymous" if self.name is None else repr(self.name)
|
791 |
+
return f"<{type(self).__name__} {name}>"
|
792 |
+
|
793 |
+
|
794 |
+
class Undefined:
|
795 |
+
"""The default undefined type. This undefined type can be printed and
|
796 |
+
iterated over, but every other access will raise an :exc:`UndefinedError`:
|
797 |
+
|
798 |
+
>>> foo = Undefined(name='foo')
|
799 |
+
>>> str(foo)
|
800 |
+
''
|
801 |
+
>>> not foo
|
802 |
+
True
|
803 |
+
>>> foo + 42
|
804 |
+
Traceback (most recent call last):
|
805 |
+
...
|
806 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
807 |
+
"""
|
808 |
+
|
809 |
+
__slots__ = (
|
810 |
+
"_undefined_hint",
|
811 |
+
"_undefined_obj",
|
812 |
+
"_undefined_name",
|
813 |
+
"_undefined_exception",
|
814 |
+
)
|
815 |
+
|
816 |
+
def __init__(
|
817 |
+
self,
|
818 |
+
hint: t.Optional[str] = None,
|
819 |
+
obj: t.Any = missing,
|
820 |
+
name: t.Optional[str] = None,
|
821 |
+
exc: t.Type[TemplateRuntimeError] = UndefinedError,
|
822 |
+
) -> None:
|
823 |
+
self._undefined_hint = hint
|
824 |
+
self._undefined_obj = obj
|
825 |
+
self._undefined_name = name
|
826 |
+
self._undefined_exception = exc
|
827 |
+
|
828 |
+
@property
|
829 |
+
def _undefined_message(self) -> str:
|
830 |
+
"""Build a message about the undefined value based on how it was
|
831 |
+
accessed.
|
832 |
+
"""
|
833 |
+
if self._undefined_hint:
|
834 |
+
return self._undefined_hint
|
835 |
+
|
836 |
+
if self._undefined_obj is missing:
|
837 |
+
return f"{self._undefined_name!r} is undefined"
|
838 |
+
|
839 |
+
if not isinstance(self._undefined_name, str):
|
840 |
+
return (
|
841 |
+
f"{object_type_repr(self._undefined_obj)} has no"
|
842 |
+
f" element {self._undefined_name!r}"
|
843 |
+
)
|
844 |
+
|
845 |
+
return (
|
846 |
+
f"{object_type_repr(self._undefined_obj)!r} has no"
|
847 |
+
f" attribute {self._undefined_name!r}"
|
848 |
+
)
|
849 |
+
|
850 |
+
@internalcode
|
851 |
+
def _fail_with_undefined_error(
|
852 |
+
self, *args: t.Any, **kwargs: t.Any
|
853 |
+
) -> "te.NoReturn":
|
854 |
+
"""Raise an :exc:`UndefinedError` when operations are performed
|
855 |
+
on the undefined value.
|
856 |
+
"""
|
857 |
+
raise self._undefined_exception(self._undefined_message)
|
858 |
+
|
859 |
+
@internalcode
|
860 |
+
def __getattr__(self, name: str) -> t.Any:
|
861 |
+
if name[:2] == "__":
|
862 |
+
raise AttributeError(name)
|
863 |
+
|
864 |
+
return self._fail_with_undefined_error()
|
865 |
+
|
866 |
+
__add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error
|
867 |
+
__mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error
|
868 |
+
__truediv__ = __rtruediv__ = _fail_with_undefined_error
|
869 |
+
__floordiv__ = __rfloordiv__ = _fail_with_undefined_error
|
870 |
+
__mod__ = __rmod__ = _fail_with_undefined_error
|
871 |
+
__pos__ = __neg__ = _fail_with_undefined_error
|
872 |
+
__call__ = __getitem__ = _fail_with_undefined_error
|
873 |
+
__lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error
|
874 |
+
__int__ = __float__ = __complex__ = _fail_with_undefined_error
|
875 |
+
__pow__ = __rpow__ = _fail_with_undefined_error
|
876 |
+
|
877 |
+
def __eq__(self, other: t.Any) -> bool:
|
878 |
+
return type(self) is type(other)
|
879 |
+
|
880 |
+
def __ne__(self, other: t.Any) -> bool:
|
881 |
+
return not self.__eq__(other)
|
882 |
+
|
883 |
+
def __hash__(self) -> int:
|
884 |
+
return id(type(self))
|
885 |
+
|
886 |
+
def __str__(self) -> str:
|
887 |
+
return ""
|
888 |
+
|
889 |
+
def __len__(self) -> int:
|
890 |
+
return 0
|
891 |
+
|
892 |
+
def __iter__(self) -> t.Iterator[t.Any]:
|
893 |
+
yield from ()
|
894 |
+
|
895 |
+
async def __aiter__(self) -> t.AsyncIterator[t.Any]:
|
896 |
+
for _ in ():
|
897 |
+
yield
|
898 |
+
|
899 |
+
def __bool__(self) -> bool:
|
900 |
+
return False
|
901 |
+
|
902 |
+
def __repr__(self) -> str:
|
903 |
+
return "Undefined"
|
904 |
+
|
905 |
+
|
906 |
+
def make_logging_undefined(
|
907 |
+
logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined
|
908 |
+
) -> t.Type[Undefined]:
|
909 |
+
"""Given a logger object this returns a new undefined class that will
|
910 |
+
log certain failures. It will log iterations and printing. If no
|
911 |
+
logger is given a default logger is created.
|
912 |
+
|
913 |
+
Example::
|
914 |
+
|
915 |
+
logger = logging.getLogger(__name__)
|
916 |
+
LoggingUndefined = make_logging_undefined(
|
917 |
+
logger=logger,
|
918 |
+
base=Undefined
|
919 |
+
)
|
920 |
+
|
921 |
+
.. versionadded:: 2.8
|
922 |
+
|
923 |
+
:param logger: the logger to use. If not provided, a default logger
|
924 |
+
is created.
|
925 |
+
:param base: the base class to add logging functionality to. This
|
926 |
+
defaults to :class:`Undefined`.
|
927 |
+
"""
|
928 |
+
if logger is None:
|
929 |
+
import logging
|
930 |
+
|
931 |
+
logger = logging.getLogger(__name__)
|
932 |
+
logger.addHandler(logging.StreamHandler(sys.stderr))
|
933 |
+
|
934 |
+
def _log_message(undef: Undefined) -> None:
|
935 |
+
logger.warning("Template variable warning: %s", undef._undefined_message)
|
936 |
+
|
937 |
+
class LoggingUndefined(base): # type: ignore
|
938 |
+
__slots__ = ()
|
939 |
+
|
940 |
+
def _fail_with_undefined_error( # type: ignore
|
941 |
+
self, *args: t.Any, **kwargs: t.Any
|
942 |
+
) -> "te.NoReturn":
|
943 |
+
try:
|
944 |
+
super()._fail_with_undefined_error(*args, **kwargs)
|
945 |
+
except self._undefined_exception as e:
|
946 |
+
logger.error("Template variable error: %s", e) # type: ignore
|
947 |
+
raise e
|
948 |
+
|
949 |
+
def __str__(self) -> str:
|
950 |
+
_log_message(self)
|
951 |
+
return super().__str__() # type: ignore
|
952 |
+
|
953 |
+
def __iter__(self) -> t.Iterator[t.Any]:
|
954 |
+
_log_message(self)
|
955 |
+
return super().__iter__() # type: ignore
|
956 |
+
|
957 |
+
def __bool__(self) -> bool:
|
958 |
+
_log_message(self)
|
959 |
+
return super().__bool__() # type: ignore
|
960 |
+
|
961 |
+
return LoggingUndefined
|
962 |
+
|
963 |
+
|
964 |
+
class ChainableUndefined(Undefined):
|
965 |
+
"""An undefined that is chainable, where both ``__getattr__`` and
|
966 |
+
``__getitem__`` return itself rather than raising an
|
967 |
+
:exc:`UndefinedError`.
|
968 |
+
|
969 |
+
>>> foo = ChainableUndefined(name='foo')
|
970 |
+
>>> str(foo.bar['baz'])
|
971 |
+
''
|
972 |
+
>>> foo.bar['baz'] + 42
|
973 |
+
Traceback (most recent call last):
|
974 |
+
...
|
975 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
976 |
+
|
977 |
+
.. versionadded:: 2.11.0
|
978 |
+
"""
|
979 |
+
|
980 |
+
__slots__ = ()
|
981 |
+
|
982 |
+
def __html__(self) -> str:
|
983 |
+
return str(self)
|
984 |
+
|
985 |
+
def __getattr__(self, _: str) -> "ChainableUndefined":
|
986 |
+
return self
|
987 |
+
|
988 |
+
__getitem__ = __getattr__ # type: ignore
|
989 |
+
|
990 |
+
|
991 |
+
class DebugUndefined(Undefined):
|
992 |
+
"""An undefined that returns the debug info when printed.
|
993 |
+
|
994 |
+
>>> foo = DebugUndefined(name='foo')
|
995 |
+
>>> str(foo)
|
996 |
+
'{{ foo }}'
|
997 |
+
>>> not foo
|
998 |
+
True
|
999 |
+
>>> foo + 42
|
1000 |
+
Traceback (most recent call last):
|
1001 |
+
...
|
1002 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
1003 |
+
"""
|
1004 |
+
|
1005 |
+
__slots__ = ()
|
1006 |
+
|
1007 |
+
def __str__(self) -> str:
|
1008 |
+
if self._undefined_hint:
|
1009 |
+
message = f"undefined value printed: {self._undefined_hint}"
|
1010 |
+
|
1011 |
+
elif self._undefined_obj is missing:
|
1012 |
+
message = self._undefined_name # type: ignore
|
1013 |
+
|
1014 |
+
else:
|
1015 |
+
message = (
|
1016 |
+
f"no such element: {object_type_repr(self._undefined_obj)}"
|
1017 |
+
f"[{self._undefined_name!r}]"
|
1018 |
+
)
|
1019 |
+
|
1020 |
+
return f"{{{{ {message} }}}}"
|
1021 |
+
|
1022 |
+
|
1023 |
+
class StrictUndefined(Undefined):
|
1024 |
+
"""An undefined that barks on print and iteration as well as boolean
|
1025 |
+
tests and all kinds of comparisons. In other words: you can do nothing
|
1026 |
+
with it except checking if it's defined using the `defined` test.
|
1027 |
+
|
1028 |
+
>>> foo = StrictUndefined(name='foo')
|
1029 |
+
>>> str(foo)
|
1030 |
+
Traceback (most recent call last):
|
1031 |
+
...
|
1032 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
1033 |
+
>>> not foo
|
1034 |
+
Traceback (most recent call last):
|
1035 |
+
...
|
1036 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
1037 |
+
>>> foo + 42
|
1038 |
+
Traceback (most recent call last):
|
1039 |
+
...
|
1040 |
+
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
1041 |
+
"""
|
1042 |
+
|
1043 |
+
__slots__ = ()
|
1044 |
+
__iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error
|
1045 |
+
__eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error
|
1046 |
+
__contains__ = Undefined._fail_with_undefined_error
|
1047 |
+
|
1048 |
+
|
1049 |
+
# Remove slots attributes, after the metaclass is applied they are
|
1050 |
+
# unneeded and contain wrong data for subclasses.
|
1051 |
+
del (
|
1052 |
+
Undefined.__slots__,
|
1053 |
+
ChainableUndefined.__slots__,
|
1054 |
+
DebugUndefined.__slots__,
|
1055 |
+
StrictUndefined.__slots__,
|
1056 |
+
)
|
llmeval-env/lib/python3.10/site-packages/jinja2/tests.py
ADDED
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Built-in template tests used with the ``is`` operator."""
|
2 |
+
|
3 |
+
import operator
|
4 |
+
import typing as t
|
5 |
+
from collections import abc
|
6 |
+
from numbers import Number
|
7 |
+
|
8 |
+
from .runtime import Undefined
|
9 |
+
from .utils import pass_environment
|
10 |
+
|
11 |
+
if t.TYPE_CHECKING:
|
12 |
+
from .environment import Environment
|
13 |
+
|
14 |
+
|
15 |
+
def test_odd(value: int) -> bool:
|
16 |
+
"""Return true if the variable is odd."""
|
17 |
+
return value % 2 == 1
|
18 |
+
|
19 |
+
|
20 |
+
def test_even(value: int) -> bool:
|
21 |
+
"""Return true if the variable is even."""
|
22 |
+
return value % 2 == 0
|
23 |
+
|
24 |
+
|
25 |
+
def test_divisibleby(value: int, num: int) -> bool:
|
26 |
+
"""Check if a variable is divisible by a number."""
|
27 |
+
return value % num == 0
|
28 |
+
|
29 |
+
|
30 |
+
def test_defined(value: t.Any) -> bool:
|
31 |
+
"""Return true if the variable is defined:
|
32 |
+
|
33 |
+
.. sourcecode:: jinja
|
34 |
+
|
35 |
+
{% if variable is defined %}
|
36 |
+
value of variable: {{ variable }}
|
37 |
+
{% else %}
|
38 |
+
variable is not defined
|
39 |
+
{% endif %}
|
40 |
+
|
41 |
+
See the :func:`default` filter for a simple way to set undefined
|
42 |
+
variables.
|
43 |
+
"""
|
44 |
+
return not isinstance(value, Undefined)
|
45 |
+
|
46 |
+
|
47 |
+
def test_undefined(value: t.Any) -> bool:
|
48 |
+
"""Like :func:`defined` but the other way round."""
|
49 |
+
return isinstance(value, Undefined)
|
50 |
+
|
51 |
+
|
52 |
+
@pass_environment
|
53 |
+
def test_filter(env: "Environment", value: str) -> bool:
|
54 |
+
"""Check if a filter exists by name. Useful if a filter may be
|
55 |
+
optionally available.
|
56 |
+
|
57 |
+
.. code-block:: jinja
|
58 |
+
|
59 |
+
{% if 'markdown' is filter %}
|
60 |
+
{{ value | markdown }}
|
61 |
+
{% else %}
|
62 |
+
{{ value }}
|
63 |
+
{% endif %}
|
64 |
+
|
65 |
+
.. versionadded:: 3.0
|
66 |
+
"""
|
67 |
+
return value in env.filters
|
68 |
+
|
69 |
+
|
70 |
+
@pass_environment
|
71 |
+
def test_test(env: "Environment", value: str) -> bool:
|
72 |
+
"""Check if a test exists by name. Useful if a test may be
|
73 |
+
optionally available.
|
74 |
+
|
75 |
+
.. code-block:: jinja
|
76 |
+
|
77 |
+
{% if 'loud' is test %}
|
78 |
+
{% if value is loud %}
|
79 |
+
{{ value|upper }}
|
80 |
+
{% else %}
|
81 |
+
{{ value|lower }}
|
82 |
+
{% endif %}
|
83 |
+
{% else %}
|
84 |
+
{{ value }}
|
85 |
+
{% endif %}
|
86 |
+
|
87 |
+
.. versionadded:: 3.0
|
88 |
+
"""
|
89 |
+
return value in env.tests
|
90 |
+
|
91 |
+
|
92 |
+
def test_none(value: t.Any) -> bool:
|
93 |
+
"""Return true if the variable is none."""
|
94 |
+
return value is None
|
95 |
+
|
96 |
+
|
97 |
+
def test_boolean(value: t.Any) -> bool:
|
98 |
+
"""Return true if the object is a boolean value.
|
99 |
+
|
100 |
+
.. versionadded:: 2.11
|
101 |
+
"""
|
102 |
+
return value is True or value is False
|
103 |
+
|
104 |
+
|
105 |
+
def test_false(value: t.Any) -> bool:
|
106 |
+
"""Return true if the object is False.
|
107 |
+
|
108 |
+
.. versionadded:: 2.11
|
109 |
+
"""
|
110 |
+
return value is False
|
111 |
+
|
112 |
+
|
113 |
+
def test_true(value: t.Any) -> bool:
|
114 |
+
"""Return true if the object is True.
|
115 |
+
|
116 |
+
.. versionadded:: 2.11
|
117 |
+
"""
|
118 |
+
return value is True
|
119 |
+
|
120 |
+
|
121 |
+
# NOTE: The existing 'number' test matches booleans and floats
|
122 |
+
def test_integer(value: t.Any) -> bool:
|
123 |
+
"""Return true if the object is an integer.
|
124 |
+
|
125 |
+
.. versionadded:: 2.11
|
126 |
+
"""
|
127 |
+
return isinstance(value, int) and value is not True and value is not False
|
128 |
+
|
129 |
+
|
130 |
+
# NOTE: The existing 'number' test matches booleans and integers
|
131 |
+
def test_float(value: t.Any) -> bool:
|
132 |
+
"""Return true if the object is a float.
|
133 |
+
|
134 |
+
.. versionadded:: 2.11
|
135 |
+
"""
|
136 |
+
return isinstance(value, float)
|
137 |
+
|
138 |
+
|
139 |
+
def test_lower(value: str) -> bool:
|
140 |
+
"""Return true if the variable is lowercased."""
|
141 |
+
return str(value).islower()
|
142 |
+
|
143 |
+
|
144 |
+
def test_upper(value: str) -> bool:
|
145 |
+
"""Return true if the variable is uppercased."""
|
146 |
+
return str(value).isupper()
|
147 |
+
|
148 |
+
|
149 |
+
def test_string(value: t.Any) -> bool:
|
150 |
+
"""Return true if the object is a string."""
|
151 |
+
return isinstance(value, str)
|
152 |
+
|
153 |
+
|
154 |
+
def test_mapping(value: t.Any) -> bool:
|
155 |
+
"""Return true if the object is a mapping (dict etc.).
|
156 |
+
|
157 |
+
.. versionadded:: 2.6
|
158 |
+
"""
|
159 |
+
return isinstance(value, abc.Mapping)
|
160 |
+
|
161 |
+
|
162 |
+
def test_number(value: t.Any) -> bool:
|
163 |
+
"""Return true if the variable is a number."""
|
164 |
+
return isinstance(value, Number)
|
165 |
+
|
166 |
+
|
167 |
+
def test_sequence(value: t.Any) -> bool:
|
168 |
+
"""Return true if the variable is a sequence. Sequences are variables
|
169 |
+
that are iterable.
|
170 |
+
"""
|
171 |
+
try:
|
172 |
+
len(value)
|
173 |
+
value.__getitem__ # noqa B018
|
174 |
+
except Exception:
|
175 |
+
return False
|
176 |
+
|
177 |
+
return True
|
178 |
+
|
179 |
+
|
180 |
+
def test_sameas(value: t.Any, other: t.Any) -> bool:
|
181 |
+
"""Check if an object points to the same memory address than another
|
182 |
+
object:
|
183 |
+
|
184 |
+
.. sourcecode:: jinja
|
185 |
+
|
186 |
+
{% if foo.attribute is sameas false %}
|
187 |
+
the foo attribute really is the `False` singleton
|
188 |
+
{% endif %}
|
189 |
+
"""
|
190 |
+
return value is other
|
191 |
+
|
192 |
+
|
193 |
+
def test_iterable(value: t.Any) -> bool:
|
194 |
+
"""Check if it's possible to iterate over an object."""
|
195 |
+
try:
|
196 |
+
iter(value)
|
197 |
+
except TypeError:
|
198 |
+
return False
|
199 |
+
|
200 |
+
return True
|
201 |
+
|
202 |
+
|
203 |
+
def test_escaped(value: t.Any) -> bool:
|
204 |
+
"""Check if the value is escaped."""
|
205 |
+
return hasattr(value, "__html__")
|
206 |
+
|
207 |
+
|
208 |
+
def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:
|
209 |
+
"""Check if value is in seq.
|
210 |
+
|
211 |
+
.. versionadded:: 2.10
|
212 |
+
"""
|
213 |
+
return value in seq
|
214 |
+
|
215 |
+
|
216 |
+
TESTS = {
|
217 |
+
"odd": test_odd,
|
218 |
+
"even": test_even,
|
219 |
+
"divisibleby": test_divisibleby,
|
220 |
+
"defined": test_defined,
|
221 |
+
"undefined": test_undefined,
|
222 |
+
"filter": test_filter,
|
223 |
+
"test": test_test,
|
224 |
+
"none": test_none,
|
225 |
+
"boolean": test_boolean,
|
226 |
+
"false": test_false,
|
227 |
+
"true": test_true,
|
228 |
+
"integer": test_integer,
|
229 |
+
"float": test_float,
|
230 |
+
"lower": test_lower,
|
231 |
+
"upper": test_upper,
|
232 |
+
"string": test_string,
|
233 |
+
"mapping": test_mapping,
|
234 |
+
"number": test_number,
|
235 |
+
"sequence": test_sequence,
|
236 |
+
"iterable": test_iterable,
|
237 |
+
"callable": callable,
|
238 |
+
"sameas": test_sameas,
|
239 |
+
"escaped": test_escaped,
|
240 |
+
"in": test_in,
|
241 |
+
"==": operator.eq,
|
242 |
+
"eq": operator.eq,
|
243 |
+
"equalto": operator.eq,
|
244 |
+
"!=": operator.ne,
|
245 |
+
"ne": operator.ne,
|
246 |
+
">": operator.gt,
|
247 |
+
"gt": operator.gt,
|
248 |
+
"greaterthan": operator.gt,
|
249 |
+
"ge": operator.ge,
|
250 |
+
">=": operator.ge,
|
251 |
+
"<": operator.lt,
|
252 |
+
"lt": operator.lt,
|
253 |
+
"lessthan": operator.lt,
|
254 |
+
"<=": operator.le,
|
255 |
+
"le": operator.le,
|
256 |
+
}
|
llmeval-env/lib/python3.10/site-packages/jinja2/utils.py
ADDED
@@ -0,0 +1,755 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import enum
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import typing as t
|
6 |
+
from collections import abc
|
7 |
+
from collections import deque
|
8 |
+
from random import choice
|
9 |
+
from random import randrange
|
10 |
+
from threading import Lock
|
11 |
+
from types import CodeType
|
12 |
+
from urllib.parse import quote_from_bytes
|
13 |
+
|
14 |
+
import markupsafe
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
import typing_extensions as te
|
18 |
+
|
19 |
+
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
|
20 |
+
|
21 |
+
# special singleton representing missing values for the runtime
|
22 |
+
missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()
|
23 |
+
|
24 |
+
internal_code: t.MutableSet[CodeType] = set()
|
25 |
+
|
26 |
+
concat = "".join
|
27 |
+
|
28 |
+
|
29 |
+
def pass_context(f: F) -> F:
|
30 |
+
"""Pass the :class:`~jinja2.runtime.Context` as the first argument
|
31 |
+
to the decorated function when called while rendering a template.
|
32 |
+
|
33 |
+
Can be used on functions, filters, and tests.
|
34 |
+
|
35 |
+
If only ``Context.eval_context`` is needed, use
|
36 |
+
:func:`pass_eval_context`. If only ``Context.environment`` is
|
37 |
+
needed, use :func:`pass_environment`.
|
38 |
+
|
39 |
+
.. versionadded:: 3.0.0
|
40 |
+
Replaces ``contextfunction`` and ``contextfilter``.
|
41 |
+
"""
|
42 |
+
f.jinja_pass_arg = _PassArg.context # type: ignore
|
43 |
+
return f
|
44 |
+
|
45 |
+
|
46 |
+
def pass_eval_context(f: F) -> F:
|
47 |
+
"""Pass the :class:`~jinja2.nodes.EvalContext` as the first argument
|
48 |
+
to the decorated function when called while rendering a template.
|
49 |
+
See :ref:`eval-context`.
|
50 |
+
|
51 |
+
Can be used on functions, filters, and tests.
|
52 |
+
|
53 |
+
If only ``EvalContext.environment`` is needed, use
|
54 |
+
:func:`pass_environment`.
|
55 |
+
|
56 |
+
.. versionadded:: 3.0.0
|
57 |
+
Replaces ``evalcontextfunction`` and ``evalcontextfilter``.
|
58 |
+
"""
|
59 |
+
f.jinja_pass_arg = _PassArg.eval_context # type: ignore
|
60 |
+
return f
|
61 |
+
|
62 |
+
|
63 |
+
def pass_environment(f: F) -> F:
|
64 |
+
"""Pass the :class:`~jinja2.Environment` as the first argument to
|
65 |
+
the decorated function when called while rendering a template.
|
66 |
+
|
67 |
+
Can be used on functions, filters, and tests.
|
68 |
+
|
69 |
+
.. versionadded:: 3.0.0
|
70 |
+
Replaces ``environmentfunction`` and ``environmentfilter``.
|
71 |
+
"""
|
72 |
+
f.jinja_pass_arg = _PassArg.environment # type: ignore
|
73 |
+
return f
|
74 |
+
|
75 |
+
|
76 |
+
class _PassArg(enum.Enum):
|
77 |
+
context = enum.auto()
|
78 |
+
eval_context = enum.auto()
|
79 |
+
environment = enum.auto()
|
80 |
+
|
81 |
+
@classmethod
|
82 |
+
def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:
|
83 |
+
if hasattr(obj, "jinja_pass_arg"):
|
84 |
+
return obj.jinja_pass_arg # type: ignore
|
85 |
+
|
86 |
+
return None
|
87 |
+
|
88 |
+
|
89 |
+
def internalcode(f: F) -> F:
|
90 |
+
"""Marks the function as internally used"""
|
91 |
+
internal_code.add(f.__code__)
|
92 |
+
return f
|
93 |
+
|
94 |
+
|
95 |
+
def is_undefined(obj: t.Any) -> bool:
|
96 |
+
"""Check if the object passed is undefined. This does nothing more than
|
97 |
+
performing an instance check against :class:`Undefined` but looks nicer.
|
98 |
+
This can be used for custom filters or tests that want to react to
|
99 |
+
undefined variables. For example a custom default filter can look like
|
100 |
+
this::
|
101 |
+
|
102 |
+
def default(var, default=''):
|
103 |
+
if is_undefined(var):
|
104 |
+
return default
|
105 |
+
return var
|
106 |
+
"""
|
107 |
+
from .runtime import Undefined
|
108 |
+
|
109 |
+
return isinstance(obj, Undefined)
|
110 |
+
|
111 |
+
|
112 |
+
def consume(iterable: t.Iterable[t.Any]) -> None:
|
113 |
+
"""Consumes an iterable without doing anything with it."""
|
114 |
+
for _ in iterable:
|
115 |
+
pass
|
116 |
+
|
117 |
+
|
118 |
+
def clear_caches() -> None:
|
119 |
+
"""Jinja keeps internal caches for environments and lexers. These are
|
120 |
+
used so that Jinja doesn't have to recreate environments and lexers all
|
121 |
+
the time. Normally you don't have to care about that but if you are
|
122 |
+
measuring memory consumption you may want to clean the caches.
|
123 |
+
"""
|
124 |
+
from .environment import get_spontaneous_environment
|
125 |
+
from .lexer import _lexer_cache
|
126 |
+
|
127 |
+
get_spontaneous_environment.cache_clear()
|
128 |
+
_lexer_cache.clear()
|
129 |
+
|
130 |
+
|
131 |
+
def import_string(import_name: str, silent: bool = False) -> t.Any:
|
132 |
+
"""Imports an object based on a string. This is useful if you want to
|
133 |
+
use import paths as endpoints or something similar. An import path can
|
134 |
+
be specified either in dotted notation (``xml.sax.saxutils.escape``)
|
135 |
+
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
|
136 |
+
|
137 |
+
If the `silent` is True the return value will be `None` if the import
|
138 |
+
fails.
|
139 |
+
|
140 |
+
:return: imported object
|
141 |
+
"""
|
142 |
+
try:
|
143 |
+
if ":" in import_name:
|
144 |
+
module, obj = import_name.split(":", 1)
|
145 |
+
elif "." in import_name:
|
146 |
+
module, _, obj = import_name.rpartition(".")
|
147 |
+
else:
|
148 |
+
return __import__(import_name)
|
149 |
+
return getattr(__import__(module, None, None, [obj]), obj)
|
150 |
+
except (ImportError, AttributeError):
|
151 |
+
if not silent:
|
152 |
+
raise
|
153 |
+
|
154 |
+
|
155 |
+
def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO[t.Any]]:
|
156 |
+
"""Returns a file descriptor for the filename if that file exists,
|
157 |
+
otherwise ``None``.
|
158 |
+
"""
|
159 |
+
if not os.path.isfile(filename):
|
160 |
+
return None
|
161 |
+
|
162 |
+
return open(filename, mode)
|
163 |
+
|
164 |
+
|
165 |
+
def object_type_repr(obj: t.Any) -> str:
|
166 |
+
"""Returns the name of the object's type. For some recognized
|
167 |
+
singletons the name of the object is returned instead. (For
|
168 |
+
example for `None` and `Ellipsis`).
|
169 |
+
"""
|
170 |
+
if obj is None:
|
171 |
+
return "None"
|
172 |
+
elif obj is Ellipsis:
|
173 |
+
return "Ellipsis"
|
174 |
+
|
175 |
+
cls = type(obj)
|
176 |
+
|
177 |
+
if cls.__module__ == "builtins":
|
178 |
+
return f"{cls.__name__} object"
|
179 |
+
|
180 |
+
return f"{cls.__module__}.{cls.__name__} object"
|
181 |
+
|
182 |
+
|
183 |
+
def pformat(obj: t.Any) -> str:
|
184 |
+
"""Format an object using :func:`pprint.pformat`."""
|
185 |
+
from pprint import pformat
|
186 |
+
|
187 |
+
return pformat(obj)
|
188 |
+
|
189 |
+
|
190 |
+
_http_re = re.compile(
|
191 |
+
r"""
|
192 |
+
^
|
193 |
+
(
|
194 |
+
(https?://|www\.) # scheme or www
|
195 |
+
(([\w%-]+\.)+)? # subdomain
|
196 |
+
(
|
197 |
+
[a-z]{2,63} # basic tld
|
198 |
+
|
|
199 |
+
xn--[\w%]{2,59} # idna tld
|
200 |
+
)
|
201 |
+
|
|
202 |
+
([\w%-]{2,63}\.)+ # basic domain
|
203 |
+
(com|net|int|edu|gov|org|info|mil) # basic tld
|
204 |
+
|
|
205 |
+
(https?://) # scheme
|
206 |
+
(
|
207 |
+
(([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4
|
208 |
+
|
|
209 |
+
(\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6
|
210 |
+
)
|
211 |
+
)
|
212 |
+
(?::[\d]{1,5})? # port
|
213 |
+
(?:[/?#]\S*)? # path, query, and fragment
|
214 |
+
$
|
215 |
+
""",
|
216 |
+
re.IGNORECASE | re.VERBOSE,
|
217 |
+
)
|
218 |
+
_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")
|
219 |
+
|
220 |
+
|
221 |
+
def urlize(
|
222 |
+
text: str,
|
223 |
+
trim_url_limit: t.Optional[int] = None,
|
224 |
+
rel: t.Optional[str] = None,
|
225 |
+
target: t.Optional[str] = None,
|
226 |
+
extra_schemes: t.Optional[t.Iterable[str]] = None,
|
227 |
+
) -> str:
|
228 |
+
"""Convert URLs in text into clickable links.
|
229 |
+
|
230 |
+
This may not recognize links in some situations. Usually, a more
|
231 |
+
comprehensive formatter, such as a Markdown library, is a better
|
232 |
+
choice.
|
233 |
+
|
234 |
+
Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
|
235 |
+
addresses. Links with trailing punctuation (periods, commas, closing
|
236 |
+
parentheses) and leading punctuation (opening parentheses) are
|
237 |
+
recognized excluding the punctuation. Email addresses that include
|
238 |
+
header fields are not recognized (for example,
|
239 |
+
``mailto:[email protected][email protected]``).
|
240 |
+
|
241 |
+
:param text: Original text containing URLs to link.
|
242 |
+
:param trim_url_limit: Shorten displayed URL values to this length.
|
243 |
+
:param target: Add the ``target`` attribute to links.
|
244 |
+
:param rel: Add the ``rel`` attribute to links.
|
245 |
+
:param extra_schemes: Recognize URLs that start with these schemes
|
246 |
+
in addition to the default behavior.
|
247 |
+
|
248 |
+
.. versionchanged:: 3.0
|
249 |
+
The ``extra_schemes`` parameter was added.
|
250 |
+
|
251 |
+
.. versionchanged:: 3.0
|
252 |
+
Generate ``https://`` links for URLs without a scheme.
|
253 |
+
|
254 |
+
.. versionchanged:: 3.0
|
255 |
+
The parsing rules were updated. Recognize email addresses with
|
256 |
+
or without the ``mailto:`` scheme. Validate IP addresses. Ignore
|
257 |
+
parentheses and brackets in more cases.
|
258 |
+
"""
|
259 |
+
if trim_url_limit is not None:
|
260 |
+
|
261 |
+
def trim_url(x: str) -> str:
|
262 |
+
if len(x) > trim_url_limit:
|
263 |
+
return f"{x[:trim_url_limit]}..."
|
264 |
+
|
265 |
+
return x
|
266 |
+
|
267 |
+
else:
|
268 |
+
|
269 |
+
def trim_url(x: str) -> str:
|
270 |
+
return x
|
271 |
+
|
272 |
+
words = re.split(r"(\s+)", str(markupsafe.escape(text)))
|
273 |
+
rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
|
274 |
+
target_attr = f' target="{markupsafe.escape(target)}"' if target else ""
|
275 |
+
|
276 |
+
for i, word in enumerate(words):
|
277 |
+
head, middle, tail = "", word, ""
|
278 |
+
match = re.match(r"^([(<]|<)+", middle)
|
279 |
+
|
280 |
+
if match:
|
281 |
+
head = match.group()
|
282 |
+
middle = middle[match.end() :]
|
283 |
+
|
284 |
+
# Unlike lead, which is anchored to the start of the string,
|
285 |
+
# need to check that the string ends with any of the characters
|
286 |
+
# before trying to match all of them, to avoid backtracking.
|
287 |
+
if middle.endswith((")", ">", ".", ",", "\n", ">")):
|
288 |
+
match = re.search(r"([)>.,\n]|>)+$", middle)
|
289 |
+
|
290 |
+
if match:
|
291 |
+
tail = match.group()
|
292 |
+
middle = middle[: match.start()]
|
293 |
+
|
294 |
+
# Prefer balancing parentheses in URLs instead of ignoring a
|
295 |
+
# trailing character.
|
296 |
+
for start_char, end_char in ("(", ")"), ("<", ">"), ("<", ">"):
|
297 |
+
start_count = middle.count(start_char)
|
298 |
+
|
299 |
+
if start_count <= middle.count(end_char):
|
300 |
+
# Balanced, or lighter on the left
|
301 |
+
continue
|
302 |
+
|
303 |
+
# Move as many as possible from the tail to balance
|
304 |
+
for _ in range(min(start_count, tail.count(end_char))):
|
305 |
+
end_index = tail.index(end_char) + len(end_char)
|
306 |
+
# Move anything in the tail before the end char too
|
307 |
+
middle += tail[:end_index]
|
308 |
+
tail = tail[end_index:]
|
309 |
+
|
310 |
+
if _http_re.match(middle):
|
311 |
+
if middle.startswith("https://") or middle.startswith("http://"):
|
312 |
+
middle = (
|
313 |
+
f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'
|
314 |
+
)
|
315 |
+
else:
|
316 |
+
middle = (
|
317 |
+
f'<a href="https://{middle}"{rel_attr}{target_attr}>'
|
318 |
+
f"{trim_url(middle)}</a>"
|
319 |
+
)
|
320 |
+
|
321 |
+
elif middle.startswith("mailto:") and _email_re.match(middle[7:]):
|
322 |
+
middle = f'<a href="{middle}">{middle[7:]}</a>'
|
323 |
+
|
324 |
+
elif (
|
325 |
+
"@" in middle
|
326 |
+
and not middle.startswith("www.")
|
327 |
+
and ":" not in middle
|
328 |
+
and _email_re.match(middle)
|
329 |
+
):
|
330 |
+
middle = f'<a href="mailto:{middle}">{middle}</a>'
|
331 |
+
|
332 |
+
elif extra_schemes is not None:
|
333 |
+
for scheme in extra_schemes:
|
334 |
+
if middle != scheme and middle.startswith(scheme):
|
335 |
+
middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'
|
336 |
+
|
337 |
+
words[i] = f"{head}{middle}{tail}"
|
338 |
+
|
339 |
+
return "".join(words)
|
340 |
+
|
341 |
+
|
342 |
+
def generate_lorem_ipsum(
|
343 |
+
n: int = 5, html: bool = True, min: int = 20, max: int = 100
|
344 |
+
) -> str:
|
345 |
+
"""Generate some lorem ipsum for the template."""
|
346 |
+
from .constants import LOREM_IPSUM_WORDS
|
347 |
+
|
348 |
+
words = LOREM_IPSUM_WORDS.split()
|
349 |
+
result = []
|
350 |
+
|
351 |
+
for _ in range(n):
|
352 |
+
next_capitalized = True
|
353 |
+
last_comma = last_fullstop = 0
|
354 |
+
word = None
|
355 |
+
last = None
|
356 |
+
p = []
|
357 |
+
|
358 |
+
# each paragraph contains out of 20 to 100 words.
|
359 |
+
for idx, _ in enumerate(range(randrange(min, max))):
|
360 |
+
while True:
|
361 |
+
word = choice(words)
|
362 |
+
if word != last:
|
363 |
+
last = word
|
364 |
+
break
|
365 |
+
if next_capitalized:
|
366 |
+
word = word.capitalize()
|
367 |
+
next_capitalized = False
|
368 |
+
# add commas
|
369 |
+
if idx - randrange(3, 8) > last_comma:
|
370 |
+
last_comma = idx
|
371 |
+
last_fullstop += 2
|
372 |
+
word += ","
|
373 |
+
# add end of sentences
|
374 |
+
if idx - randrange(10, 20) > last_fullstop:
|
375 |
+
last_comma = last_fullstop = idx
|
376 |
+
word += "."
|
377 |
+
next_capitalized = True
|
378 |
+
p.append(word)
|
379 |
+
|
380 |
+
# ensure that the paragraph ends with a dot.
|
381 |
+
p_str = " ".join(p)
|
382 |
+
|
383 |
+
if p_str.endswith(","):
|
384 |
+
p_str = p_str[:-1] + "."
|
385 |
+
elif not p_str.endswith("."):
|
386 |
+
p_str += "."
|
387 |
+
|
388 |
+
result.append(p_str)
|
389 |
+
|
390 |
+
if not html:
|
391 |
+
return "\n\n".join(result)
|
392 |
+
return markupsafe.Markup(
|
393 |
+
"\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
|
394 |
+
)
|
395 |
+
|
396 |
+
|
397 |
+
def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:
|
398 |
+
"""Quote a string for use in a URL using the given charset.
|
399 |
+
|
400 |
+
:param obj: String or bytes to quote. Other types are converted to
|
401 |
+
string then encoded to bytes using the given charset.
|
402 |
+
:param charset: Encode text to bytes using this charset.
|
403 |
+
:param for_qs: Quote "/" and use "+" for spaces.
|
404 |
+
"""
|
405 |
+
if not isinstance(obj, bytes):
|
406 |
+
if not isinstance(obj, str):
|
407 |
+
obj = str(obj)
|
408 |
+
|
409 |
+
obj = obj.encode(charset)
|
410 |
+
|
411 |
+
safe = b"" if for_qs else b"/"
|
412 |
+
rv = quote_from_bytes(obj, safe)
|
413 |
+
|
414 |
+
if for_qs:
|
415 |
+
rv = rv.replace("%20", "+")
|
416 |
+
|
417 |
+
return rv
|
418 |
+
|
419 |
+
|
420 |
+
@abc.MutableMapping.register
|
421 |
+
class LRUCache:
|
422 |
+
"""A simple LRU Cache implementation."""
|
423 |
+
|
424 |
+
# this is fast for small capacities (something below 1000) but doesn't
|
425 |
+
# scale. But as long as it's only used as storage for templates this
|
426 |
+
# won't do any harm.
|
427 |
+
|
428 |
+
def __init__(self, capacity: int) -> None:
|
429 |
+
self.capacity = capacity
|
430 |
+
self._mapping: t.Dict[t.Any, t.Any] = {}
|
431 |
+
self._queue: "te.Deque[t.Any]" = deque()
|
432 |
+
self._postinit()
|
433 |
+
|
434 |
+
def _postinit(self) -> None:
|
435 |
+
# alias all queue methods for faster lookup
|
436 |
+
self._popleft = self._queue.popleft
|
437 |
+
self._pop = self._queue.pop
|
438 |
+
self._remove = self._queue.remove
|
439 |
+
self._wlock = Lock()
|
440 |
+
self._append = self._queue.append
|
441 |
+
|
442 |
+
def __getstate__(self) -> t.Mapping[str, t.Any]:
|
443 |
+
return {
|
444 |
+
"capacity": self.capacity,
|
445 |
+
"_mapping": self._mapping,
|
446 |
+
"_queue": self._queue,
|
447 |
+
}
|
448 |
+
|
449 |
+
def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:
|
450 |
+
self.__dict__.update(d)
|
451 |
+
self._postinit()
|
452 |
+
|
453 |
+
def __getnewargs__(self) -> t.Tuple[t.Any, ...]:
|
454 |
+
return (self.capacity,)
|
455 |
+
|
456 |
+
def copy(self) -> "LRUCache":
|
457 |
+
"""Return a shallow copy of the instance."""
|
458 |
+
rv = self.__class__(self.capacity)
|
459 |
+
rv._mapping.update(self._mapping)
|
460 |
+
rv._queue.extend(self._queue)
|
461 |
+
return rv
|
462 |
+
|
463 |
+
def get(self, key: t.Any, default: t.Any = None) -> t.Any:
|
464 |
+
"""Return an item from the cache dict or `default`"""
|
465 |
+
try:
|
466 |
+
return self[key]
|
467 |
+
except KeyError:
|
468 |
+
return default
|
469 |
+
|
470 |
+
def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:
|
471 |
+
"""Set `default` if the key is not in the cache otherwise
|
472 |
+
leave unchanged. Return the value of this key.
|
473 |
+
"""
|
474 |
+
try:
|
475 |
+
return self[key]
|
476 |
+
except KeyError:
|
477 |
+
self[key] = default
|
478 |
+
return default
|
479 |
+
|
480 |
+
def clear(self) -> None:
|
481 |
+
"""Clear the cache."""
|
482 |
+
with self._wlock:
|
483 |
+
self._mapping.clear()
|
484 |
+
self._queue.clear()
|
485 |
+
|
486 |
+
def __contains__(self, key: t.Any) -> bool:
|
487 |
+
"""Check if a key exists in this cache."""
|
488 |
+
return key in self._mapping
|
489 |
+
|
490 |
+
def __len__(self) -> int:
|
491 |
+
"""Return the current size of the cache."""
|
492 |
+
return len(self._mapping)
|
493 |
+
|
494 |
+
def __repr__(self) -> str:
|
495 |
+
return f"<{type(self).__name__} {self._mapping!r}>"
|
496 |
+
|
497 |
+
def __getitem__(self, key: t.Any) -> t.Any:
|
498 |
+
"""Get an item from the cache. Moves the item up so that it has the
|
499 |
+
highest priority then.
|
500 |
+
|
501 |
+
Raise a `KeyError` if it does not exist.
|
502 |
+
"""
|
503 |
+
with self._wlock:
|
504 |
+
rv = self._mapping[key]
|
505 |
+
|
506 |
+
if self._queue[-1] != key:
|
507 |
+
try:
|
508 |
+
self._remove(key)
|
509 |
+
except ValueError:
|
510 |
+
# if something removed the key from the container
|
511 |
+
# when we read, ignore the ValueError that we would
|
512 |
+
# get otherwise.
|
513 |
+
pass
|
514 |
+
|
515 |
+
self._append(key)
|
516 |
+
|
517 |
+
return rv
|
518 |
+
|
519 |
+
def __setitem__(self, key: t.Any, value: t.Any) -> None:
|
520 |
+
"""Sets the value for an item. Moves the item up so that it
|
521 |
+
has the highest priority then.
|
522 |
+
"""
|
523 |
+
with self._wlock:
|
524 |
+
if key in self._mapping:
|
525 |
+
self._remove(key)
|
526 |
+
elif len(self._mapping) == self.capacity:
|
527 |
+
del self._mapping[self._popleft()]
|
528 |
+
|
529 |
+
self._append(key)
|
530 |
+
self._mapping[key] = value
|
531 |
+
|
532 |
+
def __delitem__(self, key: t.Any) -> None:
|
533 |
+
"""Remove an item from the cache dict.
|
534 |
+
Raise a `KeyError` if it does not exist.
|
535 |
+
"""
|
536 |
+
with self._wlock:
|
537 |
+
del self._mapping[key]
|
538 |
+
|
539 |
+
try:
|
540 |
+
self._remove(key)
|
541 |
+
except ValueError:
|
542 |
+
pass
|
543 |
+
|
544 |
+
def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:
|
545 |
+
"""Return a list of items."""
|
546 |
+
result = [(key, self._mapping[key]) for key in list(self._queue)]
|
547 |
+
result.reverse()
|
548 |
+
return result
|
549 |
+
|
550 |
+
def values(self) -> t.Iterable[t.Any]:
|
551 |
+
"""Return a list of all values."""
|
552 |
+
return [x[1] for x in self.items()]
|
553 |
+
|
554 |
+
def keys(self) -> t.Iterable[t.Any]:
|
555 |
+
"""Return a list of all keys ordered by most recent usage."""
|
556 |
+
return list(self)
|
557 |
+
|
558 |
+
def __iter__(self) -> t.Iterator[t.Any]:
|
559 |
+
return reversed(tuple(self._queue))
|
560 |
+
|
561 |
+
def __reversed__(self) -> t.Iterator[t.Any]:
|
562 |
+
"""Iterate over the keys in the cache dict, oldest items
|
563 |
+
coming first.
|
564 |
+
"""
|
565 |
+
return iter(tuple(self._queue))
|
566 |
+
|
567 |
+
__copy__ = copy
|
568 |
+
|
569 |
+
|
570 |
+
def select_autoescape(
|
571 |
+
enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),
|
572 |
+
disabled_extensions: t.Collection[str] = (),
|
573 |
+
default_for_string: bool = True,
|
574 |
+
default: bool = False,
|
575 |
+
) -> t.Callable[[t.Optional[str]], bool]:
|
576 |
+
"""Intelligently sets the initial value of autoescaping based on the
|
577 |
+
filename of the template. This is the recommended way to configure
|
578 |
+
autoescaping if you do not want to write a custom function yourself.
|
579 |
+
|
580 |
+
If you want to enable it for all templates created from strings or
|
581 |
+
for all templates with `.html` and `.xml` extensions::
|
582 |
+
|
583 |
+
from jinja2 import Environment, select_autoescape
|
584 |
+
env = Environment(autoescape=select_autoescape(
|
585 |
+
enabled_extensions=('html', 'xml'),
|
586 |
+
default_for_string=True,
|
587 |
+
))
|
588 |
+
|
589 |
+
Example configuration to turn it on at all times except if the template
|
590 |
+
ends with `.txt`::
|
591 |
+
|
592 |
+
from jinja2 import Environment, select_autoescape
|
593 |
+
env = Environment(autoescape=select_autoescape(
|
594 |
+
disabled_extensions=('txt',),
|
595 |
+
default_for_string=True,
|
596 |
+
default=True,
|
597 |
+
))
|
598 |
+
|
599 |
+
The `enabled_extensions` is an iterable of all the extensions that
|
600 |
+
autoescaping should be enabled for. Likewise `disabled_extensions` is
|
601 |
+
a list of all templates it should be disabled for. If a template is
|
602 |
+
loaded from a string then the default from `default_for_string` is used.
|
603 |
+
If nothing matches then the initial value of autoescaping is set to the
|
604 |
+
value of `default`.
|
605 |
+
|
606 |
+
For security reasons this function operates case insensitive.
|
607 |
+
|
608 |
+
.. versionadded:: 2.9
|
609 |
+
"""
|
610 |
+
enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)
|
611 |
+
disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)
|
612 |
+
|
613 |
+
def autoescape(template_name: t.Optional[str]) -> bool:
|
614 |
+
if template_name is None:
|
615 |
+
return default_for_string
|
616 |
+
template_name = template_name.lower()
|
617 |
+
if template_name.endswith(enabled_patterns):
|
618 |
+
return True
|
619 |
+
if template_name.endswith(disabled_patterns):
|
620 |
+
return False
|
621 |
+
return default
|
622 |
+
|
623 |
+
return autoescape
|
624 |
+
|
625 |
+
|
626 |
+
def htmlsafe_json_dumps(
|
627 |
+
obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any
|
628 |
+
) -> markupsafe.Markup:
|
629 |
+
"""Serialize an object to a string of JSON with :func:`json.dumps`,
|
630 |
+
then replace HTML-unsafe characters with Unicode escapes and mark
|
631 |
+
the result safe with :class:`~markupsafe.Markup`.
|
632 |
+
|
633 |
+
This is available in templates as the ``|tojson`` filter.
|
634 |
+
|
635 |
+
The following characters are escaped: ``<``, ``>``, ``&``, ``'``.
|
636 |
+
|
637 |
+
The returned string is safe to render in HTML documents and
|
638 |
+
``<script>`` tags. The exception is in HTML attributes that are
|
639 |
+
double quoted; either use single quotes or the ``|forceescape``
|
640 |
+
filter.
|
641 |
+
|
642 |
+
:param obj: The object to serialize to JSON.
|
643 |
+
:param dumps: The ``dumps`` function to use. Defaults to
|
644 |
+
``env.policies["json.dumps_function"]``, which defaults to
|
645 |
+
:func:`json.dumps`.
|
646 |
+
:param kwargs: Extra arguments to pass to ``dumps``. Merged onto
|
647 |
+
``env.policies["json.dumps_kwargs"]``.
|
648 |
+
|
649 |
+
.. versionchanged:: 3.0
|
650 |
+
The ``dumper`` parameter is renamed to ``dumps``.
|
651 |
+
|
652 |
+
.. versionadded:: 2.9
|
653 |
+
"""
|
654 |
+
if dumps is None:
|
655 |
+
dumps = json.dumps
|
656 |
+
|
657 |
+
return markupsafe.Markup(
|
658 |
+
dumps(obj, **kwargs)
|
659 |
+
.replace("<", "\\u003c")
|
660 |
+
.replace(">", "\\u003e")
|
661 |
+
.replace("&", "\\u0026")
|
662 |
+
.replace("'", "\\u0027")
|
663 |
+
)
|
664 |
+
|
665 |
+
|
666 |
+
class Cycler:
|
667 |
+
"""Cycle through values by yield them one at a time, then restarting
|
668 |
+
once the end is reached. Available as ``cycler`` in templates.
|
669 |
+
|
670 |
+
Similar to ``loop.cycle``, but can be used outside loops or across
|
671 |
+
multiple loops. For example, render a list of folders and files in a
|
672 |
+
list, alternating giving them "odd" and "even" classes.
|
673 |
+
|
674 |
+
.. code-block:: html+jinja
|
675 |
+
|
676 |
+
{% set row_class = cycler("odd", "even") %}
|
677 |
+
<ul class="browser">
|
678 |
+
{% for folder in folders %}
|
679 |
+
<li class="folder {{ row_class.next() }}">{{ folder }}
|
680 |
+
{% endfor %}
|
681 |
+
{% for file in files %}
|
682 |
+
<li class="file {{ row_class.next() }}">{{ file }}
|
683 |
+
{% endfor %}
|
684 |
+
</ul>
|
685 |
+
|
686 |
+
:param items: Each positional argument will be yielded in the order
|
687 |
+
given for each cycle.
|
688 |
+
|
689 |
+
.. versionadded:: 2.1
|
690 |
+
"""
|
691 |
+
|
692 |
+
def __init__(self, *items: t.Any) -> None:
|
693 |
+
if not items:
|
694 |
+
raise RuntimeError("at least one item has to be provided")
|
695 |
+
self.items = items
|
696 |
+
self.pos = 0
|
697 |
+
|
698 |
+
def reset(self) -> None:
|
699 |
+
"""Resets the current item to the first item."""
|
700 |
+
self.pos = 0
|
701 |
+
|
702 |
+
@property
|
703 |
+
def current(self) -> t.Any:
|
704 |
+
"""Return the current item. Equivalent to the item that will be
|
705 |
+
returned next time :meth:`next` is called.
|
706 |
+
"""
|
707 |
+
return self.items[self.pos]
|
708 |
+
|
709 |
+
def next(self) -> t.Any:
|
710 |
+
"""Return the current item, then advance :attr:`current` to the
|
711 |
+
next item.
|
712 |
+
"""
|
713 |
+
rv = self.current
|
714 |
+
self.pos = (self.pos + 1) % len(self.items)
|
715 |
+
return rv
|
716 |
+
|
717 |
+
__next__ = next
|
718 |
+
|
719 |
+
|
720 |
+
class Joiner:
|
721 |
+
"""A joining helper for templates."""
|
722 |
+
|
723 |
+
def __init__(self, sep: str = ", ") -> None:
|
724 |
+
self.sep = sep
|
725 |
+
self.used = False
|
726 |
+
|
727 |
+
def __call__(self) -> str:
|
728 |
+
if not self.used:
|
729 |
+
self.used = True
|
730 |
+
return ""
|
731 |
+
return self.sep
|
732 |
+
|
733 |
+
|
734 |
+
class Namespace:
|
735 |
+
"""A namespace object that can hold arbitrary attributes. It may be
|
736 |
+
initialized from a dictionary or with keyword arguments."""
|
737 |
+
|
738 |
+
def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902
|
739 |
+
self, args = args[0], args[1:]
|
740 |
+
self.__attrs = dict(*args, **kwargs)
|
741 |
+
|
742 |
+
def __getattribute__(self, name: str) -> t.Any:
|
743 |
+
# __class__ is needed for the awaitable check in async mode
|
744 |
+
if name in {"_Namespace__attrs", "__class__"}:
|
745 |
+
return object.__getattribute__(self, name)
|
746 |
+
try:
|
747 |
+
return self.__attrs[name]
|
748 |
+
except KeyError:
|
749 |
+
raise AttributeError(name) from None
|
750 |
+
|
751 |
+
def __setitem__(self, name: str, value: t.Any) -> None:
|
752 |
+
self.__attrs[name] = value
|
753 |
+
|
754 |
+
def __repr__(self) -> str:
|
755 |
+
return f"<Namespace {self.__attrs!r}>"
|
llmeval-env/lib/python3.10/site-packages/jinja2/visitor.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""API for traversing the AST nodes. Implemented by the compiler and
|
2 |
+
meta introspection.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import typing as t
|
6 |
+
|
7 |
+
from .nodes import Node
|
8 |
+
|
9 |
+
if t.TYPE_CHECKING:
|
10 |
+
import typing_extensions as te
|
11 |
+
|
12 |
+
class VisitCallable(te.Protocol):
|
13 |
+
def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any: ...
|
14 |
+
|
15 |
+
|
16 |
+
class NodeVisitor:
|
17 |
+
"""Walks the abstract syntax tree and call visitor functions for every
|
18 |
+
node found. The visitor functions may return values which will be
|
19 |
+
forwarded by the `visit` method.
|
20 |
+
|
21 |
+
Per default the visitor functions for the nodes are ``'visit_'`` +
|
22 |
+
class name of the node. So a `TryFinally` node visit function would
|
23 |
+
be `visit_TryFinally`. This behavior can be changed by overriding
|
24 |
+
the `get_visitor` function. If no visitor function exists for a node
|
25 |
+
(return value `None`) the `generic_visit` visitor is used instead.
|
26 |
+
"""
|
27 |
+
|
28 |
+
def get_visitor(self, node: Node) -> "t.Optional[VisitCallable]":
|
29 |
+
"""Return the visitor function for this node or `None` if no visitor
|
30 |
+
exists for this node. In that case the generic visit function is
|
31 |
+
used instead.
|
32 |
+
"""
|
33 |
+
return getattr(self, f"visit_{type(node).__name__}", None)
|
34 |
+
|
35 |
+
def visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:
|
36 |
+
"""Visit a node."""
|
37 |
+
f = self.get_visitor(node)
|
38 |
+
|
39 |
+
if f is not None:
|
40 |
+
return f(node, *args, **kwargs)
|
41 |
+
|
42 |
+
return self.generic_visit(node, *args, **kwargs)
|
43 |
+
|
44 |
+
def generic_visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:
|
45 |
+
"""Called if no explicit visitor function exists for a node."""
|
46 |
+
for child_node in node.iter_child_nodes():
|
47 |
+
self.visit(child_node, *args, **kwargs)
|
48 |
+
|
49 |
+
|
50 |
+
class NodeTransformer(NodeVisitor):
|
51 |
+
"""Walks the abstract syntax tree and allows modifications of nodes.
|
52 |
+
|
53 |
+
The `NodeTransformer` will walk the AST and use the return value of the
|
54 |
+
visitor functions to replace or remove the old node. If the return
|
55 |
+
value of the visitor function is `None` the node will be removed
|
56 |
+
from the previous location otherwise it's replaced with the return
|
57 |
+
value. The return value may be the original node in which case no
|
58 |
+
replacement takes place.
|
59 |
+
"""
|
60 |
+
|
61 |
+
def generic_visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> Node:
|
62 |
+
for field, old_value in node.iter_fields():
|
63 |
+
if isinstance(old_value, list):
|
64 |
+
new_values = []
|
65 |
+
for value in old_value:
|
66 |
+
if isinstance(value, Node):
|
67 |
+
value = self.visit(value, *args, **kwargs)
|
68 |
+
if value is None:
|
69 |
+
continue
|
70 |
+
elif not isinstance(value, Node):
|
71 |
+
new_values.extend(value)
|
72 |
+
continue
|
73 |
+
new_values.append(value)
|
74 |
+
old_value[:] = new_values
|
75 |
+
elif isinstance(old_value, Node):
|
76 |
+
new_node = self.visit(old_value, *args, **kwargs)
|
77 |
+
if new_node is None:
|
78 |
+
delattr(node, field)
|
79 |
+
else:
|
80 |
+
setattr(node, field, new_node)
|
81 |
+
return node
|
82 |
+
|
83 |
+
def visit_list(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.List[Node]:
|
84 |
+
"""As transformers may return lists in some places this method
|
85 |
+
can be used to enforce a list as return value.
|
86 |
+
"""
|
87 |
+
rv = self.visit(node, *args, **kwargs)
|
88 |
+
|
89 |
+
if not isinstance(rv, list):
|
90 |
+
return [rv]
|
91 |
+
|
92 |
+
return rv
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/__init__.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .graph import Graph
|
2 |
+
from .digraph import DiGraph
|
3 |
+
from .multigraph import MultiGraph
|
4 |
+
from .multidigraph import MultiDiGraph
|
5 |
+
|
6 |
+
from .function import *
|
7 |
+
from .graphviews import subgraph_view, reverse_view
|
8 |
+
|
9 |
+
from networkx.classes import filters
|
10 |
+
|
11 |
+
from networkx.classes import coreviews
|
12 |
+
from networkx.classes import graphviews
|
13 |
+
from networkx.classes import reportviews
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/coreviews.py
ADDED
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Views of core data structures such as nested Mappings (e.g. dict-of-dicts).
|
2 |
+
These ``Views`` often restrict element access, with either the entire view or
|
3 |
+
layers of nested mappings being read-only.
|
4 |
+
"""
|
5 |
+
from collections.abc import Mapping
|
6 |
+
|
7 |
+
__all__ = [
|
8 |
+
"AtlasView",
|
9 |
+
"AdjacencyView",
|
10 |
+
"MultiAdjacencyView",
|
11 |
+
"UnionAtlas",
|
12 |
+
"UnionAdjacency",
|
13 |
+
"UnionMultiInner",
|
14 |
+
"UnionMultiAdjacency",
|
15 |
+
"FilterAtlas",
|
16 |
+
"FilterAdjacency",
|
17 |
+
"FilterMultiInner",
|
18 |
+
"FilterMultiAdjacency",
|
19 |
+
]
|
20 |
+
|
21 |
+
|
22 |
+
class AtlasView(Mapping):
|
23 |
+
"""An AtlasView is a Read-only Mapping of Mappings.
|
24 |
+
|
25 |
+
It is a View into a dict-of-dict data structure.
|
26 |
+
The inner level of dict is read-write. But the
|
27 |
+
outer level is read-only.
|
28 |
+
|
29 |
+
See Also
|
30 |
+
========
|
31 |
+
AdjacencyView: View into dict-of-dict-of-dict
|
32 |
+
MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
|
33 |
+
"""
|
34 |
+
|
35 |
+
__slots__ = ("_atlas",)
|
36 |
+
|
37 |
+
def __getstate__(self):
|
38 |
+
return {"_atlas": self._atlas}
|
39 |
+
|
40 |
+
def __setstate__(self, state):
|
41 |
+
self._atlas = state["_atlas"]
|
42 |
+
|
43 |
+
def __init__(self, d):
|
44 |
+
self._atlas = d
|
45 |
+
|
46 |
+
def __len__(self):
|
47 |
+
return len(self._atlas)
|
48 |
+
|
49 |
+
def __iter__(self):
|
50 |
+
return iter(self._atlas)
|
51 |
+
|
52 |
+
def __getitem__(self, key):
|
53 |
+
return self._atlas[key]
|
54 |
+
|
55 |
+
def copy(self):
|
56 |
+
return {n: self[n].copy() for n in self._atlas}
|
57 |
+
|
58 |
+
def __str__(self):
|
59 |
+
return str(self._atlas) # {nbr: self[nbr] for nbr in self})
|
60 |
+
|
61 |
+
def __repr__(self):
|
62 |
+
return f"{self.__class__.__name__}({self._atlas!r})"
|
63 |
+
|
64 |
+
|
65 |
+
class AdjacencyView(AtlasView):
|
66 |
+
"""An AdjacencyView is a Read-only Map of Maps of Maps.
|
67 |
+
|
68 |
+
It is a View into a dict-of-dict-of-dict data structure.
|
69 |
+
The inner level of dict is read-write. But the
|
70 |
+
outer levels are read-only.
|
71 |
+
|
72 |
+
See Also
|
73 |
+
========
|
74 |
+
AtlasView: View into dict-of-dict
|
75 |
+
MultiAdjacencyView: View into dict-of-dict-of-dict-of-dict
|
76 |
+
"""
|
77 |
+
|
78 |
+
__slots__ = () # Still uses AtlasView slots names _atlas
|
79 |
+
|
80 |
+
def __getitem__(self, name):
|
81 |
+
return AtlasView(self._atlas[name])
|
82 |
+
|
83 |
+
def copy(self):
|
84 |
+
return {n: self[n].copy() for n in self._atlas}
|
85 |
+
|
86 |
+
|
87 |
+
class MultiAdjacencyView(AdjacencyView):
|
88 |
+
"""An MultiAdjacencyView is a Read-only Map of Maps of Maps of Maps.
|
89 |
+
|
90 |
+
It is a View into a dict-of-dict-of-dict-of-dict data structure.
|
91 |
+
The inner level of dict is read-write. But the
|
92 |
+
outer levels are read-only.
|
93 |
+
|
94 |
+
See Also
|
95 |
+
========
|
96 |
+
AtlasView: View into dict-of-dict
|
97 |
+
AdjacencyView: View into dict-of-dict-of-dict
|
98 |
+
"""
|
99 |
+
|
100 |
+
__slots__ = () # Still uses AtlasView slots names _atlas
|
101 |
+
|
102 |
+
def __getitem__(self, name):
|
103 |
+
return AdjacencyView(self._atlas[name])
|
104 |
+
|
105 |
+
def copy(self):
|
106 |
+
return {n: self[n].copy() for n in self._atlas}
|
107 |
+
|
108 |
+
|
109 |
+
class UnionAtlas(Mapping):
|
110 |
+
"""A read-only union of two atlases (dict-of-dict).
|
111 |
+
|
112 |
+
The two dict-of-dicts represent the inner dict of
|
113 |
+
an Adjacency: `G.succ[node]` and `G.pred[node]`.
|
114 |
+
The inner level of dict of both hold attribute key:value
|
115 |
+
pairs and is read-write. But the outer level is read-only.
|
116 |
+
|
117 |
+
See Also
|
118 |
+
========
|
119 |
+
UnionAdjacency: View into dict-of-dict-of-dict
|
120 |
+
UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
|
121 |
+
"""
|
122 |
+
|
123 |
+
__slots__ = ("_succ", "_pred")
|
124 |
+
|
125 |
+
def __getstate__(self):
|
126 |
+
return {"_succ": self._succ, "_pred": self._pred}
|
127 |
+
|
128 |
+
def __setstate__(self, state):
|
129 |
+
self._succ = state["_succ"]
|
130 |
+
self._pred = state["_pred"]
|
131 |
+
|
132 |
+
def __init__(self, succ, pred):
|
133 |
+
self._succ = succ
|
134 |
+
self._pred = pred
|
135 |
+
|
136 |
+
def __len__(self):
|
137 |
+
return len(self._succ.keys() | self._pred.keys())
|
138 |
+
|
139 |
+
def __iter__(self):
|
140 |
+
return iter(set(self._succ.keys()) | set(self._pred.keys()))
|
141 |
+
|
142 |
+
def __getitem__(self, key):
|
143 |
+
try:
|
144 |
+
return self._succ[key]
|
145 |
+
except KeyError:
|
146 |
+
return self._pred[key]
|
147 |
+
|
148 |
+
def copy(self):
|
149 |
+
result = {nbr: dd.copy() for nbr, dd in self._succ.items()}
|
150 |
+
for nbr, dd in self._pred.items():
|
151 |
+
if nbr in result:
|
152 |
+
result[nbr].update(dd)
|
153 |
+
else:
|
154 |
+
result[nbr] = dd.copy()
|
155 |
+
return result
|
156 |
+
|
157 |
+
def __str__(self):
|
158 |
+
return str({nbr: self[nbr] for nbr in self})
|
159 |
+
|
160 |
+
def __repr__(self):
|
161 |
+
return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
|
162 |
+
|
163 |
+
|
164 |
+
class UnionAdjacency(Mapping):
|
165 |
+
"""A read-only union of dict Adjacencies as a Map of Maps of Maps.
|
166 |
+
|
167 |
+
The two input dict-of-dict-of-dicts represent the union of
|
168 |
+
`G.succ` and `G.pred`. Return values are UnionAtlas
|
169 |
+
The inner level of dict is read-write. But the
|
170 |
+
middle and outer levels are read-only.
|
171 |
+
|
172 |
+
succ : a dict-of-dict-of-dict {node: nbrdict}
|
173 |
+
pred : a dict-of-dict-of-dict {node: nbrdict}
|
174 |
+
The keys for the two dicts should be the same
|
175 |
+
|
176 |
+
See Also
|
177 |
+
========
|
178 |
+
UnionAtlas: View into dict-of-dict
|
179 |
+
UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
|
180 |
+
"""
|
181 |
+
|
182 |
+
__slots__ = ("_succ", "_pred")
|
183 |
+
|
184 |
+
def __getstate__(self):
|
185 |
+
return {"_succ": self._succ, "_pred": self._pred}
|
186 |
+
|
187 |
+
def __setstate__(self, state):
|
188 |
+
self._succ = state["_succ"]
|
189 |
+
self._pred = state["_pred"]
|
190 |
+
|
191 |
+
def __init__(self, succ, pred):
|
192 |
+
# keys must be the same for two input dicts
|
193 |
+
assert len(set(succ.keys()) ^ set(pred.keys())) == 0
|
194 |
+
self._succ = succ
|
195 |
+
self._pred = pred
|
196 |
+
|
197 |
+
def __len__(self):
|
198 |
+
return len(self._succ) # length of each dict should be the same
|
199 |
+
|
200 |
+
def __iter__(self):
|
201 |
+
return iter(self._succ)
|
202 |
+
|
203 |
+
def __getitem__(self, nbr):
|
204 |
+
return UnionAtlas(self._succ[nbr], self._pred[nbr])
|
205 |
+
|
206 |
+
def copy(self):
|
207 |
+
return {n: self[n].copy() for n in self._succ}
|
208 |
+
|
209 |
+
def __str__(self):
|
210 |
+
return str({nbr: self[nbr] for nbr in self})
|
211 |
+
|
212 |
+
def __repr__(self):
|
213 |
+
return f"{self.__class__.__name__}({self._succ!r}, {self._pred!r})"
|
214 |
+
|
215 |
+
|
216 |
+
class UnionMultiInner(UnionAtlas):
|
217 |
+
"""A read-only union of two inner dicts of MultiAdjacencies.
|
218 |
+
|
219 |
+
The two input dict-of-dict-of-dicts represent the union of
|
220 |
+
`G.succ[node]` and `G.pred[node]` for MultiDiGraphs.
|
221 |
+
Return values are UnionAtlas.
|
222 |
+
The inner level of dict is read-write. But the outer levels are read-only.
|
223 |
+
|
224 |
+
See Also
|
225 |
+
========
|
226 |
+
UnionAtlas: View into dict-of-dict
|
227 |
+
UnionAdjacency: View into dict-of-dict-of-dict
|
228 |
+
UnionMultiAdjacency: View into dict-of-dict-of-dict-of-dict
|
229 |
+
"""
|
230 |
+
|
231 |
+
__slots__ = () # Still uses UnionAtlas slots names _succ, _pred
|
232 |
+
|
233 |
+
def __getitem__(self, node):
|
234 |
+
in_succ = node in self._succ
|
235 |
+
in_pred = node in self._pred
|
236 |
+
if in_succ:
|
237 |
+
if in_pred:
|
238 |
+
return UnionAtlas(self._succ[node], self._pred[node])
|
239 |
+
return UnionAtlas(self._succ[node], {})
|
240 |
+
return UnionAtlas({}, self._pred[node])
|
241 |
+
|
242 |
+
def copy(self):
|
243 |
+
nodes = set(self._succ.keys()) | set(self._pred.keys())
|
244 |
+
return {n: self[n].copy() for n in nodes}
|
245 |
+
|
246 |
+
|
247 |
+
class UnionMultiAdjacency(UnionAdjacency):
|
248 |
+
"""A read-only union of two dict MultiAdjacencies.
|
249 |
+
|
250 |
+
The two input dict-of-dict-of-dict-of-dicts represent the union of
|
251 |
+
`G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency.
|
252 |
+
The inner level of dict is read-write. But the outer levels are read-only.
|
253 |
+
|
254 |
+
See Also
|
255 |
+
========
|
256 |
+
UnionAtlas: View into dict-of-dict
|
257 |
+
UnionMultiInner: View into dict-of-dict-of-dict
|
258 |
+
"""
|
259 |
+
|
260 |
+
__slots__ = () # Still uses UnionAdjacency slots names _succ, _pred
|
261 |
+
|
262 |
+
def __getitem__(self, node):
|
263 |
+
return UnionMultiInner(self._succ[node], self._pred[node])
|
264 |
+
|
265 |
+
|
266 |
+
class FilterAtlas(Mapping): # nodedict, nbrdict, keydict
|
267 |
+
"""A read-only Mapping of Mappings with filtering criteria for nodes.
|
268 |
+
|
269 |
+
It is a view into a dict-of-dict data structure, and it selects only
|
270 |
+
nodes that meet the criteria defined by ``NODE_OK``.
|
271 |
+
|
272 |
+
See Also
|
273 |
+
========
|
274 |
+
FilterAdjacency
|
275 |
+
FilterMultiInner
|
276 |
+
FilterMultiAdjacency
|
277 |
+
"""
|
278 |
+
|
279 |
+
def __init__(self, d, NODE_OK):
|
280 |
+
self._atlas = d
|
281 |
+
self.NODE_OK = NODE_OK
|
282 |
+
|
283 |
+
def __len__(self):
|
284 |
+
return sum(1 for n in self)
|
285 |
+
|
286 |
+
def __iter__(self):
|
287 |
+
try: # check that NODE_OK has attr 'nodes'
|
288 |
+
node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
|
289 |
+
except AttributeError:
|
290 |
+
node_ok_shorter = False
|
291 |
+
if node_ok_shorter:
|
292 |
+
return (n for n in self.NODE_OK.nodes if n in self._atlas)
|
293 |
+
return (n for n in self._atlas if self.NODE_OK(n))
|
294 |
+
|
295 |
+
def __getitem__(self, key):
|
296 |
+
if key in self._atlas and self.NODE_OK(key):
|
297 |
+
return self._atlas[key]
|
298 |
+
raise KeyError(f"Key {key} not found")
|
299 |
+
|
300 |
+
def __str__(self):
|
301 |
+
return str({nbr: self[nbr] for nbr in self})
|
302 |
+
|
303 |
+
def __repr__(self):
|
304 |
+
return f"{self.__class__.__name__}({self._atlas!r}, {self.NODE_OK!r})"
|
305 |
+
|
306 |
+
|
307 |
+
class FilterAdjacency(Mapping): # edgedict
|
308 |
+
"""A read-only Mapping of Mappings with filtering criteria for nodes and edges.
|
309 |
+
|
310 |
+
It is a view into a dict-of-dict-of-dict data structure, and it selects nodes
|
311 |
+
and edges that satisfy specific criteria defined by ``NODE_OK`` and ``EDGE_OK``,
|
312 |
+
respectively.
|
313 |
+
|
314 |
+
See Also
|
315 |
+
========
|
316 |
+
FilterAtlas
|
317 |
+
FilterMultiInner
|
318 |
+
FilterMultiAdjacency
|
319 |
+
"""
|
320 |
+
|
321 |
+
def __init__(self, d, NODE_OK, EDGE_OK):
|
322 |
+
self._atlas = d
|
323 |
+
self.NODE_OK = NODE_OK
|
324 |
+
self.EDGE_OK = EDGE_OK
|
325 |
+
|
326 |
+
def __len__(self):
|
327 |
+
return sum(1 for n in self)
|
328 |
+
|
329 |
+
def __iter__(self):
|
330 |
+
try: # check that NODE_OK has attr 'nodes'
|
331 |
+
node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
|
332 |
+
except AttributeError:
|
333 |
+
node_ok_shorter = False
|
334 |
+
if node_ok_shorter:
|
335 |
+
return (n for n in self.NODE_OK.nodes if n in self._atlas)
|
336 |
+
return (n for n in self._atlas if self.NODE_OK(n))
|
337 |
+
|
338 |
+
def __getitem__(self, node):
|
339 |
+
if node in self._atlas and self.NODE_OK(node):
|
340 |
+
|
341 |
+
def new_node_ok(nbr):
|
342 |
+
return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr)
|
343 |
+
|
344 |
+
return FilterAtlas(self._atlas[node], new_node_ok)
|
345 |
+
raise KeyError(f"Key {node} not found")
|
346 |
+
|
347 |
+
def __str__(self):
|
348 |
+
return str({nbr: self[nbr] for nbr in self})
|
349 |
+
|
350 |
+
def __repr__(self):
|
351 |
+
name = self.__class__.__name__
|
352 |
+
return f"{name}({self._atlas!r}, {self.NODE_OK!r}, {self.EDGE_OK!r})"
|
353 |
+
|
354 |
+
|
355 |
+
class FilterMultiInner(FilterAdjacency): # muliedge_seconddict
|
356 |
+
"""A read-only Mapping of Mappings with filtering criteria for nodes and edges.
|
357 |
+
|
358 |
+
It is a view into a dict-of-dict-of-dict-of-dict data structure, and it selects nodes
|
359 |
+
and edges that meet specific criteria defined by ``NODE_OK`` and ``EDGE_OK``.
|
360 |
+
|
361 |
+
See Also
|
362 |
+
========
|
363 |
+
FilterAtlas
|
364 |
+
FilterAdjacency
|
365 |
+
FilterMultiAdjacency
|
366 |
+
"""
|
367 |
+
|
368 |
+
def __iter__(self):
|
369 |
+
try: # check that NODE_OK has attr 'nodes'
|
370 |
+
node_ok_shorter = 2 * len(self.NODE_OK.nodes) < len(self._atlas)
|
371 |
+
except AttributeError:
|
372 |
+
node_ok_shorter = False
|
373 |
+
if node_ok_shorter:
|
374 |
+
my_nodes = (n for n in self.NODE_OK.nodes if n in self._atlas)
|
375 |
+
else:
|
376 |
+
my_nodes = (n for n in self._atlas if self.NODE_OK(n))
|
377 |
+
for n in my_nodes:
|
378 |
+
some_keys_ok = False
|
379 |
+
for key in self._atlas[n]:
|
380 |
+
if self.EDGE_OK(n, key):
|
381 |
+
some_keys_ok = True
|
382 |
+
break
|
383 |
+
if some_keys_ok is True:
|
384 |
+
yield n
|
385 |
+
|
386 |
+
def __getitem__(self, nbr):
|
387 |
+
if nbr in self._atlas and self.NODE_OK(nbr):
|
388 |
+
|
389 |
+
def new_node_ok(key):
|
390 |
+
return self.EDGE_OK(nbr, key)
|
391 |
+
|
392 |
+
return FilterAtlas(self._atlas[nbr], new_node_ok)
|
393 |
+
raise KeyError(f"Key {nbr} not found")
|
394 |
+
|
395 |
+
|
396 |
+
class FilterMultiAdjacency(FilterAdjacency): # multiedgedict
|
397 |
+
"""A read-only Mapping of Mappings with filtering criteria
|
398 |
+
for nodes and edges.
|
399 |
+
|
400 |
+
It is a view into a dict-of-dict-of-dict-of-dict data structure,
|
401 |
+
and it selects nodes and edges that satisfy specific criteria
|
402 |
+
defined by ``NODE_OK`` and ``EDGE_OK``, respectively.
|
403 |
+
|
404 |
+
See Also
|
405 |
+
========
|
406 |
+
FilterAtlas
|
407 |
+
FilterAdjacency
|
408 |
+
FilterMultiInner
|
409 |
+
"""
|
410 |
+
|
411 |
+
def __getitem__(self, node):
|
412 |
+
if node in self._atlas and self.NODE_OK(node):
|
413 |
+
|
414 |
+
def edge_ok(nbr, key):
|
415 |
+
return self.NODE_OK(nbr) and self.EDGE_OK(node, nbr, key)
|
416 |
+
|
417 |
+
return FilterMultiInner(self._atlas[node], self.NODE_OK, edge_ok)
|
418 |
+
raise KeyError(f"Key {node} not found")
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/digraph.py
ADDED
@@ -0,0 +1,1334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for directed graphs."""
|
2 |
+
from copy import deepcopy
|
3 |
+
from functools import cached_property
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx import convert
|
7 |
+
from networkx.classes.coreviews import AdjacencyView
|
8 |
+
from networkx.classes.graph import Graph
|
9 |
+
from networkx.classes.reportviews import (
|
10 |
+
DiDegreeView,
|
11 |
+
InDegreeView,
|
12 |
+
InEdgeView,
|
13 |
+
OutDegreeView,
|
14 |
+
OutEdgeView,
|
15 |
+
)
|
16 |
+
from networkx.exception import NetworkXError
|
17 |
+
|
18 |
+
__all__ = ["DiGraph"]
|
19 |
+
|
20 |
+
|
21 |
+
class _CachedPropertyResetterAdjAndSucc:
|
22 |
+
"""Data Descriptor class that syncs and resets cached properties adj and succ
|
23 |
+
|
24 |
+
The cached properties `adj` and `succ` are reset whenever `_adj` or `_succ`
|
25 |
+
are set to new objects. In addition, the attributes `_succ` and `_adj`
|
26 |
+
are synced so these two names point to the same object.
|
27 |
+
|
28 |
+
This object sits on a class and ensures that any instance of that
|
29 |
+
class clears its cached properties "succ" and "adj" whenever the
|
30 |
+
underlying instance attributes "_succ" or "_adj" are set to a new object.
|
31 |
+
It only affects the set process of the obj._adj and obj._succ attribute.
|
32 |
+
All get/del operations act as they normally would.
|
33 |
+
|
34 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __set__(self, obj, value):
|
38 |
+
od = obj.__dict__
|
39 |
+
od["_adj"] = value
|
40 |
+
od["_succ"] = value
|
41 |
+
# reset cached properties
|
42 |
+
if "adj" in od:
|
43 |
+
del od["adj"]
|
44 |
+
if "succ" in od:
|
45 |
+
del od["succ"]
|
46 |
+
|
47 |
+
|
48 |
+
class _CachedPropertyResetterPred:
|
49 |
+
"""Data Descriptor class for _pred that resets ``pred`` cached_property when needed
|
50 |
+
|
51 |
+
This assumes that the ``cached_property`` ``G.pred`` should be reset whenever
|
52 |
+
``G._pred`` is set to a new value.
|
53 |
+
|
54 |
+
This object sits on a class and ensures that any instance of that
|
55 |
+
class clears its cached property "pred" whenever the underlying
|
56 |
+
instance attribute "_pred" is set to a new object. It only affects
|
57 |
+
the set process of the obj._pred attribute. All get/del operations
|
58 |
+
act as they normally would.
|
59 |
+
|
60 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
61 |
+
"""
|
62 |
+
|
63 |
+
def __set__(self, obj, value):
|
64 |
+
od = obj.__dict__
|
65 |
+
od["_pred"] = value
|
66 |
+
if "pred" in od:
|
67 |
+
del od["pred"]
|
68 |
+
|
69 |
+
|
70 |
+
class DiGraph(Graph):
|
71 |
+
"""
|
72 |
+
Base class for directed graphs.
|
73 |
+
|
74 |
+
A DiGraph stores nodes and edges with optional data, or attributes.
|
75 |
+
|
76 |
+
DiGraphs hold directed edges. Self loops are allowed but multiple
|
77 |
+
(parallel) edges are not.
|
78 |
+
|
79 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
80 |
+
key/value attributes. By convention `None` is not used as a node.
|
81 |
+
|
82 |
+
Edges are represented as links between nodes with optional
|
83 |
+
key/value attributes.
|
84 |
+
|
85 |
+
Parameters
|
86 |
+
----------
|
87 |
+
incoming_graph_data : input graph (optional, default: None)
|
88 |
+
Data to initialize graph. If None (default) an empty
|
89 |
+
graph is created. The data can be any format that is supported
|
90 |
+
by the to_networkx_graph() function, currently including edge list,
|
91 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
|
92 |
+
sparse matrix, or PyGraphviz graph.
|
93 |
+
|
94 |
+
attr : keyword arguments, optional (default= no attributes)
|
95 |
+
Attributes to add to graph as key=value pairs.
|
96 |
+
|
97 |
+
See Also
|
98 |
+
--------
|
99 |
+
Graph
|
100 |
+
MultiGraph
|
101 |
+
MultiDiGraph
|
102 |
+
|
103 |
+
Examples
|
104 |
+
--------
|
105 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
106 |
+
no edges.
|
107 |
+
|
108 |
+
>>> G = nx.DiGraph()
|
109 |
+
|
110 |
+
G can be grown in several ways.
|
111 |
+
|
112 |
+
**Nodes:**
|
113 |
+
|
114 |
+
Add one node at a time:
|
115 |
+
|
116 |
+
>>> G.add_node(1)
|
117 |
+
|
118 |
+
Add the nodes from any container (a list, dict, set or
|
119 |
+
even the lines from a file or the nodes from another graph).
|
120 |
+
|
121 |
+
>>> G.add_nodes_from([2, 3])
|
122 |
+
>>> G.add_nodes_from(range(100, 110))
|
123 |
+
>>> H = nx.path_graph(10)
|
124 |
+
>>> G.add_nodes_from(H)
|
125 |
+
|
126 |
+
In addition to strings and integers any hashable Python object
|
127 |
+
(except None) can represent a node, e.g. a customized node object,
|
128 |
+
or even another Graph.
|
129 |
+
|
130 |
+
>>> G.add_node(H)
|
131 |
+
|
132 |
+
**Edges:**
|
133 |
+
|
134 |
+
G can also be grown by adding edges.
|
135 |
+
|
136 |
+
Add one edge,
|
137 |
+
|
138 |
+
>>> G.add_edge(1, 2)
|
139 |
+
|
140 |
+
a list of edges,
|
141 |
+
|
142 |
+
>>> G.add_edges_from([(1, 2), (1, 3)])
|
143 |
+
|
144 |
+
or a collection of edges,
|
145 |
+
|
146 |
+
>>> G.add_edges_from(H.edges)
|
147 |
+
|
148 |
+
If some edges connect nodes not yet in the graph, the nodes
|
149 |
+
are added automatically. There are no errors when adding
|
150 |
+
nodes or edges that already exist.
|
151 |
+
|
152 |
+
**Attributes:**
|
153 |
+
|
154 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
155 |
+
in an associated attribute dictionary (the keys must be hashable).
|
156 |
+
By default these are empty, but can be added or changed using
|
157 |
+
add_edge, add_node or direct manipulation of the attribute
|
158 |
+
dictionaries named graph, node and edge respectively.
|
159 |
+
|
160 |
+
>>> G = nx.DiGraph(day="Friday")
|
161 |
+
>>> G.graph
|
162 |
+
{'day': 'Friday'}
|
163 |
+
|
164 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
165 |
+
|
166 |
+
>>> G.add_node(1, time="5pm")
|
167 |
+
>>> G.add_nodes_from([3], time="2pm")
|
168 |
+
>>> G.nodes[1]
|
169 |
+
{'time': '5pm'}
|
170 |
+
>>> G.nodes[1]["room"] = 714
|
171 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
172 |
+
>>> list(G.nodes(data=True))
|
173 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
174 |
+
|
175 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
176 |
+
notation, or G.edges.
|
177 |
+
|
178 |
+
>>> G.add_edge(1, 2, weight=4.7)
|
179 |
+
>>> G.add_edges_from([(3, 4), (4, 5)], color="red")
|
180 |
+
>>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
181 |
+
>>> G[1][2]["weight"] = 4.7
|
182 |
+
>>> G.edges[1, 2]["weight"] = 4
|
183 |
+
|
184 |
+
Warning: we protect the graph data structure by making `G.edges[1, 2]` a
|
185 |
+
read-only dict-like structure. However, you can assign to attributes
|
186 |
+
in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
|
187 |
+
data attributes: `G.edges[1, 2]['weight'] = 4`
|
188 |
+
(For multigraphs: `MG.edges[u, v, key][name] = value`).
|
189 |
+
|
190 |
+
**Shortcuts:**
|
191 |
+
|
192 |
+
Many common graph features allow python syntax to speed reporting.
|
193 |
+
|
194 |
+
>>> 1 in G # check if node in graph
|
195 |
+
True
|
196 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
197 |
+
[1, 2]
|
198 |
+
>>> len(G) # number of nodes in graph
|
199 |
+
5
|
200 |
+
|
201 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
202 |
+
The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
|
203 |
+
|
204 |
+
>>> for n, nbrsdict in G.adjacency():
|
205 |
+
... for nbr, eattr in nbrsdict.items():
|
206 |
+
... if "weight" in eattr:
|
207 |
+
... # Do something useful with the edges
|
208 |
+
... pass
|
209 |
+
|
210 |
+
But the edges reporting object is often more convenient:
|
211 |
+
|
212 |
+
>>> for u, v, weight in G.edges(data="weight"):
|
213 |
+
... if weight is not None:
|
214 |
+
... # Do something useful with the edges
|
215 |
+
... pass
|
216 |
+
|
217 |
+
**Reporting:**
|
218 |
+
|
219 |
+
Simple graph information is obtained using object-attributes and methods.
|
220 |
+
Reporting usually provides views instead of containers to reduce memory
|
221 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
222 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
223 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
|
224 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
225 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
226 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
227 |
+
|
228 |
+
For details on these and other miscellaneous methods, see below.
|
229 |
+
|
230 |
+
**Subclasses (Advanced):**
|
231 |
+
|
232 |
+
The Graph class uses a dict-of-dict-of-dict data structure.
|
233 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
234 |
+
The next dict (adjlist_dict) represents the adjacency information and holds
|
235 |
+
edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
|
236 |
+
the edge data and holds edge attribute values keyed by attribute names.
|
237 |
+
|
238 |
+
Each of these three dicts can be replaced in a subclass by a user defined
|
239 |
+
dict-like object. In general, the dict-like features should be
|
240 |
+
maintained but extra features can be added. To replace one of the
|
241 |
+
dicts create a new graph class by changing the class(!) variable
|
242 |
+
holding the factory for that dict-like structure. The variable names are
|
243 |
+
node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
|
244 |
+
adjlist_outer_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
|
245 |
+
|
246 |
+
node_dict_factory : function, (default: dict)
|
247 |
+
Factory function to be used to create the dict containing node
|
248 |
+
attributes, keyed by node id.
|
249 |
+
It should require no arguments and return a dict-like object
|
250 |
+
|
251 |
+
node_attr_dict_factory: function, (default: dict)
|
252 |
+
Factory function to be used to create the node attribute
|
253 |
+
dict which holds attribute values keyed by attribute name.
|
254 |
+
It should require no arguments and return a dict-like object
|
255 |
+
|
256 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
257 |
+
Factory function to be used to create the outer-most dict
|
258 |
+
in the data structure that holds adjacency info keyed by node.
|
259 |
+
It should require no arguments and return a dict-like object.
|
260 |
+
|
261 |
+
adjlist_inner_dict_factory : function, optional (default: dict)
|
262 |
+
Factory function to be used to create the adjacency list
|
263 |
+
dict which holds edge data keyed by neighbor.
|
264 |
+
It should require no arguments and return a dict-like object
|
265 |
+
|
266 |
+
edge_attr_dict_factory : function, optional (default: dict)
|
267 |
+
Factory function to be used to create the edge attribute
|
268 |
+
dict which holds attribute values keyed by attribute name.
|
269 |
+
It should require no arguments and return a dict-like object.
|
270 |
+
|
271 |
+
graph_attr_dict_factory : function, (default: dict)
|
272 |
+
Factory function to be used to create the graph attribute
|
273 |
+
dict which holds attribute values keyed by attribute name.
|
274 |
+
It should require no arguments and return a dict-like object.
|
275 |
+
|
276 |
+
Typically, if your extension doesn't impact the data structure all
|
277 |
+
methods will inherited without issue except: `to_directed/to_undirected`.
|
278 |
+
By default these methods create a DiGraph/Graph class and you probably
|
279 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
280 |
+
this we define two class variables that you can set in your subclass.
|
281 |
+
|
282 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
283 |
+
Class to create a new graph structure in the `to_directed` method.
|
284 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
285 |
+
|
286 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
287 |
+
Class to create a new graph structure in the `to_undirected` method.
|
288 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
289 |
+
|
290 |
+
**Subclassing Example**
|
291 |
+
|
292 |
+
Create a low memory graph class that effectively disallows edge
|
293 |
+
attributes by using a single attribute dict for all edges.
|
294 |
+
This reduces the memory used, but you lose edge attributes.
|
295 |
+
|
296 |
+
>>> class ThinGraph(nx.Graph):
|
297 |
+
... all_edge_dict = {"weight": 1}
|
298 |
+
...
|
299 |
+
... def single_edge_dict(self):
|
300 |
+
... return self.all_edge_dict
|
301 |
+
...
|
302 |
+
... edge_attr_dict_factory = single_edge_dict
|
303 |
+
>>> G = ThinGraph()
|
304 |
+
>>> G.add_edge(2, 1)
|
305 |
+
>>> G[2][1]
|
306 |
+
{'weight': 1}
|
307 |
+
>>> G.add_edge(2, 2)
|
308 |
+
>>> G[2][1] is G[2][2]
|
309 |
+
True
|
310 |
+
"""
|
311 |
+
|
312 |
+
_adj = _CachedPropertyResetterAdjAndSucc() # type: ignore[assignment]
|
313 |
+
_succ = _adj # type: ignore[has-type]
|
314 |
+
_pred = _CachedPropertyResetterPred()
|
315 |
+
|
316 |
+
def __init__(self, incoming_graph_data=None, **attr):
|
317 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
318 |
+
|
319 |
+
Parameters
|
320 |
+
----------
|
321 |
+
incoming_graph_data : input graph (optional, default: None)
|
322 |
+
Data to initialize graph. If None (default) an empty
|
323 |
+
graph is created. The data can be an edge list, or any
|
324 |
+
NetworkX graph object. If the corresponding optional Python
|
325 |
+
packages are installed the data can also be a 2D NumPy array, a
|
326 |
+
SciPy sparse array, or a PyGraphviz graph.
|
327 |
+
|
328 |
+
attr : keyword arguments, optional (default= no attributes)
|
329 |
+
Attributes to add to graph as key=value pairs.
|
330 |
+
|
331 |
+
See Also
|
332 |
+
--------
|
333 |
+
convert
|
334 |
+
|
335 |
+
Examples
|
336 |
+
--------
|
337 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
338 |
+
>>> G = nx.Graph(name="my graph")
|
339 |
+
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
|
340 |
+
>>> G = nx.Graph(e)
|
341 |
+
|
342 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
343 |
+
|
344 |
+
>>> G = nx.Graph(e, day="Friday")
|
345 |
+
>>> G.graph
|
346 |
+
{'day': 'Friday'}
|
347 |
+
|
348 |
+
"""
|
349 |
+
self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
|
350 |
+
self._node = self.node_dict_factory() # dictionary for node attr
|
351 |
+
# We store two adjacency lists:
|
352 |
+
# the predecessors of node n are stored in the dict self._pred
|
353 |
+
# the successors of node n are stored in the dict self._succ=self._adj
|
354 |
+
self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict successor
|
355 |
+
self._pred = self.adjlist_outer_dict_factory() # predecessor
|
356 |
+
# Note: self._succ = self._adj # successor
|
357 |
+
|
358 |
+
self.__networkx_cache__ = {}
|
359 |
+
# attempt to load graph with data
|
360 |
+
if incoming_graph_data is not None:
|
361 |
+
convert.to_networkx_graph(incoming_graph_data, create_using=self)
|
362 |
+
# load graph attributes (must be after convert)
|
363 |
+
self.graph.update(attr)
|
364 |
+
|
365 |
+
@cached_property
|
366 |
+
def adj(self):
|
367 |
+
"""Graph adjacency object holding the neighbors of each node.
|
368 |
+
|
369 |
+
This object is a read-only dict-like structure with node keys
|
370 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
371 |
+
to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
|
372 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
373 |
+
|
374 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
375 |
+
`for nbr, datadict in G.adj[n].items():`.
|
376 |
+
|
377 |
+
The neighbor information is also provided by subscripting the graph.
|
378 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
379 |
+
|
380 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
381 |
+
"""
|
382 |
+
return AdjacencyView(self._succ)
|
383 |
+
|
384 |
+
@cached_property
|
385 |
+
def succ(self):
|
386 |
+
"""Graph adjacency object holding the successors of each node.
|
387 |
+
|
388 |
+
This object is a read-only dict-like structure with node keys
|
389 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
390 |
+
to the edge-data-dict. So `G.succ[3][2]['color'] = 'blue'` sets
|
391 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
392 |
+
|
393 |
+
Iterating over G.succ behaves like a dict. Useful idioms include
|
394 |
+
`for nbr, datadict in G.succ[n].items():`. A data-view not provided
|
395 |
+
by dicts also exists: `for nbr, foovalue in G.succ[node].data('foo'):`
|
396 |
+
and a default can be set via a `default` argument to the `data` method.
|
397 |
+
|
398 |
+
The neighbor information is also provided by subscripting the graph.
|
399 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
400 |
+
|
401 |
+
For directed graphs, `G.adj` is identical to `G.succ`.
|
402 |
+
"""
|
403 |
+
return AdjacencyView(self._succ)
|
404 |
+
|
405 |
+
@cached_property
|
406 |
+
def pred(self):
|
407 |
+
"""Graph adjacency object holding the predecessors of each node.
|
408 |
+
|
409 |
+
This object is a read-only dict-like structure with node keys
|
410 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
411 |
+
to the edge-data-dict. So `G.pred[2][3]['color'] = 'blue'` sets
|
412 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
413 |
+
|
414 |
+
Iterating over G.pred behaves like a dict. Useful idioms include
|
415 |
+
`for nbr, datadict in G.pred[n].items():`. A data-view not provided
|
416 |
+
by dicts also exists: `for nbr, foovalue in G.pred[node].data('foo'):`
|
417 |
+
A default can be set via a `default` argument to the `data` method.
|
418 |
+
"""
|
419 |
+
return AdjacencyView(self._pred)
|
420 |
+
|
421 |
+
def add_node(self, node_for_adding, **attr):
|
422 |
+
"""Add a single node `node_for_adding` and update node attributes.
|
423 |
+
|
424 |
+
Parameters
|
425 |
+
----------
|
426 |
+
node_for_adding : node
|
427 |
+
A node can be any hashable Python object except None.
|
428 |
+
attr : keyword arguments, optional
|
429 |
+
Set or change node attributes using key=value.
|
430 |
+
|
431 |
+
See Also
|
432 |
+
--------
|
433 |
+
add_nodes_from
|
434 |
+
|
435 |
+
Examples
|
436 |
+
--------
|
437 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
438 |
+
>>> G.add_node(1)
|
439 |
+
>>> G.add_node("Hello")
|
440 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
441 |
+
>>> G.add_node(K3)
|
442 |
+
>>> G.number_of_nodes()
|
443 |
+
3
|
444 |
+
|
445 |
+
Use keywords set/change node attributes:
|
446 |
+
|
447 |
+
>>> G.add_node(1, size=10)
|
448 |
+
>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
|
449 |
+
|
450 |
+
Notes
|
451 |
+
-----
|
452 |
+
A hashable object is one that can be used as a key in a Python
|
453 |
+
dictionary. This includes strings, numbers, tuples of strings
|
454 |
+
and numbers, etc.
|
455 |
+
|
456 |
+
On many platforms hashable items also include mutables such as
|
457 |
+
NetworkX Graphs, though one should be careful that the hash
|
458 |
+
doesn't change on mutables.
|
459 |
+
"""
|
460 |
+
if node_for_adding not in self._succ:
|
461 |
+
if node_for_adding is None:
|
462 |
+
raise ValueError("None cannot be a node")
|
463 |
+
self._succ[node_for_adding] = self.adjlist_inner_dict_factory()
|
464 |
+
self._pred[node_for_adding] = self.adjlist_inner_dict_factory()
|
465 |
+
attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
|
466 |
+
attr_dict.update(attr)
|
467 |
+
else: # update attr even if node already exists
|
468 |
+
self._node[node_for_adding].update(attr)
|
469 |
+
nx._clear_cache(self)
|
470 |
+
|
471 |
+
def add_nodes_from(self, nodes_for_adding, **attr):
|
472 |
+
"""Add multiple nodes.
|
473 |
+
|
474 |
+
Parameters
|
475 |
+
----------
|
476 |
+
nodes_for_adding : iterable container
|
477 |
+
A container of nodes (list, dict, set, etc.).
|
478 |
+
OR
|
479 |
+
A container of (node, attribute dict) tuples.
|
480 |
+
Node attributes are updated using the attribute dict.
|
481 |
+
attr : keyword arguments, optional (default= no attributes)
|
482 |
+
Update attributes for all nodes in nodes.
|
483 |
+
Node attributes specified in nodes as a tuple take
|
484 |
+
precedence over attributes specified via keyword arguments.
|
485 |
+
|
486 |
+
See Also
|
487 |
+
--------
|
488 |
+
add_node
|
489 |
+
|
490 |
+
Notes
|
491 |
+
-----
|
492 |
+
When adding nodes from an iterator over the graph you are changing,
|
493 |
+
a `RuntimeError` can be raised with message:
|
494 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
495 |
+
happens when the graph's underlying dictionary is modified during
|
496 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
497 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
498 |
+
object to `G.add_nodes_from`.
|
499 |
+
|
500 |
+
Examples
|
501 |
+
--------
|
502 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
503 |
+
>>> G.add_nodes_from("Hello")
|
504 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
505 |
+
>>> G.add_nodes_from(K3)
|
506 |
+
>>> sorted(G.nodes(), key=str)
|
507 |
+
[0, 1, 2, 'H', 'e', 'l', 'o']
|
508 |
+
|
509 |
+
Use keywords to update specific node attributes for every node.
|
510 |
+
|
511 |
+
>>> G.add_nodes_from([1, 2], size=10)
|
512 |
+
>>> G.add_nodes_from([3, 4], weight=0.4)
|
513 |
+
|
514 |
+
Use (node, attrdict) tuples to update attributes for specific nodes.
|
515 |
+
|
516 |
+
>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
|
517 |
+
>>> G.nodes[1]["size"]
|
518 |
+
11
|
519 |
+
>>> H = nx.Graph()
|
520 |
+
>>> H.add_nodes_from(G.nodes(data=True))
|
521 |
+
>>> H.nodes[1]["size"]
|
522 |
+
11
|
523 |
+
|
524 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
525 |
+
|
526 |
+
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
|
527 |
+
>>> # wrong way - will raise RuntimeError
|
528 |
+
>>> # G.add_nodes_from(n + 1 for n in G.nodes)
|
529 |
+
>>> # correct way
|
530 |
+
>>> G.add_nodes_from(list(n + 1 for n in G.nodes))
|
531 |
+
"""
|
532 |
+
for n in nodes_for_adding:
|
533 |
+
try:
|
534 |
+
newnode = n not in self._node
|
535 |
+
newdict = attr
|
536 |
+
except TypeError:
|
537 |
+
n, ndict = n
|
538 |
+
newnode = n not in self._node
|
539 |
+
newdict = attr.copy()
|
540 |
+
newdict.update(ndict)
|
541 |
+
if newnode:
|
542 |
+
if n is None:
|
543 |
+
raise ValueError("None cannot be a node")
|
544 |
+
self._succ[n] = self.adjlist_inner_dict_factory()
|
545 |
+
self._pred[n] = self.adjlist_inner_dict_factory()
|
546 |
+
self._node[n] = self.node_attr_dict_factory()
|
547 |
+
self._node[n].update(newdict)
|
548 |
+
nx._clear_cache(self)
|
549 |
+
|
550 |
+
def remove_node(self, n):
|
551 |
+
"""Remove node n.
|
552 |
+
|
553 |
+
Removes the node n and all adjacent edges.
|
554 |
+
Attempting to remove a nonexistent node will raise an exception.
|
555 |
+
|
556 |
+
Parameters
|
557 |
+
----------
|
558 |
+
n : node
|
559 |
+
A node in the graph
|
560 |
+
|
561 |
+
Raises
|
562 |
+
------
|
563 |
+
NetworkXError
|
564 |
+
If n is not in the graph.
|
565 |
+
|
566 |
+
See Also
|
567 |
+
--------
|
568 |
+
remove_nodes_from
|
569 |
+
|
570 |
+
Examples
|
571 |
+
--------
|
572 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
573 |
+
>>> list(G.edges)
|
574 |
+
[(0, 1), (1, 2)]
|
575 |
+
>>> G.remove_node(1)
|
576 |
+
>>> list(G.edges)
|
577 |
+
[]
|
578 |
+
|
579 |
+
"""
|
580 |
+
try:
|
581 |
+
nbrs = self._succ[n]
|
582 |
+
del self._node[n]
|
583 |
+
except KeyError as err: # NetworkXError if n not in self
|
584 |
+
raise NetworkXError(f"The node {n} is not in the digraph.") from err
|
585 |
+
for u in nbrs:
|
586 |
+
del self._pred[u][n] # remove all edges n-u in digraph
|
587 |
+
del self._succ[n] # remove node from succ
|
588 |
+
for u in self._pred[n]:
|
589 |
+
del self._succ[u][n] # remove all edges n-u in digraph
|
590 |
+
del self._pred[n] # remove node from pred
|
591 |
+
nx._clear_cache(self)
|
592 |
+
|
593 |
+
def remove_nodes_from(self, nodes):
|
594 |
+
"""Remove multiple nodes.
|
595 |
+
|
596 |
+
Parameters
|
597 |
+
----------
|
598 |
+
nodes : iterable container
|
599 |
+
A container of nodes (list, dict, set, etc.). If a node
|
600 |
+
in the container is not in the graph it is silently ignored.
|
601 |
+
|
602 |
+
See Also
|
603 |
+
--------
|
604 |
+
remove_node
|
605 |
+
|
606 |
+
Notes
|
607 |
+
-----
|
608 |
+
When removing nodes from an iterator over the graph you are changing,
|
609 |
+
a `RuntimeError` will be raised with message:
|
610 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
611 |
+
happens when the graph's underlying dictionary is modified during
|
612 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
613 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
614 |
+
object to `G.remove_nodes_from`.
|
615 |
+
|
616 |
+
Examples
|
617 |
+
--------
|
618 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
619 |
+
>>> e = list(G.nodes)
|
620 |
+
>>> e
|
621 |
+
[0, 1, 2]
|
622 |
+
>>> G.remove_nodes_from(e)
|
623 |
+
>>> list(G.nodes)
|
624 |
+
[]
|
625 |
+
|
626 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
627 |
+
|
628 |
+
>>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)])
|
629 |
+
>>> # this command will fail, as the graph's dict is modified during iteration
|
630 |
+
>>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
|
631 |
+
>>> # this command will work, since the dictionary underlying graph is not modified
|
632 |
+
>>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
|
633 |
+
"""
|
634 |
+
for n in nodes:
|
635 |
+
try:
|
636 |
+
succs = self._succ[n]
|
637 |
+
del self._node[n]
|
638 |
+
for u in succs:
|
639 |
+
del self._pred[u][n] # remove all edges n-u in digraph
|
640 |
+
del self._succ[n] # now remove node
|
641 |
+
for u in self._pred[n]:
|
642 |
+
del self._succ[u][n] # remove all edges n-u in digraph
|
643 |
+
del self._pred[n] # now remove node
|
644 |
+
except KeyError:
|
645 |
+
pass # silent failure on remove
|
646 |
+
nx._clear_cache(self)
|
647 |
+
|
648 |
+
def add_edge(self, u_of_edge, v_of_edge, **attr):
|
649 |
+
"""Add an edge between u and v.
|
650 |
+
|
651 |
+
The nodes u and v will be automatically added if they are
|
652 |
+
not already in the graph.
|
653 |
+
|
654 |
+
Edge attributes can be specified with keywords or by directly
|
655 |
+
accessing the edge's attribute dictionary. See examples below.
|
656 |
+
|
657 |
+
Parameters
|
658 |
+
----------
|
659 |
+
u_of_edge, v_of_edge : nodes
|
660 |
+
Nodes can be, for example, strings or numbers.
|
661 |
+
Nodes must be hashable (and not None) Python objects.
|
662 |
+
attr : keyword arguments, optional
|
663 |
+
Edge data (or labels or objects) can be assigned using
|
664 |
+
keyword arguments.
|
665 |
+
|
666 |
+
See Also
|
667 |
+
--------
|
668 |
+
add_edges_from : add a collection of edges
|
669 |
+
|
670 |
+
Notes
|
671 |
+
-----
|
672 |
+
Adding an edge that already exists updates the edge data.
|
673 |
+
|
674 |
+
Many NetworkX algorithms designed for weighted graphs use
|
675 |
+
an edge attribute (by default `weight`) to hold a numerical value.
|
676 |
+
|
677 |
+
Examples
|
678 |
+
--------
|
679 |
+
The following all add the edge e=(1, 2) to graph G:
|
680 |
+
|
681 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
682 |
+
>>> e = (1, 2)
|
683 |
+
>>> G.add_edge(1, 2) # explicit two-node form
|
684 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
685 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
686 |
+
|
687 |
+
Associate data to edges using keywords:
|
688 |
+
|
689 |
+
>>> G.add_edge(1, 2, weight=3)
|
690 |
+
>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
691 |
+
|
692 |
+
For non-string attribute keys, use subscript notation.
|
693 |
+
|
694 |
+
>>> G.add_edge(1, 2)
|
695 |
+
>>> G[1][2].update({0: 5})
|
696 |
+
>>> G.edges[1, 2].update({0: 5})
|
697 |
+
"""
|
698 |
+
u, v = u_of_edge, v_of_edge
|
699 |
+
# add nodes
|
700 |
+
if u not in self._succ:
|
701 |
+
if u is None:
|
702 |
+
raise ValueError("None cannot be a node")
|
703 |
+
self._succ[u] = self.adjlist_inner_dict_factory()
|
704 |
+
self._pred[u] = self.adjlist_inner_dict_factory()
|
705 |
+
self._node[u] = self.node_attr_dict_factory()
|
706 |
+
if v not in self._succ:
|
707 |
+
if v is None:
|
708 |
+
raise ValueError("None cannot be a node")
|
709 |
+
self._succ[v] = self.adjlist_inner_dict_factory()
|
710 |
+
self._pred[v] = self.adjlist_inner_dict_factory()
|
711 |
+
self._node[v] = self.node_attr_dict_factory()
|
712 |
+
# add the edge
|
713 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
714 |
+
datadict.update(attr)
|
715 |
+
self._succ[u][v] = datadict
|
716 |
+
self._pred[v][u] = datadict
|
717 |
+
nx._clear_cache(self)
|
718 |
+
|
719 |
+
def add_edges_from(self, ebunch_to_add, **attr):
|
720 |
+
"""Add all the edges in ebunch_to_add.
|
721 |
+
|
722 |
+
Parameters
|
723 |
+
----------
|
724 |
+
ebunch_to_add : container of edges
|
725 |
+
Each edge given in the container will be added to the
|
726 |
+
graph. The edges must be given as 2-tuples (u, v) or
|
727 |
+
3-tuples (u, v, d) where d is a dictionary containing edge data.
|
728 |
+
attr : keyword arguments, optional
|
729 |
+
Edge data (or labels or objects) can be assigned using
|
730 |
+
keyword arguments.
|
731 |
+
|
732 |
+
See Also
|
733 |
+
--------
|
734 |
+
add_edge : add a single edge
|
735 |
+
add_weighted_edges_from : convenient way to add weighted edges
|
736 |
+
|
737 |
+
Notes
|
738 |
+
-----
|
739 |
+
Adding the same edge twice has no effect but any edge data
|
740 |
+
will be updated when each duplicate edge is added.
|
741 |
+
|
742 |
+
Edge attributes specified in an ebunch take precedence over
|
743 |
+
attributes specified via keyword arguments.
|
744 |
+
|
745 |
+
When adding edges from an iterator over the graph you are changing,
|
746 |
+
a `RuntimeError` can be raised with message:
|
747 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
748 |
+
happens when the graph's underlying dictionary is modified during
|
749 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
750 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
751 |
+
object to `G.add_edges_from`.
|
752 |
+
|
753 |
+
Examples
|
754 |
+
--------
|
755 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
756 |
+
>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
|
757 |
+
>>> e = zip(range(0, 3), range(1, 4))
|
758 |
+
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3
|
759 |
+
|
760 |
+
Associate data to edges
|
761 |
+
|
762 |
+
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
|
763 |
+
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
|
764 |
+
|
765 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
766 |
+
|
767 |
+
>>> G = nx.DiGraph([(1, 2), (2, 3), (3, 4)])
|
768 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
769 |
+
>>> # wrong way - will raise RuntimeError
|
770 |
+
>>> # G.add_edges_from(((5, n) for n in G.nodes))
|
771 |
+
>>> # right way - note that there will be no self-edge for node 5
|
772 |
+
>>> G.add_edges_from(list((5, n) for n in G.nodes))
|
773 |
+
"""
|
774 |
+
for e in ebunch_to_add:
|
775 |
+
ne = len(e)
|
776 |
+
if ne == 3:
|
777 |
+
u, v, dd = e
|
778 |
+
elif ne == 2:
|
779 |
+
u, v = e
|
780 |
+
dd = {}
|
781 |
+
else:
|
782 |
+
raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
|
783 |
+
if u not in self._succ:
|
784 |
+
if u is None:
|
785 |
+
raise ValueError("None cannot be a node")
|
786 |
+
self._succ[u] = self.adjlist_inner_dict_factory()
|
787 |
+
self._pred[u] = self.adjlist_inner_dict_factory()
|
788 |
+
self._node[u] = self.node_attr_dict_factory()
|
789 |
+
if v not in self._succ:
|
790 |
+
if v is None:
|
791 |
+
raise ValueError("None cannot be a node")
|
792 |
+
self._succ[v] = self.adjlist_inner_dict_factory()
|
793 |
+
self._pred[v] = self.adjlist_inner_dict_factory()
|
794 |
+
self._node[v] = self.node_attr_dict_factory()
|
795 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
796 |
+
datadict.update(attr)
|
797 |
+
datadict.update(dd)
|
798 |
+
self._succ[u][v] = datadict
|
799 |
+
self._pred[v][u] = datadict
|
800 |
+
nx._clear_cache(self)
|
801 |
+
|
802 |
+
def remove_edge(self, u, v):
|
803 |
+
"""Remove the edge between u and v.
|
804 |
+
|
805 |
+
Parameters
|
806 |
+
----------
|
807 |
+
u, v : nodes
|
808 |
+
Remove the edge between nodes u and v.
|
809 |
+
|
810 |
+
Raises
|
811 |
+
------
|
812 |
+
NetworkXError
|
813 |
+
If there is not an edge between u and v.
|
814 |
+
|
815 |
+
See Also
|
816 |
+
--------
|
817 |
+
remove_edges_from : remove a collection of edges
|
818 |
+
|
819 |
+
Examples
|
820 |
+
--------
|
821 |
+
>>> G = nx.Graph() # or DiGraph, etc
|
822 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
823 |
+
>>> G.remove_edge(0, 1)
|
824 |
+
>>> e = (1, 2)
|
825 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
826 |
+
>>> e = (2, 3, {"weight": 7}) # an edge with attribute data
|
827 |
+
>>> G.remove_edge(*e[:2]) # select first part of edge tuple
|
828 |
+
"""
|
829 |
+
try:
|
830 |
+
del self._succ[u][v]
|
831 |
+
del self._pred[v][u]
|
832 |
+
except KeyError as err:
|
833 |
+
raise NetworkXError(f"The edge {u}-{v} not in graph.") from err
|
834 |
+
nx._clear_cache(self)
|
835 |
+
|
836 |
+
def remove_edges_from(self, ebunch):
|
837 |
+
"""Remove all edges specified in ebunch.
|
838 |
+
|
839 |
+
Parameters
|
840 |
+
----------
|
841 |
+
ebunch: list or container of edge tuples
|
842 |
+
Each edge given in the list or container will be removed
|
843 |
+
from the graph. The edges can be:
|
844 |
+
|
845 |
+
- 2-tuples (u, v) edge between u and v.
|
846 |
+
- 3-tuples (u, v, k) where k is ignored.
|
847 |
+
|
848 |
+
See Also
|
849 |
+
--------
|
850 |
+
remove_edge : remove a single edge
|
851 |
+
|
852 |
+
Notes
|
853 |
+
-----
|
854 |
+
Will fail silently if an edge in ebunch is not in the graph.
|
855 |
+
|
856 |
+
Examples
|
857 |
+
--------
|
858 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
859 |
+
>>> ebunch = [(1, 2), (2, 3)]
|
860 |
+
>>> G.remove_edges_from(ebunch)
|
861 |
+
"""
|
862 |
+
for e in ebunch:
|
863 |
+
u, v = e[:2] # ignore edge data
|
864 |
+
if u in self._succ and v in self._succ[u]:
|
865 |
+
del self._succ[u][v]
|
866 |
+
del self._pred[v][u]
|
867 |
+
nx._clear_cache(self)
|
868 |
+
|
869 |
+
def has_successor(self, u, v):
|
870 |
+
"""Returns True if node u has successor v.
|
871 |
+
|
872 |
+
This is true if graph has the edge u->v.
|
873 |
+
"""
|
874 |
+
return u in self._succ and v in self._succ[u]
|
875 |
+
|
876 |
+
def has_predecessor(self, u, v):
|
877 |
+
"""Returns True if node u has predecessor v.
|
878 |
+
|
879 |
+
This is true if graph has the edge u<-v.
|
880 |
+
"""
|
881 |
+
return u in self._pred and v in self._pred[u]
|
882 |
+
|
883 |
+
def successors(self, n):
|
884 |
+
"""Returns an iterator over successor nodes of n.
|
885 |
+
|
886 |
+
A successor of n is a node m such that there exists a directed
|
887 |
+
edge from n to m.
|
888 |
+
|
889 |
+
Parameters
|
890 |
+
----------
|
891 |
+
n : node
|
892 |
+
A node in the graph
|
893 |
+
|
894 |
+
Raises
|
895 |
+
------
|
896 |
+
NetworkXError
|
897 |
+
If n is not in the graph.
|
898 |
+
|
899 |
+
See Also
|
900 |
+
--------
|
901 |
+
predecessors
|
902 |
+
|
903 |
+
Notes
|
904 |
+
-----
|
905 |
+
neighbors() and successors() are the same.
|
906 |
+
"""
|
907 |
+
try:
|
908 |
+
return iter(self._succ[n])
|
909 |
+
except KeyError as err:
|
910 |
+
raise NetworkXError(f"The node {n} is not in the digraph.") from err
|
911 |
+
|
912 |
+
# digraph definitions
|
913 |
+
neighbors = successors
|
914 |
+
|
915 |
+
def predecessors(self, n):
|
916 |
+
"""Returns an iterator over predecessor nodes of n.
|
917 |
+
|
918 |
+
A predecessor of n is a node m such that there exists a directed
|
919 |
+
edge from m to n.
|
920 |
+
|
921 |
+
Parameters
|
922 |
+
----------
|
923 |
+
n : node
|
924 |
+
A node in the graph
|
925 |
+
|
926 |
+
Raises
|
927 |
+
------
|
928 |
+
NetworkXError
|
929 |
+
If n is not in the graph.
|
930 |
+
|
931 |
+
See Also
|
932 |
+
--------
|
933 |
+
successors
|
934 |
+
"""
|
935 |
+
try:
|
936 |
+
return iter(self._pred[n])
|
937 |
+
except KeyError as err:
|
938 |
+
raise NetworkXError(f"The node {n} is not in the digraph.") from err
|
939 |
+
|
940 |
+
@cached_property
|
941 |
+
def edges(self):
|
942 |
+
"""An OutEdgeView of the DiGraph as G.edges or G.edges().
|
943 |
+
|
944 |
+
edges(self, nbunch=None, data=False, default=None)
|
945 |
+
|
946 |
+
The OutEdgeView provides set-like operations on the edge-tuples
|
947 |
+
as well as edge attribute lookup. When called, it also provides
|
948 |
+
an EdgeDataView object which allows control of access to edge
|
949 |
+
attributes (but does not provide set-like operations).
|
950 |
+
Hence, `G.edges[u, v]['color']` provides the value of the color
|
951 |
+
attribute for edge `(u, v)` while
|
952 |
+
`for (u, v, c) in G.edges.data('color', default='red'):`
|
953 |
+
iterates through all the edges yielding the color attribute
|
954 |
+
with default `'red'` if no color attribute exists.
|
955 |
+
|
956 |
+
Parameters
|
957 |
+
----------
|
958 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
959 |
+
The view will only report edges from these nodes.
|
960 |
+
data : string or bool, optional (default=False)
|
961 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
962 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
963 |
+
If False, return 2-tuple (u, v).
|
964 |
+
default : value, optional (default=None)
|
965 |
+
Value used for edges that don't have the requested attribute.
|
966 |
+
Only relevant if data is not True or False.
|
967 |
+
|
968 |
+
Returns
|
969 |
+
-------
|
970 |
+
edges : OutEdgeView
|
971 |
+
A view of edge attributes, usually it iterates over (u, v)
|
972 |
+
or (u, v, d) tuples of edges, but can also be used for
|
973 |
+
attribute lookup as `edges[u, v]['foo']`.
|
974 |
+
|
975 |
+
See Also
|
976 |
+
--------
|
977 |
+
in_edges, out_edges
|
978 |
+
|
979 |
+
Notes
|
980 |
+
-----
|
981 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
982 |
+
For directed graphs this returns the out-edges.
|
983 |
+
|
984 |
+
Examples
|
985 |
+
--------
|
986 |
+
>>> G = nx.DiGraph() # or MultiDiGraph, etc
|
987 |
+
>>> nx.add_path(G, [0, 1, 2])
|
988 |
+
>>> G.add_edge(2, 3, weight=5)
|
989 |
+
>>> [e for e in G.edges]
|
990 |
+
[(0, 1), (1, 2), (2, 3)]
|
991 |
+
>>> G.edges.data() # default data is {} (empty dict)
|
992 |
+
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
|
993 |
+
>>> G.edges.data("weight", default=1)
|
994 |
+
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
|
995 |
+
>>> G.edges([0, 2]) # only edges originating from these nodes
|
996 |
+
OutEdgeDataView([(0, 1), (2, 3)])
|
997 |
+
>>> G.edges(0) # only edges from node 0
|
998 |
+
OutEdgeDataView([(0, 1)])
|
999 |
+
|
1000 |
+
"""
|
1001 |
+
return OutEdgeView(self)
|
1002 |
+
|
1003 |
+
# alias out_edges to edges
|
1004 |
+
@cached_property
|
1005 |
+
def out_edges(self):
|
1006 |
+
return OutEdgeView(self)
|
1007 |
+
|
1008 |
+
out_edges.__doc__ = edges.__doc__
|
1009 |
+
|
1010 |
+
@cached_property
|
1011 |
+
def in_edges(self):
|
1012 |
+
"""A view of the in edges of the graph as G.in_edges or G.in_edges().
|
1013 |
+
|
1014 |
+
in_edges(self, nbunch=None, data=False, default=None):
|
1015 |
+
|
1016 |
+
Parameters
|
1017 |
+
----------
|
1018 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1019 |
+
The view will only report edges incident to these nodes.
|
1020 |
+
data : string or bool, optional (default=False)
|
1021 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
1022 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
1023 |
+
If False, return 2-tuple (u, v).
|
1024 |
+
default : value, optional (default=None)
|
1025 |
+
Value used for edges that don't have the requested attribute.
|
1026 |
+
Only relevant if data is not True or False.
|
1027 |
+
|
1028 |
+
Returns
|
1029 |
+
-------
|
1030 |
+
in_edges : InEdgeView or InEdgeDataView
|
1031 |
+
A view of edge attributes, usually it iterates over (u, v)
|
1032 |
+
or (u, v, d) tuples of edges, but can also be used for
|
1033 |
+
attribute lookup as `edges[u, v]['foo']`.
|
1034 |
+
|
1035 |
+
Examples
|
1036 |
+
--------
|
1037 |
+
>>> G = nx.DiGraph()
|
1038 |
+
>>> G.add_edge(1, 2, color="blue")
|
1039 |
+
>>> G.in_edges()
|
1040 |
+
InEdgeView([(1, 2)])
|
1041 |
+
>>> G.in_edges(nbunch=2)
|
1042 |
+
InEdgeDataView([(1, 2)])
|
1043 |
+
|
1044 |
+
See Also
|
1045 |
+
--------
|
1046 |
+
edges
|
1047 |
+
"""
|
1048 |
+
return InEdgeView(self)
|
1049 |
+
|
1050 |
+
@cached_property
|
1051 |
+
def degree(self):
|
1052 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
1053 |
+
|
1054 |
+
The node degree is the number of edges adjacent to the node.
|
1055 |
+
The weighted node degree is the sum of the edge weights for
|
1056 |
+
edges incident to that node.
|
1057 |
+
|
1058 |
+
This object provides an iterator for (node, degree) as well as
|
1059 |
+
lookup for the degree for a single node.
|
1060 |
+
|
1061 |
+
Parameters
|
1062 |
+
----------
|
1063 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1064 |
+
The view will only report edges incident to these nodes.
|
1065 |
+
|
1066 |
+
weight : string or None, optional (default=None)
|
1067 |
+
The name of an edge attribute that holds the numerical value used
|
1068 |
+
as a weight. If None, then each edge has weight 1.
|
1069 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1070 |
+
|
1071 |
+
Returns
|
1072 |
+
-------
|
1073 |
+
DiDegreeView or int
|
1074 |
+
If multiple nodes are requested (the default), returns a `DiDegreeView`
|
1075 |
+
mapping nodes to their degree.
|
1076 |
+
If a single node is requested, returns the degree of the node as an integer.
|
1077 |
+
|
1078 |
+
See Also
|
1079 |
+
--------
|
1080 |
+
in_degree, out_degree
|
1081 |
+
|
1082 |
+
Examples
|
1083 |
+
--------
|
1084 |
+
>>> G = nx.DiGraph() # or MultiDiGraph
|
1085 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1086 |
+
>>> G.degree(0) # node 0 with degree 1
|
1087 |
+
1
|
1088 |
+
>>> list(G.degree([0, 1, 2]))
|
1089 |
+
[(0, 1), (1, 2), (2, 2)]
|
1090 |
+
|
1091 |
+
"""
|
1092 |
+
return DiDegreeView(self)
|
1093 |
+
|
1094 |
+
@cached_property
|
1095 |
+
def in_degree(self):
|
1096 |
+
"""An InDegreeView for (node, in_degree) or in_degree for single node.
|
1097 |
+
|
1098 |
+
The node in_degree is the number of edges pointing to the node.
|
1099 |
+
The weighted node degree is the sum of the edge weights for
|
1100 |
+
edges incident to that node.
|
1101 |
+
|
1102 |
+
This object provides an iteration over (node, in_degree) as well as
|
1103 |
+
lookup for the degree for a single node.
|
1104 |
+
|
1105 |
+
Parameters
|
1106 |
+
----------
|
1107 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1108 |
+
The view will only report edges incident to these nodes.
|
1109 |
+
|
1110 |
+
weight : string or None, optional (default=None)
|
1111 |
+
The name of an edge attribute that holds the numerical value used
|
1112 |
+
as a weight. If None, then each edge has weight 1.
|
1113 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1114 |
+
|
1115 |
+
Returns
|
1116 |
+
-------
|
1117 |
+
If a single node is requested
|
1118 |
+
deg : int
|
1119 |
+
In-degree of the node
|
1120 |
+
|
1121 |
+
OR if multiple nodes are requested
|
1122 |
+
nd_iter : iterator
|
1123 |
+
The iterator returns two-tuples of (node, in-degree).
|
1124 |
+
|
1125 |
+
See Also
|
1126 |
+
--------
|
1127 |
+
degree, out_degree
|
1128 |
+
|
1129 |
+
Examples
|
1130 |
+
--------
|
1131 |
+
>>> G = nx.DiGraph()
|
1132 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1133 |
+
>>> G.in_degree(0) # node 0 with degree 0
|
1134 |
+
0
|
1135 |
+
>>> list(G.in_degree([0, 1, 2]))
|
1136 |
+
[(0, 0), (1, 1), (2, 1)]
|
1137 |
+
|
1138 |
+
"""
|
1139 |
+
return InDegreeView(self)
|
1140 |
+
|
1141 |
+
@cached_property
|
1142 |
+
def out_degree(self):
|
1143 |
+
"""An OutDegreeView for (node, out_degree)
|
1144 |
+
|
1145 |
+
The node out_degree is the number of edges pointing out of the node.
|
1146 |
+
The weighted node degree is the sum of the edge weights for
|
1147 |
+
edges incident to that node.
|
1148 |
+
|
1149 |
+
This object provides an iterator over (node, out_degree) as well as
|
1150 |
+
lookup for the degree for a single node.
|
1151 |
+
|
1152 |
+
Parameters
|
1153 |
+
----------
|
1154 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1155 |
+
The view will only report edges incident to these nodes.
|
1156 |
+
|
1157 |
+
weight : string or None, optional (default=None)
|
1158 |
+
The name of an edge attribute that holds the numerical value used
|
1159 |
+
as a weight. If None, then each edge has weight 1.
|
1160 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1161 |
+
|
1162 |
+
Returns
|
1163 |
+
-------
|
1164 |
+
If a single node is requested
|
1165 |
+
deg : int
|
1166 |
+
Out-degree of the node
|
1167 |
+
|
1168 |
+
OR if multiple nodes are requested
|
1169 |
+
nd_iter : iterator
|
1170 |
+
The iterator returns two-tuples of (node, out-degree).
|
1171 |
+
|
1172 |
+
See Also
|
1173 |
+
--------
|
1174 |
+
degree, in_degree
|
1175 |
+
|
1176 |
+
Examples
|
1177 |
+
--------
|
1178 |
+
>>> G = nx.DiGraph()
|
1179 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
1180 |
+
>>> G.out_degree(0) # node 0 with degree 1
|
1181 |
+
1
|
1182 |
+
>>> list(G.out_degree([0, 1, 2]))
|
1183 |
+
[(0, 1), (1, 1), (2, 1)]
|
1184 |
+
|
1185 |
+
"""
|
1186 |
+
return OutDegreeView(self)
|
1187 |
+
|
1188 |
+
def clear(self):
|
1189 |
+
"""Remove all nodes and edges from the graph.
|
1190 |
+
|
1191 |
+
This also removes the name, and all graph, node, and edge attributes.
|
1192 |
+
|
1193 |
+
Examples
|
1194 |
+
--------
|
1195 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1196 |
+
>>> G.clear()
|
1197 |
+
>>> list(G.nodes)
|
1198 |
+
[]
|
1199 |
+
>>> list(G.edges)
|
1200 |
+
[]
|
1201 |
+
|
1202 |
+
"""
|
1203 |
+
self._succ.clear()
|
1204 |
+
self._pred.clear()
|
1205 |
+
self._node.clear()
|
1206 |
+
self.graph.clear()
|
1207 |
+
nx._clear_cache(self)
|
1208 |
+
|
1209 |
+
def clear_edges(self):
|
1210 |
+
"""Remove all edges from the graph without altering nodes.
|
1211 |
+
|
1212 |
+
Examples
|
1213 |
+
--------
|
1214 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1215 |
+
>>> G.clear_edges()
|
1216 |
+
>>> list(G.nodes)
|
1217 |
+
[0, 1, 2, 3]
|
1218 |
+
>>> list(G.edges)
|
1219 |
+
[]
|
1220 |
+
|
1221 |
+
"""
|
1222 |
+
for predecessor_dict in self._pred.values():
|
1223 |
+
predecessor_dict.clear()
|
1224 |
+
for successor_dict in self._succ.values():
|
1225 |
+
successor_dict.clear()
|
1226 |
+
nx._clear_cache(self)
|
1227 |
+
|
1228 |
+
def is_multigraph(self):
|
1229 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
1230 |
+
return False
|
1231 |
+
|
1232 |
+
def is_directed(self):
|
1233 |
+
"""Returns True if graph is directed, False otherwise."""
|
1234 |
+
return True
|
1235 |
+
|
1236 |
+
def to_undirected(self, reciprocal=False, as_view=False):
|
1237 |
+
"""Returns an undirected representation of the digraph.
|
1238 |
+
|
1239 |
+
Parameters
|
1240 |
+
----------
|
1241 |
+
reciprocal : bool (optional)
|
1242 |
+
If True only keep edges that appear in both directions
|
1243 |
+
in the original digraph.
|
1244 |
+
as_view : bool (optional, default=False)
|
1245 |
+
If True return an undirected view of the original directed graph.
|
1246 |
+
|
1247 |
+
Returns
|
1248 |
+
-------
|
1249 |
+
G : Graph
|
1250 |
+
An undirected graph with the same name and nodes and
|
1251 |
+
with edge (u, v, data) if either (u, v, data) or (v, u, data)
|
1252 |
+
is in the digraph. If both edges exist in digraph and
|
1253 |
+
their edge data is different, only one edge is created
|
1254 |
+
with an arbitrary choice of which edge data to use.
|
1255 |
+
You must check and correct for this manually if desired.
|
1256 |
+
|
1257 |
+
See Also
|
1258 |
+
--------
|
1259 |
+
Graph, copy, add_edge, add_edges_from
|
1260 |
+
|
1261 |
+
Notes
|
1262 |
+
-----
|
1263 |
+
If edges in both directions (u, v) and (v, u) exist in the
|
1264 |
+
graph, attributes for the new undirected edge will be a combination of
|
1265 |
+
the attributes of the directed edges. The edge data is updated
|
1266 |
+
in the (arbitrary) order that the edges are encountered. For
|
1267 |
+
more customized control of the edge attributes use add_edge().
|
1268 |
+
|
1269 |
+
This returns a "deepcopy" of the edge, node, and
|
1270 |
+
graph attributes which attempts to completely copy
|
1271 |
+
all of the data and references.
|
1272 |
+
|
1273 |
+
This is in contrast to the similar G=DiGraph(D) which returns a
|
1274 |
+
shallow copy of the data.
|
1275 |
+
|
1276 |
+
See the Python copy module for more information on shallow
|
1277 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1278 |
+
|
1279 |
+
Warning: If you have subclassed DiGraph to use dict-like objects
|
1280 |
+
in the data structure, those changes do not transfer to the
|
1281 |
+
Graph created by this method.
|
1282 |
+
|
1283 |
+
Examples
|
1284 |
+
--------
|
1285 |
+
>>> G = nx.path_graph(2) # or MultiGraph, etc
|
1286 |
+
>>> H = G.to_directed()
|
1287 |
+
>>> list(H.edges)
|
1288 |
+
[(0, 1), (1, 0)]
|
1289 |
+
>>> G2 = H.to_undirected()
|
1290 |
+
>>> list(G2.edges)
|
1291 |
+
[(0, 1)]
|
1292 |
+
"""
|
1293 |
+
graph_class = self.to_undirected_class()
|
1294 |
+
if as_view is True:
|
1295 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1296 |
+
# deepcopy when not a view
|
1297 |
+
G = graph_class()
|
1298 |
+
G.graph.update(deepcopy(self.graph))
|
1299 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1300 |
+
if reciprocal is True:
|
1301 |
+
G.add_edges_from(
|
1302 |
+
(u, v, deepcopy(d))
|
1303 |
+
for u, nbrs in self._adj.items()
|
1304 |
+
for v, d in nbrs.items()
|
1305 |
+
if v in self._pred[u]
|
1306 |
+
)
|
1307 |
+
else:
|
1308 |
+
G.add_edges_from(
|
1309 |
+
(u, v, deepcopy(d))
|
1310 |
+
for u, nbrs in self._adj.items()
|
1311 |
+
for v, d in nbrs.items()
|
1312 |
+
)
|
1313 |
+
return G
|
1314 |
+
|
1315 |
+
def reverse(self, copy=True):
|
1316 |
+
"""Returns the reverse of the graph.
|
1317 |
+
|
1318 |
+
The reverse is a graph with the same nodes and edges
|
1319 |
+
but with the directions of the edges reversed.
|
1320 |
+
|
1321 |
+
Parameters
|
1322 |
+
----------
|
1323 |
+
copy : bool optional (default=True)
|
1324 |
+
If True, return a new DiGraph holding the reversed edges.
|
1325 |
+
If False, the reverse graph is created using a view of
|
1326 |
+
the original graph.
|
1327 |
+
"""
|
1328 |
+
if copy:
|
1329 |
+
H = self.__class__()
|
1330 |
+
H.graph.update(deepcopy(self.graph))
|
1331 |
+
H.add_nodes_from((n, deepcopy(d)) for n, d in self.nodes.items())
|
1332 |
+
H.add_edges_from((v, u, deepcopy(d)) for u, v, d in self.edges(data=True))
|
1333 |
+
return H
|
1334 |
+
return nx.reverse_view(self)
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/filters.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Filter factories to hide or show sets of nodes and edges.
|
2 |
+
|
3 |
+
These filters return the function used when creating `SubGraph`.
|
4 |
+
"""
|
5 |
+
__all__ = [
|
6 |
+
"no_filter",
|
7 |
+
"hide_nodes",
|
8 |
+
"hide_edges",
|
9 |
+
"hide_multiedges",
|
10 |
+
"hide_diedges",
|
11 |
+
"hide_multidiedges",
|
12 |
+
"show_nodes",
|
13 |
+
"show_edges",
|
14 |
+
"show_multiedges",
|
15 |
+
"show_diedges",
|
16 |
+
"show_multidiedges",
|
17 |
+
]
|
18 |
+
|
19 |
+
|
20 |
+
def no_filter(*items):
|
21 |
+
"""Returns a filter function that always evaluates to True."""
|
22 |
+
return True
|
23 |
+
|
24 |
+
|
25 |
+
def hide_nodes(nodes):
|
26 |
+
"""Returns a filter function that hides specific nodes."""
|
27 |
+
nodes = set(nodes)
|
28 |
+
return lambda node: node not in nodes
|
29 |
+
|
30 |
+
|
31 |
+
def hide_diedges(edges):
|
32 |
+
"""Returns a filter function that hides specific directed edges."""
|
33 |
+
edges = {(u, v) for u, v in edges}
|
34 |
+
return lambda u, v: (u, v) not in edges
|
35 |
+
|
36 |
+
|
37 |
+
def hide_edges(edges):
|
38 |
+
"""Returns a filter function that hides specific undirected edges."""
|
39 |
+
alledges = set(edges) | {(v, u) for (u, v) in edges}
|
40 |
+
return lambda u, v: (u, v) not in alledges
|
41 |
+
|
42 |
+
|
43 |
+
def hide_multidiedges(edges):
|
44 |
+
"""Returns a filter function that hides specific multi-directed edges."""
|
45 |
+
edges = {(u, v, k) for u, v, k in edges}
|
46 |
+
return lambda u, v, k: (u, v, k) not in edges
|
47 |
+
|
48 |
+
|
49 |
+
def hide_multiedges(edges):
|
50 |
+
"""Returns a filter function that hides specific multi-undirected edges."""
|
51 |
+
alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
|
52 |
+
return lambda u, v, k: (u, v, k) not in alledges
|
53 |
+
|
54 |
+
|
55 |
+
# write show_nodes as a class to make SubGraph pickleable
|
56 |
+
class show_nodes:
|
57 |
+
"""Filter class to show specific nodes."""
|
58 |
+
|
59 |
+
def __init__(self, nodes):
|
60 |
+
self.nodes = set(nodes)
|
61 |
+
|
62 |
+
def __call__(self, node):
|
63 |
+
return node in self.nodes
|
64 |
+
|
65 |
+
|
66 |
+
def show_diedges(edges):
|
67 |
+
"""Returns a filter function that shows specific directed edges."""
|
68 |
+
edges = {(u, v) for u, v in edges}
|
69 |
+
return lambda u, v: (u, v) in edges
|
70 |
+
|
71 |
+
|
72 |
+
def show_edges(edges):
|
73 |
+
"""Returns a filter function that shows specific undirected edges."""
|
74 |
+
alledges = set(edges) | {(v, u) for (u, v) in edges}
|
75 |
+
return lambda u, v: (u, v) in alledges
|
76 |
+
|
77 |
+
|
78 |
+
def show_multidiedges(edges):
|
79 |
+
"""Returns a filter function that shows specific multi-directed edges."""
|
80 |
+
edges = {(u, v, k) for u, v, k in edges}
|
81 |
+
return lambda u, v, k: (u, v, k) in edges
|
82 |
+
|
83 |
+
|
84 |
+
def show_multiedges(edges):
|
85 |
+
"""Returns a filter function that shows specific multi-undirected edges."""
|
86 |
+
alledges = set(edges) | {(v, u, k) for (u, v, k) in edges}
|
87 |
+
return lambda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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for undirected graphs.
|
2 |
+
|
3 |
+
The Graph class allows any hashable object as a node
|
4 |
+
and can associate key/value attribute pairs with each undirected edge.
|
5 |
+
|
6 |
+
Self-loops are allowed but multiple edges are not (see MultiGraph).
|
7 |
+
|
8 |
+
For directed graphs see DiGraph and MultiDiGraph.
|
9 |
+
"""
|
10 |
+
from copy import deepcopy
|
11 |
+
from functools import cached_property
|
12 |
+
|
13 |
+
import networkx as nx
|
14 |
+
from networkx import convert
|
15 |
+
from networkx.classes.coreviews import AdjacencyView
|
16 |
+
from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
|
17 |
+
from networkx.exception import NetworkXError
|
18 |
+
|
19 |
+
__all__ = ["Graph"]
|
20 |
+
|
21 |
+
|
22 |
+
class _CachedPropertyResetterAdj:
|
23 |
+
"""Data Descriptor class for _adj that resets ``adj`` cached_property when needed
|
24 |
+
|
25 |
+
This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
|
26 |
+
``G._adj`` is set to a new value.
|
27 |
+
|
28 |
+
This object sits on a class and ensures that any instance of that
|
29 |
+
class clears its cached property "adj" whenever the underlying
|
30 |
+
instance attribute "_adj" is set to a new object. It only affects
|
31 |
+
the set process of the obj._adj attribute. All get/del operations
|
32 |
+
act as they normally would.
|
33 |
+
|
34 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __set__(self, obj, value):
|
38 |
+
od = obj.__dict__
|
39 |
+
od["_adj"] = value
|
40 |
+
if "adj" in od:
|
41 |
+
del od["adj"]
|
42 |
+
|
43 |
+
|
44 |
+
class _CachedPropertyResetterNode:
|
45 |
+
"""Data Descriptor class for _node that resets ``nodes`` cached_property when needed
|
46 |
+
|
47 |
+
This assumes that the ``cached_property`` ``G.node`` should be reset whenever
|
48 |
+
``G._node`` is set to a new value.
|
49 |
+
|
50 |
+
This object sits on a class and ensures that any instance of that
|
51 |
+
class clears its cached property "nodes" whenever the underlying
|
52 |
+
instance attribute "_node" is set to a new object. It only affects
|
53 |
+
the set process of the obj._adj attribute. All get/del operations
|
54 |
+
act as they normally would.
|
55 |
+
|
56 |
+
For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
|
57 |
+
"""
|
58 |
+
|
59 |
+
def __set__(self, obj, value):
|
60 |
+
od = obj.__dict__
|
61 |
+
od["_node"] = value
|
62 |
+
if "nodes" in od:
|
63 |
+
del od["nodes"]
|
64 |
+
|
65 |
+
|
66 |
+
class Graph:
|
67 |
+
"""
|
68 |
+
Base class for undirected graphs.
|
69 |
+
|
70 |
+
A Graph stores nodes and edges with optional data, or attributes.
|
71 |
+
|
72 |
+
Graphs hold undirected edges. Self loops are allowed but multiple
|
73 |
+
(parallel) edges are not.
|
74 |
+
|
75 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
76 |
+
key/value attributes, except that `None` is not allowed as a node.
|
77 |
+
|
78 |
+
Edges are represented as links between nodes with optional
|
79 |
+
key/value attributes.
|
80 |
+
|
81 |
+
Parameters
|
82 |
+
----------
|
83 |
+
incoming_graph_data : input graph (optional, default: None)
|
84 |
+
Data to initialize graph. If None (default) an empty
|
85 |
+
graph is created. The data can be any format that is supported
|
86 |
+
by the to_networkx_graph() function, currently including edge list,
|
87 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
|
88 |
+
sparse matrix, or PyGraphviz graph.
|
89 |
+
|
90 |
+
attr : keyword arguments, optional (default= no attributes)
|
91 |
+
Attributes to add to graph as key=value pairs.
|
92 |
+
|
93 |
+
See Also
|
94 |
+
--------
|
95 |
+
DiGraph
|
96 |
+
MultiGraph
|
97 |
+
MultiDiGraph
|
98 |
+
|
99 |
+
Examples
|
100 |
+
--------
|
101 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
102 |
+
no edges.
|
103 |
+
|
104 |
+
>>> G = nx.Graph()
|
105 |
+
|
106 |
+
G can be grown in several ways.
|
107 |
+
|
108 |
+
**Nodes:**
|
109 |
+
|
110 |
+
Add one node at a time:
|
111 |
+
|
112 |
+
>>> G.add_node(1)
|
113 |
+
|
114 |
+
Add the nodes from any container (a list, dict, set or
|
115 |
+
even the lines from a file or the nodes from another graph).
|
116 |
+
|
117 |
+
>>> G.add_nodes_from([2, 3])
|
118 |
+
>>> G.add_nodes_from(range(100, 110))
|
119 |
+
>>> H = nx.path_graph(10)
|
120 |
+
>>> G.add_nodes_from(H)
|
121 |
+
|
122 |
+
In addition to strings and integers any hashable Python object
|
123 |
+
(except None) can represent a node, e.g. a customized node object,
|
124 |
+
or even another Graph.
|
125 |
+
|
126 |
+
>>> G.add_node(H)
|
127 |
+
|
128 |
+
**Edges:**
|
129 |
+
|
130 |
+
G can also be grown by adding edges.
|
131 |
+
|
132 |
+
Add one edge,
|
133 |
+
|
134 |
+
>>> G.add_edge(1, 2)
|
135 |
+
|
136 |
+
a list of edges,
|
137 |
+
|
138 |
+
>>> G.add_edges_from([(1, 2), (1, 3)])
|
139 |
+
|
140 |
+
or a collection of edges,
|
141 |
+
|
142 |
+
>>> G.add_edges_from(H.edges)
|
143 |
+
|
144 |
+
If some edges connect nodes not yet in the graph, the nodes
|
145 |
+
are added automatically. There are no errors when adding
|
146 |
+
nodes or edges that already exist.
|
147 |
+
|
148 |
+
**Attributes:**
|
149 |
+
|
150 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
151 |
+
in an associated attribute dictionary (the keys must be hashable).
|
152 |
+
By default these are empty, but can be added or changed using
|
153 |
+
add_edge, add_node or direct manipulation of the attribute
|
154 |
+
dictionaries named graph, node and edge respectively.
|
155 |
+
|
156 |
+
>>> G = nx.Graph(day="Friday")
|
157 |
+
>>> G.graph
|
158 |
+
{'day': 'Friday'}
|
159 |
+
|
160 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
161 |
+
|
162 |
+
>>> G.add_node(1, time="5pm")
|
163 |
+
>>> G.add_nodes_from([3], time="2pm")
|
164 |
+
>>> G.nodes[1]
|
165 |
+
{'time': '5pm'}
|
166 |
+
>>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes
|
167 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
168 |
+
>>> list(G.nodes(data=True))
|
169 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
170 |
+
|
171 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
172 |
+
notation, or G.edges.
|
173 |
+
|
174 |
+
>>> G.add_edge(1, 2, weight=4.7)
|
175 |
+
>>> G.add_edges_from([(3, 4), (4, 5)], color="red")
|
176 |
+
>>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
177 |
+
>>> G[1][2]["weight"] = 4.7
|
178 |
+
>>> G.edges[1, 2]["weight"] = 4
|
179 |
+
|
180 |
+
Warning: we protect the graph data structure by making `G.edges` a
|
181 |
+
read-only dict-like structure. However, you can assign to attributes
|
182 |
+
in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
|
183 |
+
data attributes: `G.edges[1, 2]['weight'] = 4`
|
184 |
+
(For multigraphs: `MG.edges[u, v, key][name] = value`).
|
185 |
+
|
186 |
+
**Shortcuts:**
|
187 |
+
|
188 |
+
Many common graph features allow python syntax to speed reporting.
|
189 |
+
|
190 |
+
>>> 1 in G # check if node in graph
|
191 |
+
True
|
192 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
193 |
+
[1, 2]
|
194 |
+
>>> len(G) # number of nodes in graph
|
195 |
+
5
|
196 |
+
|
197 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
198 |
+
The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
|
199 |
+
|
200 |
+
>>> for n, nbrsdict in G.adjacency():
|
201 |
+
... for nbr, eattr in nbrsdict.items():
|
202 |
+
... if "weight" in eattr:
|
203 |
+
... # Do something useful with the edges
|
204 |
+
... pass
|
205 |
+
|
206 |
+
But the edges() method is often more convenient:
|
207 |
+
|
208 |
+
>>> for u, v, weight in G.edges.data("weight"):
|
209 |
+
... if weight is not None:
|
210 |
+
... # Do something useful with the edges
|
211 |
+
... pass
|
212 |
+
|
213 |
+
**Reporting:**
|
214 |
+
|
215 |
+
Simple graph information is obtained using object-attributes and methods.
|
216 |
+
Reporting typically provides views instead of containers to reduce memory
|
217 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
218 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
219 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
|
220 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
221 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
222 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
223 |
+
|
224 |
+
For details on these and other miscellaneous methods, see below.
|
225 |
+
|
226 |
+
**Subclasses (Advanced):**
|
227 |
+
|
228 |
+
The Graph class uses a dict-of-dict-of-dict data structure.
|
229 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
230 |
+
The next dict (adjlist_dict) represents the adjacency information and holds
|
231 |
+
edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
|
232 |
+
the edge data and holds edge attribute values keyed by attribute names.
|
233 |
+
|
234 |
+
Each of these three dicts can be replaced in a subclass by a user defined
|
235 |
+
dict-like object. In general, the dict-like features should be
|
236 |
+
maintained but extra features can be added. To replace one of the
|
237 |
+
dicts create a new graph class by changing the class(!) variable
|
238 |
+
holding the factory for that dict-like structure.
|
239 |
+
|
240 |
+
node_dict_factory : function, (default: dict)
|
241 |
+
Factory function to be used to create the dict containing node
|
242 |
+
attributes, keyed by node id.
|
243 |
+
It should require no arguments and return a dict-like object
|
244 |
+
|
245 |
+
node_attr_dict_factory: function, (default: dict)
|
246 |
+
Factory function to be used to create the node attribute
|
247 |
+
dict which holds attribute values keyed by attribute name.
|
248 |
+
It should require no arguments and return a dict-like object
|
249 |
+
|
250 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
251 |
+
Factory function to be used to create the outer-most dict
|
252 |
+
in the data structure that holds adjacency info keyed by node.
|
253 |
+
It should require no arguments and return a dict-like object.
|
254 |
+
|
255 |
+
adjlist_inner_dict_factory : function, (default: dict)
|
256 |
+
Factory function to be used to create the adjacency list
|
257 |
+
dict which holds edge data keyed by neighbor.
|
258 |
+
It should require no arguments and return a dict-like object
|
259 |
+
|
260 |
+
edge_attr_dict_factory : function, (default: dict)
|
261 |
+
Factory function to be used to create the edge attribute
|
262 |
+
dict which holds attribute values keyed by attribute name.
|
263 |
+
It should require no arguments and return a dict-like object.
|
264 |
+
|
265 |
+
graph_attr_dict_factory : function, (default: dict)
|
266 |
+
Factory function to be used to create the graph attribute
|
267 |
+
dict which holds attribute values keyed by attribute name.
|
268 |
+
It should require no arguments and return a dict-like object.
|
269 |
+
|
270 |
+
Typically, if your extension doesn't impact the data structure all
|
271 |
+
methods will inherit without issue except: `to_directed/to_undirected`.
|
272 |
+
By default these methods create a DiGraph/Graph class and you probably
|
273 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
274 |
+
this we define two class variables that you can set in your subclass.
|
275 |
+
|
276 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
277 |
+
Class to create a new graph structure in the `to_directed` method.
|
278 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
279 |
+
|
280 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
281 |
+
Class to create a new graph structure in the `to_undirected` method.
|
282 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
283 |
+
|
284 |
+
**Subclassing Example**
|
285 |
+
|
286 |
+
Create a low memory graph class that effectively disallows edge
|
287 |
+
attributes by using a single attribute dict for all edges.
|
288 |
+
This reduces the memory used, but you lose edge attributes.
|
289 |
+
|
290 |
+
>>> class ThinGraph(nx.Graph):
|
291 |
+
... all_edge_dict = {"weight": 1}
|
292 |
+
...
|
293 |
+
... def single_edge_dict(self):
|
294 |
+
... return self.all_edge_dict
|
295 |
+
...
|
296 |
+
... edge_attr_dict_factory = single_edge_dict
|
297 |
+
>>> G = ThinGraph()
|
298 |
+
>>> G.add_edge(2, 1)
|
299 |
+
>>> G[2][1]
|
300 |
+
{'weight': 1}
|
301 |
+
>>> G.add_edge(2, 2)
|
302 |
+
>>> G[2][1] is G[2][2]
|
303 |
+
True
|
304 |
+
"""
|
305 |
+
|
306 |
+
_adj = _CachedPropertyResetterAdj()
|
307 |
+
_node = _CachedPropertyResetterNode()
|
308 |
+
|
309 |
+
node_dict_factory = dict
|
310 |
+
node_attr_dict_factory = dict
|
311 |
+
adjlist_outer_dict_factory = dict
|
312 |
+
adjlist_inner_dict_factory = dict
|
313 |
+
edge_attr_dict_factory = dict
|
314 |
+
graph_attr_dict_factory = dict
|
315 |
+
|
316 |
+
def to_directed_class(self):
|
317 |
+
"""Returns the class to use for empty directed copies.
|
318 |
+
|
319 |
+
If you subclass the base classes, use this to designate
|
320 |
+
what directed class to use for `to_directed()` copies.
|
321 |
+
"""
|
322 |
+
return nx.DiGraph
|
323 |
+
|
324 |
+
def to_undirected_class(self):
|
325 |
+
"""Returns the class to use for empty undirected copies.
|
326 |
+
|
327 |
+
If you subclass the base classes, use this to designate
|
328 |
+
what directed class to use for `to_directed()` copies.
|
329 |
+
"""
|
330 |
+
return Graph
|
331 |
+
|
332 |
+
def __init__(self, incoming_graph_data=None, **attr):
|
333 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
334 |
+
|
335 |
+
Parameters
|
336 |
+
----------
|
337 |
+
incoming_graph_data : input graph (optional, default: None)
|
338 |
+
Data to initialize graph. If None (default) an empty
|
339 |
+
graph is created. The data can be an edge list, or any
|
340 |
+
NetworkX graph object. If the corresponding optional Python
|
341 |
+
packages are installed the data can also be a 2D NumPy array, a
|
342 |
+
SciPy sparse array, or a PyGraphviz graph.
|
343 |
+
|
344 |
+
attr : keyword arguments, optional (default= no attributes)
|
345 |
+
Attributes to add to graph as key=value pairs.
|
346 |
+
|
347 |
+
See Also
|
348 |
+
--------
|
349 |
+
convert
|
350 |
+
|
351 |
+
Examples
|
352 |
+
--------
|
353 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
354 |
+
>>> G = nx.Graph(name="my graph")
|
355 |
+
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
|
356 |
+
>>> G = nx.Graph(e)
|
357 |
+
|
358 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
359 |
+
|
360 |
+
>>> G = nx.Graph(e, day="Friday")
|
361 |
+
>>> G.graph
|
362 |
+
{'day': 'Friday'}
|
363 |
+
|
364 |
+
"""
|
365 |
+
self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
|
366 |
+
self._node = self.node_dict_factory() # empty node attribute dict
|
367 |
+
self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict
|
368 |
+
self.__networkx_cache__ = {}
|
369 |
+
# attempt to load graph with data
|
370 |
+
if incoming_graph_data is not None:
|
371 |
+
convert.to_networkx_graph(incoming_graph_data, create_using=self)
|
372 |
+
# load graph attributes (must be after convert)
|
373 |
+
self.graph.update(attr)
|
374 |
+
|
375 |
+
@cached_property
|
376 |
+
def adj(self):
|
377 |
+
"""Graph adjacency object holding the neighbors of each node.
|
378 |
+
|
379 |
+
This object is a read-only dict-like structure with node keys
|
380 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
381 |
+
to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
|
382 |
+
the color of the edge `(3, 2)` to `"blue"`.
|
383 |
+
|
384 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
385 |
+
`for nbr, datadict in G.adj[n].items():`.
|
386 |
+
|
387 |
+
The neighbor information is also provided by subscripting the graph.
|
388 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
389 |
+
|
390 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
391 |
+
"""
|
392 |
+
return AdjacencyView(self._adj)
|
393 |
+
|
394 |
+
@property
|
395 |
+
def name(self):
|
396 |
+
"""String identifier of the graph.
|
397 |
+
|
398 |
+
This graph attribute appears in the attribute dict G.graph
|
399 |
+
keyed by the string `"name"`. as well as an attribute (technically
|
400 |
+
a property) `G.name`. This is entirely user controlled.
|
401 |
+
"""
|
402 |
+
return self.graph.get("name", "")
|
403 |
+
|
404 |
+
@name.setter
|
405 |
+
def name(self, s):
|
406 |
+
self.graph["name"] = s
|
407 |
+
nx._clear_cache(self)
|
408 |
+
|
409 |
+
def __str__(self):
|
410 |
+
"""Returns a short summary of the graph.
|
411 |
+
|
412 |
+
Returns
|
413 |
+
-------
|
414 |
+
info : string
|
415 |
+
Graph information including the graph name (if any), graph type, and the
|
416 |
+
number of nodes and edges.
|
417 |
+
|
418 |
+
Examples
|
419 |
+
--------
|
420 |
+
>>> G = nx.Graph(name="foo")
|
421 |
+
>>> str(G)
|
422 |
+
"Graph named 'foo' with 0 nodes and 0 edges"
|
423 |
+
|
424 |
+
>>> G = nx.path_graph(3)
|
425 |
+
>>> str(G)
|
426 |
+
'Graph with 3 nodes and 2 edges'
|
427 |
+
|
428 |
+
"""
|
429 |
+
return "".join(
|
430 |
+
[
|
431 |
+
type(self).__name__,
|
432 |
+
f" named {self.name!r}" if self.name else "",
|
433 |
+
f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
|
434 |
+
]
|
435 |
+
)
|
436 |
+
|
437 |
+
def __iter__(self):
|
438 |
+
"""Iterate over the nodes. Use: 'for n in G'.
|
439 |
+
|
440 |
+
Returns
|
441 |
+
-------
|
442 |
+
niter : iterator
|
443 |
+
An iterator over all nodes in the graph.
|
444 |
+
|
445 |
+
Examples
|
446 |
+
--------
|
447 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
448 |
+
>>> [n for n in G]
|
449 |
+
[0, 1, 2, 3]
|
450 |
+
>>> list(G)
|
451 |
+
[0, 1, 2, 3]
|
452 |
+
"""
|
453 |
+
return iter(self._node)
|
454 |
+
|
455 |
+
def __contains__(self, n):
|
456 |
+
"""Returns True if n is a node, False otherwise. Use: 'n in G'.
|
457 |
+
|
458 |
+
Examples
|
459 |
+
--------
|
460 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
461 |
+
>>> 1 in G
|
462 |
+
True
|
463 |
+
"""
|
464 |
+
try:
|
465 |
+
return n in self._node
|
466 |
+
except TypeError:
|
467 |
+
return False
|
468 |
+
|
469 |
+
def __len__(self):
|
470 |
+
"""Returns the number of nodes in the graph. Use: 'len(G)'.
|
471 |
+
|
472 |
+
Returns
|
473 |
+
-------
|
474 |
+
nnodes : int
|
475 |
+
The number of nodes in the graph.
|
476 |
+
|
477 |
+
See Also
|
478 |
+
--------
|
479 |
+
number_of_nodes: identical method
|
480 |
+
order: identical method
|
481 |
+
|
482 |
+
Examples
|
483 |
+
--------
|
484 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
485 |
+
>>> len(G)
|
486 |
+
4
|
487 |
+
|
488 |
+
"""
|
489 |
+
return len(self._node)
|
490 |
+
|
491 |
+
def __getitem__(self, n):
|
492 |
+
"""Returns a dict of neighbors of node n. Use: 'G[n]'.
|
493 |
+
|
494 |
+
Parameters
|
495 |
+
----------
|
496 |
+
n : node
|
497 |
+
A node in the graph.
|
498 |
+
|
499 |
+
Returns
|
500 |
+
-------
|
501 |
+
adj_dict : dictionary
|
502 |
+
The adjacency dictionary for nodes connected to n.
|
503 |
+
|
504 |
+
Notes
|
505 |
+
-----
|
506 |
+
G[n] is the same as G.adj[n] and similar to G.neighbors(n)
|
507 |
+
(which is an iterator over G.adj[n])
|
508 |
+
|
509 |
+
Examples
|
510 |
+
--------
|
511 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
512 |
+
>>> G[0]
|
513 |
+
AtlasView({1: {}})
|
514 |
+
"""
|
515 |
+
return self.adj[n]
|
516 |
+
|
517 |
+
def add_node(self, node_for_adding, **attr):
|
518 |
+
"""Add a single node `node_for_adding` and update node attributes.
|
519 |
+
|
520 |
+
Parameters
|
521 |
+
----------
|
522 |
+
node_for_adding : node
|
523 |
+
A node can be any hashable Python object except None.
|
524 |
+
attr : keyword arguments, optional
|
525 |
+
Set or change node attributes using key=value.
|
526 |
+
|
527 |
+
See Also
|
528 |
+
--------
|
529 |
+
add_nodes_from
|
530 |
+
|
531 |
+
Examples
|
532 |
+
--------
|
533 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
534 |
+
>>> G.add_node(1)
|
535 |
+
>>> G.add_node("Hello")
|
536 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
537 |
+
>>> G.add_node(K3)
|
538 |
+
>>> G.number_of_nodes()
|
539 |
+
3
|
540 |
+
|
541 |
+
Use keywords set/change node attributes:
|
542 |
+
|
543 |
+
>>> G.add_node(1, size=10)
|
544 |
+
>>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
|
545 |
+
|
546 |
+
Notes
|
547 |
+
-----
|
548 |
+
A hashable object is one that can be used as a key in a Python
|
549 |
+
dictionary. This includes strings, numbers, tuples of strings
|
550 |
+
and numbers, etc.
|
551 |
+
|
552 |
+
On many platforms hashable items also include mutables such as
|
553 |
+
NetworkX Graphs, though one should be careful that the hash
|
554 |
+
doesn't change on mutables.
|
555 |
+
"""
|
556 |
+
if node_for_adding not in self._node:
|
557 |
+
if node_for_adding is None:
|
558 |
+
raise ValueError("None cannot be a node")
|
559 |
+
self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
|
560 |
+
attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
|
561 |
+
attr_dict.update(attr)
|
562 |
+
else: # update attr even if node already exists
|
563 |
+
self._node[node_for_adding].update(attr)
|
564 |
+
nx._clear_cache(self)
|
565 |
+
|
566 |
+
def add_nodes_from(self, nodes_for_adding, **attr):
|
567 |
+
"""Add multiple nodes.
|
568 |
+
|
569 |
+
Parameters
|
570 |
+
----------
|
571 |
+
nodes_for_adding : iterable container
|
572 |
+
A container of nodes (list, dict, set, etc.).
|
573 |
+
OR
|
574 |
+
A container of (node, attribute dict) tuples.
|
575 |
+
Node attributes are updated using the attribute dict.
|
576 |
+
attr : keyword arguments, optional (default= no attributes)
|
577 |
+
Update attributes for all nodes in nodes.
|
578 |
+
Node attributes specified in nodes as a tuple take
|
579 |
+
precedence over attributes specified via keyword arguments.
|
580 |
+
|
581 |
+
See Also
|
582 |
+
--------
|
583 |
+
add_node
|
584 |
+
|
585 |
+
Notes
|
586 |
+
-----
|
587 |
+
When adding nodes from an iterator over the graph you are changing,
|
588 |
+
a `RuntimeError` can be raised with message:
|
589 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
590 |
+
happens when the graph's underlying dictionary is modified during
|
591 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
592 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
593 |
+
object to `G.add_nodes_from`.
|
594 |
+
|
595 |
+
Examples
|
596 |
+
--------
|
597 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
598 |
+
>>> G.add_nodes_from("Hello")
|
599 |
+
>>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
|
600 |
+
>>> G.add_nodes_from(K3)
|
601 |
+
>>> sorted(G.nodes(), key=str)
|
602 |
+
[0, 1, 2, 'H', 'e', 'l', 'o']
|
603 |
+
|
604 |
+
Use keywords to update specific node attributes for every node.
|
605 |
+
|
606 |
+
>>> G.add_nodes_from([1, 2], size=10)
|
607 |
+
>>> G.add_nodes_from([3, 4], weight=0.4)
|
608 |
+
|
609 |
+
Use (node, attrdict) tuples to update attributes for specific nodes.
|
610 |
+
|
611 |
+
>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
|
612 |
+
>>> G.nodes[1]["size"]
|
613 |
+
11
|
614 |
+
>>> H = nx.Graph()
|
615 |
+
>>> H.add_nodes_from(G.nodes(data=True))
|
616 |
+
>>> H.nodes[1]["size"]
|
617 |
+
11
|
618 |
+
|
619 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
620 |
+
|
621 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
|
622 |
+
>>> # wrong way - will raise RuntimeError
|
623 |
+
>>> # G.add_nodes_from(n + 1 for n in G.nodes)
|
624 |
+
>>> # correct way
|
625 |
+
>>> G.add_nodes_from(list(n + 1 for n in G.nodes))
|
626 |
+
"""
|
627 |
+
for n in nodes_for_adding:
|
628 |
+
try:
|
629 |
+
newnode = n not in self._node
|
630 |
+
newdict = attr
|
631 |
+
except TypeError:
|
632 |
+
n, ndict = n
|
633 |
+
newnode = n not in self._node
|
634 |
+
newdict = attr.copy()
|
635 |
+
newdict.update(ndict)
|
636 |
+
if newnode:
|
637 |
+
if n is None:
|
638 |
+
raise ValueError("None cannot be a node")
|
639 |
+
self._adj[n] = self.adjlist_inner_dict_factory()
|
640 |
+
self._node[n] = self.node_attr_dict_factory()
|
641 |
+
self._node[n].update(newdict)
|
642 |
+
nx._clear_cache(self)
|
643 |
+
|
644 |
+
def remove_node(self, n):
|
645 |
+
"""Remove node n.
|
646 |
+
|
647 |
+
Removes the node n and all adjacent edges.
|
648 |
+
Attempting to remove a nonexistent node will raise an exception.
|
649 |
+
|
650 |
+
Parameters
|
651 |
+
----------
|
652 |
+
n : node
|
653 |
+
A node in the graph
|
654 |
+
|
655 |
+
Raises
|
656 |
+
------
|
657 |
+
NetworkXError
|
658 |
+
If n is not in the graph.
|
659 |
+
|
660 |
+
See Also
|
661 |
+
--------
|
662 |
+
remove_nodes_from
|
663 |
+
|
664 |
+
Examples
|
665 |
+
--------
|
666 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
667 |
+
>>> list(G.edges)
|
668 |
+
[(0, 1), (1, 2)]
|
669 |
+
>>> G.remove_node(1)
|
670 |
+
>>> list(G.edges)
|
671 |
+
[]
|
672 |
+
|
673 |
+
"""
|
674 |
+
adj = self._adj
|
675 |
+
try:
|
676 |
+
nbrs = list(adj[n]) # list handles self-loops (allows mutation)
|
677 |
+
del self._node[n]
|
678 |
+
except KeyError as err: # NetworkXError if n not in self
|
679 |
+
raise NetworkXError(f"The node {n} is not in the graph.") from err
|
680 |
+
for u in nbrs:
|
681 |
+
del adj[u][n] # remove all edges n-u in graph
|
682 |
+
del adj[n] # now remove node
|
683 |
+
nx._clear_cache(self)
|
684 |
+
|
685 |
+
def remove_nodes_from(self, nodes):
|
686 |
+
"""Remove multiple nodes.
|
687 |
+
|
688 |
+
Parameters
|
689 |
+
----------
|
690 |
+
nodes : iterable container
|
691 |
+
A container of nodes (list, dict, set, etc.). If a node
|
692 |
+
in the container is not in the graph it is silently
|
693 |
+
ignored.
|
694 |
+
|
695 |
+
See Also
|
696 |
+
--------
|
697 |
+
remove_node
|
698 |
+
|
699 |
+
Notes
|
700 |
+
-----
|
701 |
+
When removing nodes from an iterator over the graph you are changing,
|
702 |
+
a `RuntimeError` will be raised with message:
|
703 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
704 |
+
happens when the graph's underlying dictionary is modified during
|
705 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
706 |
+
object, e.g. by using `list(iterator_of_nodes)`, and pass this
|
707 |
+
object to `G.remove_nodes_from`.
|
708 |
+
|
709 |
+
Examples
|
710 |
+
--------
|
711 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
712 |
+
>>> e = list(G.nodes)
|
713 |
+
>>> e
|
714 |
+
[0, 1, 2]
|
715 |
+
>>> G.remove_nodes_from(e)
|
716 |
+
>>> list(G.nodes)
|
717 |
+
[]
|
718 |
+
|
719 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
720 |
+
|
721 |
+
>>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
|
722 |
+
>>> # this command will fail, as the graph's dict is modified during iteration
|
723 |
+
>>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
|
724 |
+
>>> # this command will work, since the dictionary underlying graph is not modified
|
725 |
+
>>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
|
726 |
+
"""
|
727 |
+
adj = self._adj
|
728 |
+
for n in nodes:
|
729 |
+
try:
|
730 |
+
del self._node[n]
|
731 |
+
for u in list(adj[n]): # list handles self-loops
|
732 |
+
del adj[u][n] # (allows mutation of dict in loop)
|
733 |
+
del adj[n]
|
734 |
+
except KeyError:
|
735 |
+
pass
|
736 |
+
nx._clear_cache(self)
|
737 |
+
|
738 |
+
@cached_property
|
739 |
+
def nodes(self):
|
740 |
+
"""A NodeView of the Graph as G.nodes or G.nodes().
|
741 |
+
|
742 |
+
Can be used as `G.nodes` for data lookup and for set-like operations.
|
743 |
+
Can also be used as `G.nodes(data='color', default=None)` to return a
|
744 |
+
NodeDataView which reports specific node data but no set operations.
|
745 |
+
It presents a dict-like interface as well with `G.nodes.items()`
|
746 |
+
iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
|
747 |
+
providing the value of the `foo` attribute for node `3`. In addition,
|
748 |
+
a view `G.nodes.data('foo')` provides a dict-like interface to the
|
749 |
+
`foo` attribute of each node. `G.nodes.data('foo', default=1)`
|
750 |
+
provides a default for nodes that do not have attribute `foo`.
|
751 |
+
|
752 |
+
Parameters
|
753 |
+
----------
|
754 |
+
data : string or bool, optional (default=False)
|
755 |
+
The node attribute returned in 2-tuple (n, ddict[data]).
|
756 |
+
If True, return entire node attribute dict as (n, ddict).
|
757 |
+
If False, return just the nodes n.
|
758 |
+
|
759 |
+
default : value, optional (default=None)
|
760 |
+
Value used for nodes that don't have the requested attribute.
|
761 |
+
Only relevant if data is not True or False.
|
762 |
+
|
763 |
+
Returns
|
764 |
+
-------
|
765 |
+
NodeView
|
766 |
+
Allows set-like operations over the nodes as well as node
|
767 |
+
attribute dict lookup and calling to get a NodeDataView.
|
768 |
+
A NodeDataView iterates over `(n, data)` and has no set operations.
|
769 |
+
A NodeView iterates over `n` and includes set operations.
|
770 |
+
|
771 |
+
When called, if data is False, an iterator over nodes.
|
772 |
+
Otherwise an iterator of 2-tuples (node, attribute value)
|
773 |
+
where the attribute is specified in `data`.
|
774 |
+
If data is True then the attribute becomes the
|
775 |
+
entire data dictionary.
|
776 |
+
|
777 |
+
Notes
|
778 |
+
-----
|
779 |
+
If your node data is not needed, it is simpler and equivalent
|
780 |
+
to use the expression ``for n in G``, or ``list(G)``.
|
781 |
+
|
782 |
+
Examples
|
783 |
+
--------
|
784 |
+
There are two simple ways of getting a list of all nodes in the graph:
|
785 |
+
|
786 |
+
>>> G = nx.path_graph(3)
|
787 |
+
>>> list(G.nodes)
|
788 |
+
[0, 1, 2]
|
789 |
+
>>> list(G)
|
790 |
+
[0, 1, 2]
|
791 |
+
|
792 |
+
To get the node data along with the nodes:
|
793 |
+
|
794 |
+
>>> G.add_node(1, time="5pm")
|
795 |
+
>>> G.nodes[0]["foo"] = "bar"
|
796 |
+
>>> list(G.nodes(data=True))
|
797 |
+
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
|
798 |
+
>>> list(G.nodes.data())
|
799 |
+
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
|
800 |
+
|
801 |
+
>>> list(G.nodes(data="foo"))
|
802 |
+
[(0, 'bar'), (1, None), (2, None)]
|
803 |
+
>>> list(G.nodes.data("foo"))
|
804 |
+
[(0, 'bar'), (1, None), (2, None)]
|
805 |
+
|
806 |
+
>>> list(G.nodes(data="time"))
|
807 |
+
[(0, None), (1, '5pm'), (2, None)]
|
808 |
+
>>> list(G.nodes.data("time"))
|
809 |
+
[(0, None), (1, '5pm'), (2, None)]
|
810 |
+
|
811 |
+
>>> list(G.nodes(data="time", default="Not Available"))
|
812 |
+
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
|
813 |
+
>>> list(G.nodes.data("time", default="Not Available"))
|
814 |
+
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
|
815 |
+
|
816 |
+
If some of your nodes have an attribute and the rest are assumed
|
817 |
+
to have a default attribute value you can create a dictionary
|
818 |
+
from node/attribute pairs using the `default` keyword argument
|
819 |
+
to guarantee the value is never None::
|
820 |
+
|
821 |
+
>>> G = nx.Graph()
|
822 |
+
>>> G.add_node(0)
|
823 |
+
>>> G.add_node(1, weight=2)
|
824 |
+
>>> G.add_node(2, weight=3)
|
825 |
+
>>> dict(G.nodes(data="weight", default=1))
|
826 |
+
{0: 1, 1: 2, 2: 3}
|
827 |
+
|
828 |
+
"""
|
829 |
+
return NodeView(self)
|
830 |
+
|
831 |
+
def number_of_nodes(self):
|
832 |
+
"""Returns the number of nodes in the graph.
|
833 |
+
|
834 |
+
Returns
|
835 |
+
-------
|
836 |
+
nnodes : int
|
837 |
+
The number of nodes in the graph.
|
838 |
+
|
839 |
+
See Also
|
840 |
+
--------
|
841 |
+
order: identical method
|
842 |
+
__len__: identical method
|
843 |
+
|
844 |
+
Examples
|
845 |
+
--------
|
846 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
847 |
+
>>> G.number_of_nodes()
|
848 |
+
3
|
849 |
+
"""
|
850 |
+
return len(self._node)
|
851 |
+
|
852 |
+
def order(self):
|
853 |
+
"""Returns the number of nodes in the graph.
|
854 |
+
|
855 |
+
Returns
|
856 |
+
-------
|
857 |
+
nnodes : int
|
858 |
+
The number of nodes in the graph.
|
859 |
+
|
860 |
+
See Also
|
861 |
+
--------
|
862 |
+
number_of_nodes: identical method
|
863 |
+
__len__: identical method
|
864 |
+
|
865 |
+
Examples
|
866 |
+
--------
|
867 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
868 |
+
>>> G.order()
|
869 |
+
3
|
870 |
+
"""
|
871 |
+
return len(self._node)
|
872 |
+
|
873 |
+
def has_node(self, n):
|
874 |
+
"""Returns True if the graph contains the node n.
|
875 |
+
|
876 |
+
Identical to `n in G`
|
877 |
+
|
878 |
+
Parameters
|
879 |
+
----------
|
880 |
+
n : node
|
881 |
+
|
882 |
+
Examples
|
883 |
+
--------
|
884 |
+
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
885 |
+
>>> G.has_node(0)
|
886 |
+
True
|
887 |
+
|
888 |
+
It is more readable and simpler to use
|
889 |
+
|
890 |
+
>>> 0 in G
|
891 |
+
True
|
892 |
+
|
893 |
+
"""
|
894 |
+
try:
|
895 |
+
return n in self._node
|
896 |
+
except TypeError:
|
897 |
+
return False
|
898 |
+
|
899 |
+
def add_edge(self, u_of_edge, v_of_edge, **attr):
|
900 |
+
"""Add an edge between u and v.
|
901 |
+
|
902 |
+
The nodes u and v will be automatically added if they are
|
903 |
+
not already in the graph.
|
904 |
+
|
905 |
+
Edge attributes can be specified with keywords or by directly
|
906 |
+
accessing the edge's attribute dictionary. See examples below.
|
907 |
+
|
908 |
+
Parameters
|
909 |
+
----------
|
910 |
+
u_of_edge, v_of_edge : nodes
|
911 |
+
Nodes can be, for example, strings or numbers.
|
912 |
+
Nodes must be hashable (and not None) Python objects.
|
913 |
+
attr : keyword arguments, optional
|
914 |
+
Edge data (or labels or objects) can be assigned using
|
915 |
+
keyword arguments.
|
916 |
+
|
917 |
+
See Also
|
918 |
+
--------
|
919 |
+
add_edges_from : add a collection of edges
|
920 |
+
|
921 |
+
Notes
|
922 |
+
-----
|
923 |
+
Adding an edge that already exists updates the edge data.
|
924 |
+
|
925 |
+
Many NetworkX algorithms designed for weighted graphs use
|
926 |
+
an edge attribute (by default `weight`) to hold a numerical value.
|
927 |
+
|
928 |
+
Examples
|
929 |
+
--------
|
930 |
+
The following all add the edge e=(1, 2) to graph G:
|
931 |
+
|
932 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
933 |
+
>>> e = (1, 2)
|
934 |
+
>>> G.add_edge(1, 2) # explicit two-node form
|
935 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
936 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
937 |
+
|
938 |
+
Associate data to edges using keywords:
|
939 |
+
|
940 |
+
>>> G.add_edge(1, 2, weight=3)
|
941 |
+
>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
942 |
+
|
943 |
+
For non-string attribute keys, use subscript notation.
|
944 |
+
|
945 |
+
>>> G.add_edge(1, 2)
|
946 |
+
>>> G[1][2].update({0: 5})
|
947 |
+
>>> G.edges[1, 2].update({0: 5})
|
948 |
+
"""
|
949 |
+
u, v = u_of_edge, v_of_edge
|
950 |
+
# add nodes
|
951 |
+
if u not in self._node:
|
952 |
+
if u is None:
|
953 |
+
raise ValueError("None cannot be a node")
|
954 |
+
self._adj[u] = self.adjlist_inner_dict_factory()
|
955 |
+
self._node[u] = self.node_attr_dict_factory()
|
956 |
+
if v not in self._node:
|
957 |
+
if v is None:
|
958 |
+
raise ValueError("None cannot be a node")
|
959 |
+
self._adj[v] = self.adjlist_inner_dict_factory()
|
960 |
+
self._node[v] = self.node_attr_dict_factory()
|
961 |
+
# add the edge
|
962 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
963 |
+
datadict.update(attr)
|
964 |
+
self._adj[u][v] = datadict
|
965 |
+
self._adj[v][u] = datadict
|
966 |
+
nx._clear_cache(self)
|
967 |
+
|
968 |
+
def add_edges_from(self, ebunch_to_add, **attr):
|
969 |
+
"""Add all the edges in ebunch_to_add.
|
970 |
+
|
971 |
+
Parameters
|
972 |
+
----------
|
973 |
+
ebunch_to_add : container of edges
|
974 |
+
Each edge given in the container will be added to the
|
975 |
+
graph. The edges must be given as 2-tuples (u, v) or
|
976 |
+
3-tuples (u, v, d) where d is a dictionary containing edge data.
|
977 |
+
attr : keyword arguments, optional
|
978 |
+
Edge data (or labels or objects) can be assigned using
|
979 |
+
keyword arguments.
|
980 |
+
|
981 |
+
See Also
|
982 |
+
--------
|
983 |
+
add_edge : add a single edge
|
984 |
+
add_weighted_edges_from : convenient way to add weighted edges
|
985 |
+
|
986 |
+
Notes
|
987 |
+
-----
|
988 |
+
Adding the same edge twice has no effect but any edge data
|
989 |
+
will be updated when each duplicate edge is added.
|
990 |
+
|
991 |
+
Edge attributes specified in an ebunch take precedence over
|
992 |
+
attributes specified via keyword arguments.
|
993 |
+
|
994 |
+
When adding edges from an iterator over the graph you are changing,
|
995 |
+
a `RuntimeError` can be raised with message:
|
996 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
997 |
+
happens when the graph's underlying dictionary is modified during
|
998 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
999 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
1000 |
+
object to `G.add_edges_from`.
|
1001 |
+
|
1002 |
+
Examples
|
1003 |
+
--------
|
1004 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1005 |
+
>>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
|
1006 |
+
>>> e = zip(range(0, 3), range(1, 4))
|
1007 |
+
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3
|
1008 |
+
|
1009 |
+
Associate data to edges
|
1010 |
+
|
1011 |
+
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
|
1012 |
+
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
|
1013 |
+
|
1014 |
+
Evaluate an iterator over a graph if using it to modify the same graph
|
1015 |
+
|
1016 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
|
1017 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
1018 |
+
>>> # wrong way - will raise RuntimeError
|
1019 |
+
>>> # G.add_edges_from(((5, n) for n in G.nodes))
|
1020 |
+
>>> # correct way - note that there will be no self-edge for node 5
|
1021 |
+
>>> G.add_edges_from(list((5, n) for n in G.nodes))
|
1022 |
+
"""
|
1023 |
+
for e in ebunch_to_add:
|
1024 |
+
ne = len(e)
|
1025 |
+
if ne == 3:
|
1026 |
+
u, v, dd = e
|
1027 |
+
elif ne == 2:
|
1028 |
+
u, v = e
|
1029 |
+
dd = {} # doesn't need edge_attr_dict_factory
|
1030 |
+
else:
|
1031 |
+
raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
|
1032 |
+
if u not in self._node:
|
1033 |
+
if u is None:
|
1034 |
+
raise ValueError("None cannot be a node")
|
1035 |
+
self._adj[u] = self.adjlist_inner_dict_factory()
|
1036 |
+
self._node[u] = self.node_attr_dict_factory()
|
1037 |
+
if v not in self._node:
|
1038 |
+
if v is None:
|
1039 |
+
raise ValueError("None cannot be a node")
|
1040 |
+
self._adj[v] = self.adjlist_inner_dict_factory()
|
1041 |
+
self._node[v] = self.node_attr_dict_factory()
|
1042 |
+
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
|
1043 |
+
datadict.update(attr)
|
1044 |
+
datadict.update(dd)
|
1045 |
+
self._adj[u][v] = datadict
|
1046 |
+
self._adj[v][u] = datadict
|
1047 |
+
nx._clear_cache(self)
|
1048 |
+
|
1049 |
+
def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
|
1050 |
+
"""Add weighted edges in `ebunch_to_add` with specified weight attr
|
1051 |
+
|
1052 |
+
Parameters
|
1053 |
+
----------
|
1054 |
+
ebunch_to_add : container of edges
|
1055 |
+
Each edge given in the list or container will be added
|
1056 |
+
to the graph. The edges must be given as 3-tuples (u, v, w)
|
1057 |
+
where w is a number.
|
1058 |
+
weight : string, optional (default= 'weight')
|
1059 |
+
The attribute name for the edge weights to be added.
|
1060 |
+
attr : keyword arguments, optional (default= no attributes)
|
1061 |
+
Edge attributes to add/update for all edges.
|
1062 |
+
|
1063 |
+
See Also
|
1064 |
+
--------
|
1065 |
+
add_edge : add a single edge
|
1066 |
+
add_edges_from : add multiple edges
|
1067 |
+
|
1068 |
+
Notes
|
1069 |
+
-----
|
1070 |
+
Adding the same edge twice for Graph/DiGraph simply updates
|
1071 |
+
the edge data. For MultiGraph/MultiDiGraph, duplicate edges
|
1072 |
+
are stored.
|
1073 |
+
|
1074 |
+
When adding edges from an iterator over the graph you are changing,
|
1075 |
+
a `RuntimeError` can be raised with message:
|
1076 |
+
`RuntimeError: dictionary changed size during iteration`. This
|
1077 |
+
happens when the graph's underlying dictionary is modified during
|
1078 |
+
iteration. To avoid this error, evaluate the iterator into a separate
|
1079 |
+
object, e.g. by using `list(iterator_of_edges)`, and pass this
|
1080 |
+
object to `G.add_weighted_edges_from`.
|
1081 |
+
|
1082 |
+
Examples
|
1083 |
+
--------
|
1084 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1085 |
+
>>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
|
1086 |
+
|
1087 |
+
Evaluate an iterator over edges before passing it
|
1088 |
+
|
1089 |
+
>>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
|
1090 |
+
>>> weight = 0.1
|
1091 |
+
>>> # Grow graph by one new node, adding edges to all existing nodes.
|
1092 |
+
>>> # wrong way - will raise RuntimeError
|
1093 |
+
>>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
|
1094 |
+
>>> # correct way - note that there will be no self-edge for node 5
|
1095 |
+
>>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
|
1096 |
+
"""
|
1097 |
+
self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
|
1098 |
+
nx._clear_cache(self)
|
1099 |
+
|
1100 |
+
def remove_edge(self, u, v):
|
1101 |
+
"""Remove the edge between u and v.
|
1102 |
+
|
1103 |
+
Parameters
|
1104 |
+
----------
|
1105 |
+
u, v : nodes
|
1106 |
+
Remove the edge between nodes u and v.
|
1107 |
+
|
1108 |
+
Raises
|
1109 |
+
------
|
1110 |
+
NetworkXError
|
1111 |
+
If there is not an edge between u and v.
|
1112 |
+
|
1113 |
+
See Also
|
1114 |
+
--------
|
1115 |
+
remove_edges_from : remove a collection of edges
|
1116 |
+
|
1117 |
+
Examples
|
1118 |
+
--------
|
1119 |
+
>>> G = nx.path_graph(4) # or DiGraph, etc
|
1120 |
+
>>> G.remove_edge(0, 1)
|
1121 |
+
>>> e = (1, 2)
|
1122 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
1123 |
+
>>> e = (2, 3, {"weight": 7}) # an edge with attribute data
|
1124 |
+
>>> G.remove_edge(*e[:2]) # select first part of edge tuple
|
1125 |
+
"""
|
1126 |
+
try:
|
1127 |
+
del self._adj[u][v]
|
1128 |
+
if u != v: # self-loop needs only one entry removed
|
1129 |
+
del self._adj[v][u]
|
1130 |
+
except KeyError as err:
|
1131 |
+
raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
|
1132 |
+
nx._clear_cache(self)
|
1133 |
+
|
1134 |
+
def remove_edges_from(self, ebunch):
|
1135 |
+
"""Remove all edges specified in ebunch.
|
1136 |
+
|
1137 |
+
Parameters
|
1138 |
+
----------
|
1139 |
+
ebunch: list or container of edge tuples
|
1140 |
+
Each edge given in the list or container will be removed
|
1141 |
+
from the graph. The edges can be:
|
1142 |
+
|
1143 |
+
- 2-tuples (u, v) edge between u and v.
|
1144 |
+
- 3-tuples (u, v, k) where k is ignored.
|
1145 |
+
|
1146 |
+
See Also
|
1147 |
+
--------
|
1148 |
+
remove_edge : remove a single edge
|
1149 |
+
|
1150 |
+
Notes
|
1151 |
+
-----
|
1152 |
+
Will fail silently if an edge in ebunch is not in the graph.
|
1153 |
+
|
1154 |
+
Examples
|
1155 |
+
--------
|
1156 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1157 |
+
>>> ebunch = [(1, 2), (2, 3)]
|
1158 |
+
>>> G.remove_edges_from(ebunch)
|
1159 |
+
"""
|
1160 |
+
adj = self._adj
|
1161 |
+
for e in ebunch:
|
1162 |
+
u, v = e[:2] # ignore edge data if present
|
1163 |
+
if u in adj and v in adj[u]:
|
1164 |
+
del adj[u][v]
|
1165 |
+
if u != v: # self loop needs only one entry removed
|
1166 |
+
del adj[v][u]
|
1167 |
+
nx._clear_cache(self)
|
1168 |
+
|
1169 |
+
def update(self, edges=None, nodes=None):
|
1170 |
+
"""Update the graph using nodes/edges/graphs as input.
|
1171 |
+
|
1172 |
+
Like dict.update, this method takes a graph as input, adding the
|
1173 |
+
graph's nodes and edges to this graph. It can also take two inputs:
|
1174 |
+
edges and nodes. Finally it can take either edges or nodes.
|
1175 |
+
To specify only nodes the keyword `nodes` must be used.
|
1176 |
+
|
1177 |
+
The collections of edges and nodes are treated similarly to
|
1178 |
+
the add_edges_from/add_nodes_from methods. When iterated, they
|
1179 |
+
should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
|
1180 |
+
|
1181 |
+
Parameters
|
1182 |
+
----------
|
1183 |
+
edges : Graph object, collection of edges, or None
|
1184 |
+
The first parameter can be a graph or some edges. If it has
|
1185 |
+
attributes `nodes` and `edges`, then it is taken to be a
|
1186 |
+
Graph-like object and those attributes are used as collections
|
1187 |
+
of nodes and edges to be added to the graph.
|
1188 |
+
If the first parameter does not have those attributes, it is
|
1189 |
+
treated as a collection of edges and added to the graph.
|
1190 |
+
If the first argument is None, no edges are added.
|
1191 |
+
nodes : collection of nodes, or None
|
1192 |
+
The second parameter is treated as a collection of nodes
|
1193 |
+
to be added to the graph unless it is None.
|
1194 |
+
If `edges is None` and `nodes is None` an exception is raised.
|
1195 |
+
If the first parameter is a Graph, then `nodes` is ignored.
|
1196 |
+
|
1197 |
+
Examples
|
1198 |
+
--------
|
1199 |
+
>>> G = nx.path_graph(5)
|
1200 |
+
>>> G.update(nx.complete_graph(range(4, 10)))
|
1201 |
+
>>> from itertools import combinations
|
1202 |
+
>>> edges = (
|
1203 |
+
... (u, v, {"power": u * v})
|
1204 |
+
... for u, v in combinations(range(10, 20), 2)
|
1205 |
+
... if u * v < 225
|
1206 |
+
... )
|
1207 |
+
>>> nodes = [1000] # for singleton, use a container
|
1208 |
+
>>> G.update(edges, nodes)
|
1209 |
+
|
1210 |
+
Notes
|
1211 |
+
-----
|
1212 |
+
It you want to update the graph using an adjacency structure
|
1213 |
+
it is straightforward to obtain the edges/nodes from adjacency.
|
1214 |
+
The following examples provide common cases, your adjacency may
|
1215 |
+
be slightly different and require tweaks of these examples::
|
1216 |
+
|
1217 |
+
>>> # dict-of-set/list/tuple
|
1218 |
+
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
|
1219 |
+
>>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
|
1220 |
+
>>> G.update(edges=e, nodes=adj)
|
1221 |
+
|
1222 |
+
>>> DG = nx.DiGraph()
|
1223 |
+
>>> # dict-of-dict-of-attribute
|
1224 |
+
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
|
1225 |
+
>>> e = [(u, v, {"weight": d}) for u, nbrs in adj.items() for v, d in nbrs.items()]
|
1226 |
+
>>> DG.update(edges=e, nodes=adj)
|
1227 |
+
|
1228 |
+
>>> # dict-of-dict-of-dict
|
1229 |
+
>>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
|
1230 |
+
>>> e = [(u, v, {"weight": d}) for u, nbrs in adj.items() for v, d in nbrs.items()]
|
1231 |
+
>>> DG.update(edges=e, nodes=adj)
|
1232 |
+
|
1233 |
+
>>> # predecessor adjacency (dict-of-set)
|
1234 |
+
>>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
|
1235 |
+
>>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
|
1236 |
+
|
1237 |
+
>>> # MultiGraph dict-of-dict-of-dict-of-attribute
|
1238 |
+
>>> MDG = nx.MultiDiGraph()
|
1239 |
+
>>> adj = {
|
1240 |
+
... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
|
1241 |
+
... 3: {2: {0: {"weight": 0.7}}},
|
1242 |
+
... }
|
1243 |
+
>>> e = [
|
1244 |
+
... (u, v, ekey, d)
|
1245 |
+
... for u, nbrs in adj.items()
|
1246 |
+
... for v, keydict in nbrs.items()
|
1247 |
+
... for ekey, d in keydict.items()
|
1248 |
+
... ]
|
1249 |
+
>>> MDG.update(edges=e)
|
1250 |
+
|
1251 |
+
See Also
|
1252 |
+
--------
|
1253 |
+
add_edges_from: add multiple edges to a graph
|
1254 |
+
add_nodes_from: add multiple nodes to a graph
|
1255 |
+
"""
|
1256 |
+
if edges is not None:
|
1257 |
+
if nodes is not None:
|
1258 |
+
self.add_nodes_from(nodes)
|
1259 |
+
self.add_edges_from(edges)
|
1260 |
+
else:
|
1261 |
+
# check if edges is a Graph object
|
1262 |
+
try:
|
1263 |
+
graph_nodes = edges.nodes
|
1264 |
+
graph_edges = edges.edges
|
1265 |
+
except AttributeError:
|
1266 |
+
# edge not Graph-like
|
1267 |
+
self.add_edges_from(edges)
|
1268 |
+
else: # edges is Graph-like
|
1269 |
+
self.add_nodes_from(graph_nodes.data())
|
1270 |
+
self.add_edges_from(graph_edges.data())
|
1271 |
+
self.graph.update(edges.graph)
|
1272 |
+
elif nodes is not None:
|
1273 |
+
self.add_nodes_from(nodes)
|
1274 |
+
else:
|
1275 |
+
raise NetworkXError("update needs nodes or edges input")
|
1276 |
+
|
1277 |
+
def has_edge(self, u, v):
|
1278 |
+
"""Returns True if the edge (u, v) is in the graph.
|
1279 |
+
|
1280 |
+
This is the same as `v in G[u]` without KeyError exceptions.
|
1281 |
+
|
1282 |
+
Parameters
|
1283 |
+
----------
|
1284 |
+
u, v : nodes
|
1285 |
+
Nodes can be, for example, strings or numbers.
|
1286 |
+
Nodes must be hashable (and not None) Python objects.
|
1287 |
+
|
1288 |
+
Returns
|
1289 |
+
-------
|
1290 |
+
edge_ind : bool
|
1291 |
+
True if edge is in the graph, False otherwise.
|
1292 |
+
|
1293 |
+
Examples
|
1294 |
+
--------
|
1295 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1296 |
+
>>> G.has_edge(0, 1) # using two nodes
|
1297 |
+
True
|
1298 |
+
>>> e = (0, 1)
|
1299 |
+
>>> G.has_edge(*e) # e is a 2-tuple (u, v)
|
1300 |
+
True
|
1301 |
+
>>> e = (0, 1, {"weight": 7})
|
1302 |
+
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
|
1303 |
+
True
|
1304 |
+
|
1305 |
+
The following syntax are equivalent:
|
1306 |
+
|
1307 |
+
>>> G.has_edge(0, 1)
|
1308 |
+
True
|
1309 |
+
>>> 1 in G[0] # though this gives KeyError if 0 not in G
|
1310 |
+
True
|
1311 |
+
|
1312 |
+
"""
|
1313 |
+
try:
|
1314 |
+
return v in self._adj[u]
|
1315 |
+
except KeyError:
|
1316 |
+
return False
|
1317 |
+
|
1318 |
+
def neighbors(self, n):
|
1319 |
+
"""Returns an iterator over all neighbors of node n.
|
1320 |
+
|
1321 |
+
This is identical to `iter(G[n])`
|
1322 |
+
|
1323 |
+
Parameters
|
1324 |
+
----------
|
1325 |
+
n : node
|
1326 |
+
A node in the graph
|
1327 |
+
|
1328 |
+
Returns
|
1329 |
+
-------
|
1330 |
+
neighbors : iterator
|
1331 |
+
An iterator over all neighbors of node n
|
1332 |
+
|
1333 |
+
Raises
|
1334 |
+
------
|
1335 |
+
NetworkXError
|
1336 |
+
If the node n is not in the graph.
|
1337 |
+
|
1338 |
+
Examples
|
1339 |
+
--------
|
1340 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1341 |
+
>>> [n for n in G.neighbors(0)]
|
1342 |
+
[1]
|
1343 |
+
|
1344 |
+
Notes
|
1345 |
+
-----
|
1346 |
+
Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
|
1347 |
+
|
1348 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1349 |
+
>>> G.add_edge("a", "b", weight=7)
|
1350 |
+
>>> G["a"]
|
1351 |
+
AtlasView({'b': {'weight': 7}})
|
1352 |
+
>>> G = nx.path_graph(4)
|
1353 |
+
>>> [n for n in G[0]]
|
1354 |
+
[1]
|
1355 |
+
"""
|
1356 |
+
try:
|
1357 |
+
return iter(self._adj[n])
|
1358 |
+
except KeyError as err:
|
1359 |
+
raise NetworkXError(f"The node {n} is not in the graph.") from err
|
1360 |
+
|
1361 |
+
@cached_property
|
1362 |
+
def edges(self):
|
1363 |
+
"""An EdgeView of the Graph as G.edges or G.edges().
|
1364 |
+
|
1365 |
+
edges(self, nbunch=None, data=False, default=None)
|
1366 |
+
|
1367 |
+
The EdgeView provides set-like operations on the edge-tuples
|
1368 |
+
as well as edge attribute lookup. When called, it also provides
|
1369 |
+
an EdgeDataView object which allows control of access to edge
|
1370 |
+
attributes (but does not provide set-like operations).
|
1371 |
+
Hence, `G.edges[u, v]['color']` provides the value of the color
|
1372 |
+
attribute for edge `(u, v)` while
|
1373 |
+
`for (u, v, c) in G.edges.data('color', default='red'):`
|
1374 |
+
iterates through all the edges yielding the color attribute
|
1375 |
+
with default `'red'` if no color attribute exists.
|
1376 |
+
|
1377 |
+
Parameters
|
1378 |
+
----------
|
1379 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1380 |
+
The view will only report edges from these nodes.
|
1381 |
+
data : string or bool, optional (default=False)
|
1382 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
1383 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
1384 |
+
If False, return 2-tuple (u, v).
|
1385 |
+
default : value, optional (default=None)
|
1386 |
+
Value used for edges that don't have the requested attribute.
|
1387 |
+
Only relevant if data is not True or False.
|
1388 |
+
|
1389 |
+
Returns
|
1390 |
+
-------
|
1391 |
+
edges : EdgeView
|
1392 |
+
A view of edge attributes, usually it iterates over (u, v)
|
1393 |
+
or (u, v, d) tuples of edges, but can also be used for
|
1394 |
+
attribute lookup as `edges[u, v]['foo']`.
|
1395 |
+
|
1396 |
+
Notes
|
1397 |
+
-----
|
1398 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
1399 |
+
For directed graphs this returns the out-edges.
|
1400 |
+
|
1401 |
+
Examples
|
1402 |
+
--------
|
1403 |
+
>>> G = nx.path_graph(3) # or MultiGraph, etc
|
1404 |
+
>>> G.add_edge(2, 3, weight=5)
|
1405 |
+
>>> [e for e in G.edges]
|
1406 |
+
[(0, 1), (1, 2), (2, 3)]
|
1407 |
+
>>> G.edges.data() # default data is {} (empty dict)
|
1408 |
+
EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
|
1409 |
+
>>> G.edges.data("weight", default=1)
|
1410 |
+
EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
|
1411 |
+
>>> G.edges([0, 3]) # only edges from these nodes
|
1412 |
+
EdgeDataView([(0, 1), (3, 2)])
|
1413 |
+
>>> G.edges(0) # only edges from node 0
|
1414 |
+
EdgeDataView([(0, 1)])
|
1415 |
+
"""
|
1416 |
+
return EdgeView(self)
|
1417 |
+
|
1418 |
+
def get_edge_data(self, u, v, default=None):
|
1419 |
+
"""Returns the attribute dictionary associated with edge (u, v).
|
1420 |
+
|
1421 |
+
This is identical to `G[u][v]` except the default is returned
|
1422 |
+
instead of an exception if the edge doesn't exist.
|
1423 |
+
|
1424 |
+
Parameters
|
1425 |
+
----------
|
1426 |
+
u, v : nodes
|
1427 |
+
default: any Python object (default=None)
|
1428 |
+
Value to return if the edge (u, v) is not found.
|
1429 |
+
|
1430 |
+
Returns
|
1431 |
+
-------
|
1432 |
+
edge_dict : dictionary
|
1433 |
+
The edge attribute dictionary.
|
1434 |
+
|
1435 |
+
Examples
|
1436 |
+
--------
|
1437 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1438 |
+
>>> G[0][1]
|
1439 |
+
{}
|
1440 |
+
|
1441 |
+
Warning: Assigning to `G[u][v]` is not permitted.
|
1442 |
+
But it is safe to assign attributes `G[u][v]['foo']`
|
1443 |
+
|
1444 |
+
>>> G[0][1]["weight"] = 7
|
1445 |
+
>>> G[0][1]["weight"]
|
1446 |
+
7
|
1447 |
+
>>> G[1][0]["weight"]
|
1448 |
+
7
|
1449 |
+
|
1450 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1451 |
+
>>> G.get_edge_data(0, 1) # default edge data is {}
|
1452 |
+
{}
|
1453 |
+
>>> e = (0, 1)
|
1454 |
+
>>> G.get_edge_data(*e) # tuple form
|
1455 |
+
{}
|
1456 |
+
>>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
|
1457 |
+
0
|
1458 |
+
"""
|
1459 |
+
try:
|
1460 |
+
return self._adj[u][v]
|
1461 |
+
except KeyError:
|
1462 |
+
return default
|
1463 |
+
|
1464 |
+
def adjacency(self):
|
1465 |
+
"""Returns an iterator over (node, adjacency dict) tuples for all nodes.
|
1466 |
+
|
1467 |
+
For directed graphs, only outgoing neighbors/adjacencies are included.
|
1468 |
+
|
1469 |
+
Returns
|
1470 |
+
-------
|
1471 |
+
adj_iter : iterator
|
1472 |
+
An iterator over (node, adjacency dictionary) for all nodes in
|
1473 |
+
the graph.
|
1474 |
+
|
1475 |
+
Examples
|
1476 |
+
--------
|
1477 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1478 |
+
>>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
|
1479 |
+
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
|
1480 |
+
|
1481 |
+
"""
|
1482 |
+
return iter(self._adj.items())
|
1483 |
+
|
1484 |
+
@cached_property
|
1485 |
+
def degree(self):
|
1486 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
1487 |
+
|
1488 |
+
The node degree is the number of edges adjacent to the node.
|
1489 |
+
The weighted node degree is the sum of the edge weights for
|
1490 |
+
edges incident to that node.
|
1491 |
+
|
1492 |
+
This object provides an iterator for (node, degree) as well as
|
1493 |
+
lookup for the degree for a single node.
|
1494 |
+
|
1495 |
+
Parameters
|
1496 |
+
----------
|
1497 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1498 |
+
The view will only report edges incident to these nodes.
|
1499 |
+
|
1500 |
+
weight : string or None, optional (default=None)
|
1501 |
+
The name of an edge attribute that holds the numerical value used
|
1502 |
+
as a weight. If None, then each edge has weight 1.
|
1503 |
+
The degree is the sum of the edge weights adjacent to the node.
|
1504 |
+
|
1505 |
+
Returns
|
1506 |
+
-------
|
1507 |
+
DegreeView or int
|
1508 |
+
If multiple nodes are requested (the default), returns a `DegreeView`
|
1509 |
+
mapping nodes to their degree.
|
1510 |
+
If a single node is requested, returns the degree of the node as an integer.
|
1511 |
+
|
1512 |
+
Examples
|
1513 |
+
--------
|
1514 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1515 |
+
>>> G.degree[0] # node 0 has degree 1
|
1516 |
+
1
|
1517 |
+
>>> list(G.degree([0, 1, 2]))
|
1518 |
+
[(0, 1), (1, 2), (2, 2)]
|
1519 |
+
"""
|
1520 |
+
return DegreeView(self)
|
1521 |
+
|
1522 |
+
def clear(self):
|
1523 |
+
"""Remove all nodes and edges from the graph.
|
1524 |
+
|
1525 |
+
This also removes the name, and all graph, node, and edge attributes.
|
1526 |
+
|
1527 |
+
Examples
|
1528 |
+
--------
|
1529 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1530 |
+
>>> G.clear()
|
1531 |
+
>>> list(G.nodes)
|
1532 |
+
[]
|
1533 |
+
>>> list(G.edges)
|
1534 |
+
[]
|
1535 |
+
|
1536 |
+
"""
|
1537 |
+
self._adj.clear()
|
1538 |
+
self._node.clear()
|
1539 |
+
self.graph.clear()
|
1540 |
+
nx._clear_cache(self)
|
1541 |
+
|
1542 |
+
def clear_edges(self):
|
1543 |
+
"""Remove all edges from the graph without altering nodes.
|
1544 |
+
|
1545 |
+
Examples
|
1546 |
+
--------
|
1547 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1548 |
+
>>> G.clear_edges()
|
1549 |
+
>>> list(G.nodes)
|
1550 |
+
[0, 1, 2, 3]
|
1551 |
+
>>> list(G.edges)
|
1552 |
+
[]
|
1553 |
+
"""
|
1554 |
+
for nbr_dict in self._adj.values():
|
1555 |
+
nbr_dict.clear()
|
1556 |
+
nx._clear_cache(self)
|
1557 |
+
|
1558 |
+
def is_multigraph(self):
|
1559 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
1560 |
+
return False
|
1561 |
+
|
1562 |
+
def is_directed(self):
|
1563 |
+
"""Returns True if graph is directed, False otherwise."""
|
1564 |
+
return False
|
1565 |
+
|
1566 |
+
def copy(self, as_view=False):
|
1567 |
+
"""Returns a copy of the graph.
|
1568 |
+
|
1569 |
+
The copy method by default returns an independent shallow copy
|
1570 |
+
of the graph and attributes. That is, if an attribute is a
|
1571 |
+
container, that container is shared by the original an the copy.
|
1572 |
+
Use Python's `copy.deepcopy` for new containers.
|
1573 |
+
|
1574 |
+
If `as_view` is True then a view is returned instead of a copy.
|
1575 |
+
|
1576 |
+
Notes
|
1577 |
+
-----
|
1578 |
+
All copies reproduce the graph structure, but data attributes
|
1579 |
+
may be handled in different ways. There are four types of copies
|
1580 |
+
of a graph that people might want.
|
1581 |
+
|
1582 |
+
Deepcopy -- A "deepcopy" copies the graph structure as well as
|
1583 |
+
all data attributes and any objects they might contain.
|
1584 |
+
The entire graph object is new so that changes in the copy
|
1585 |
+
do not affect the original object. (see Python's copy.deepcopy)
|
1586 |
+
|
1587 |
+
Data Reference (Shallow) -- For a shallow copy the graph structure
|
1588 |
+
is copied but the edge, node and graph attribute dicts are
|
1589 |
+
references to those in the original graph. This saves
|
1590 |
+
time and memory but could cause confusion if you change an attribute
|
1591 |
+
in one graph and it changes the attribute in the other.
|
1592 |
+
NetworkX does not provide this level of shallow copy.
|
1593 |
+
|
1594 |
+
Independent Shallow -- This copy creates new independent attribute
|
1595 |
+
dicts and then does a shallow copy of the attributes. That is, any
|
1596 |
+
attributes that are containers are shared between the new graph
|
1597 |
+
and the original. This is exactly what `dict.copy()` provides.
|
1598 |
+
You can obtain this style copy using:
|
1599 |
+
|
1600 |
+
>>> G = nx.path_graph(5)
|
1601 |
+
>>> H = G.copy()
|
1602 |
+
>>> H = G.copy(as_view=False)
|
1603 |
+
>>> H = nx.Graph(G)
|
1604 |
+
>>> H = G.__class__(G)
|
1605 |
+
|
1606 |
+
Fresh Data -- For fresh data, the graph structure is copied while
|
1607 |
+
new empty data attribute dicts are created. The resulting graph
|
1608 |
+
is independent of the original and it has no edge, node or graph
|
1609 |
+
attributes. Fresh copies are not enabled. Instead use:
|
1610 |
+
|
1611 |
+
>>> H = G.__class__()
|
1612 |
+
>>> H.add_nodes_from(G)
|
1613 |
+
>>> H.add_edges_from(G.edges)
|
1614 |
+
|
1615 |
+
View -- Inspired by dict-views, graph-views act like read-only
|
1616 |
+
versions of the original graph, providing a copy of the original
|
1617 |
+
structure without requiring any memory for copying the information.
|
1618 |
+
|
1619 |
+
See the Python copy module for more information on shallow
|
1620 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1621 |
+
|
1622 |
+
Parameters
|
1623 |
+
----------
|
1624 |
+
as_view : bool, optional (default=False)
|
1625 |
+
If True, the returned graph-view provides a read-only view
|
1626 |
+
of the original graph without actually copying any data.
|
1627 |
+
|
1628 |
+
Returns
|
1629 |
+
-------
|
1630 |
+
G : Graph
|
1631 |
+
A copy of the graph.
|
1632 |
+
|
1633 |
+
See Also
|
1634 |
+
--------
|
1635 |
+
to_directed: return a directed copy of the graph.
|
1636 |
+
|
1637 |
+
Examples
|
1638 |
+
--------
|
1639 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1640 |
+
>>> H = G.copy()
|
1641 |
+
|
1642 |
+
"""
|
1643 |
+
if as_view is True:
|
1644 |
+
return nx.graphviews.generic_graph_view(self)
|
1645 |
+
G = self.__class__()
|
1646 |
+
G.graph.update(self.graph)
|
1647 |
+
G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
|
1648 |
+
G.add_edges_from(
|
1649 |
+
(u, v, datadict.copy())
|
1650 |
+
for u, nbrs in self._adj.items()
|
1651 |
+
for v, datadict in nbrs.items()
|
1652 |
+
)
|
1653 |
+
return G
|
1654 |
+
|
1655 |
+
def to_directed(self, as_view=False):
|
1656 |
+
"""Returns a directed representation of the graph.
|
1657 |
+
|
1658 |
+
Returns
|
1659 |
+
-------
|
1660 |
+
G : DiGraph
|
1661 |
+
A directed graph with the same name, same nodes, and with
|
1662 |
+
each edge (u, v, data) replaced by two directed edges
|
1663 |
+
(u, v, data) and (v, u, data).
|
1664 |
+
|
1665 |
+
Notes
|
1666 |
+
-----
|
1667 |
+
This returns a "deepcopy" of the edge, node, and
|
1668 |
+
graph attributes which attempts to completely copy
|
1669 |
+
all of the data and references.
|
1670 |
+
|
1671 |
+
This is in contrast to the similar D=DiGraph(G) which returns a
|
1672 |
+
shallow copy of the data.
|
1673 |
+
|
1674 |
+
See the Python copy module for more information on shallow
|
1675 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1676 |
+
|
1677 |
+
Warning: If you have subclassed Graph to use dict-like objects
|
1678 |
+
in the data structure, those changes do not transfer to the
|
1679 |
+
DiGraph created by this method.
|
1680 |
+
|
1681 |
+
Examples
|
1682 |
+
--------
|
1683 |
+
>>> G = nx.Graph() # or MultiGraph, etc
|
1684 |
+
>>> G.add_edge(0, 1)
|
1685 |
+
>>> H = G.to_directed()
|
1686 |
+
>>> list(H.edges)
|
1687 |
+
[(0, 1), (1, 0)]
|
1688 |
+
|
1689 |
+
If already directed, return a (deep) copy
|
1690 |
+
|
1691 |
+
>>> G = nx.DiGraph() # or MultiDiGraph, etc
|
1692 |
+
>>> G.add_edge(0, 1)
|
1693 |
+
>>> H = G.to_directed()
|
1694 |
+
>>> list(H.edges)
|
1695 |
+
[(0, 1)]
|
1696 |
+
"""
|
1697 |
+
graph_class = self.to_directed_class()
|
1698 |
+
if as_view is True:
|
1699 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1700 |
+
# deepcopy when not a view
|
1701 |
+
G = graph_class()
|
1702 |
+
G.graph.update(deepcopy(self.graph))
|
1703 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1704 |
+
G.add_edges_from(
|
1705 |
+
(u, v, deepcopy(data))
|
1706 |
+
for u, nbrs in self._adj.items()
|
1707 |
+
for v, data in nbrs.items()
|
1708 |
+
)
|
1709 |
+
return G
|
1710 |
+
|
1711 |
+
def to_undirected(self, as_view=False):
|
1712 |
+
"""Returns an undirected copy of the graph.
|
1713 |
+
|
1714 |
+
Parameters
|
1715 |
+
----------
|
1716 |
+
as_view : bool (optional, default=False)
|
1717 |
+
If True return a view of the original undirected graph.
|
1718 |
+
|
1719 |
+
Returns
|
1720 |
+
-------
|
1721 |
+
G : Graph/MultiGraph
|
1722 |
+
A deepcopy of the graph.
|
1723 |
+
|
1724 |
+
See Also
|
1725 |
+
--------
|
1726 |
+
Graph, copy, add_edge, add_edges_from
|
1727 |
+
|
1728 |
+
Notes
|
1729 |
+
-----
|
1730 |
+
This returns a "deepcopy" of the edge, node, and
|
1731 |
+
graph attributes which attempts to completely copy
|
1732 |
+
all of the data and references.
|
1733 |
+
|
1734 |
+
This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
|
1735 |
+
shallow copy of the data.
|
1736 |
+
|
1737 |
+
See the Python copy module for more information on shallow
|
1738 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
1739 |
+
|
1740 |
+
Warning: If you have subclassed DiGraph to use dict-like objects
|
1741 |
+
in the data structure, those changes do not transfer to the
|
1742 |
+
Graph created by this method.
|
1743 |
+
|
1744 |
+
Examples
|
1745 |
+
--------
|
1746 |
+
>>> G = nx.path_graph(2) # or MultiGraph, etc
|
1747 |
+
>>> H = G.to_directed()
|
1748 |
+
>>> list(H.edges)
|
1749 |
+
[(0, 1), (1, 0)]
|
1750 |
+
>>> G2 = H.to_undirected()
|
1751 |
+
>>> list(G2.edges)
|
1752 |
+
[(0, 1)]
|
1753 |
+
"""
|
1754 |
+
graph_class = self.to_undirected_class()
|
1755 |
+
if as_view is True:
|
1756 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
1757 |
+
# deepcopy when not a view
|
1758 |
+
G = graph_class()
|
1759 |
+
G.graph.update(deepcopy(self.graph))
|
1760 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
1761 |
+
G.add_edges_from(
|
1762 |
+
(u, v, deepcopy(d))
|
1763 |
+
for u, nbrs in self._adj.items()
|
1764 |
+
for v, d in nbrs.items()
|
1765 |
+
)
|
1766 |
+
return G
|
1767 |
+
|
1768 |
+
def subgraph(self, nodes):
|
1769 |
+
"""Returns a SubGraph view of the subgraph induced on `nodes`.
|
1770 |
+
|
1771 |
+
The induced subgraph of the graph contains the nodes in `nodes`
|
1772 |
+
and the edges between those nodes.
|
1773 |
+
|
1774 |
+
Parameters
|
1775 |
+
----------
|
1776 |
+
nodes : list, iterable
|
1777 |
+
A container of nodes which will be iterated through once.
|
1778 |
+
|
1779 |
+
Returns
|
1780 |
+
-------
|
1781 |
+
G : SubGraph View
|
1782 |
+
A subgraph view of the graph. The graph structure cannot be
|
1783 |
+
changed but node/edge attributes can and are shared with the
|
1784 |
+
original graph.
|
1785 |
+
|
1786 |
+
Notes
|
1787 |
+
-----
|
1788 |
+
The graph, edge and node attributes are shared with the original graph.
|
1789 |
+
Changes to the graph structure is ruled out by the view, but changes
|
1790 |
+
to attributes are reflected in the original graph.
|
1791 |
+
|
1792 |
+
To create a subgraph with its own copy of the edge/node attributes use:
|
1793 |
+
G.subgraph(nodes).copy()
|
1794 |
+
|
1795 |
+
For an inplace reduction of a graph to a subgraph you can remove nodes:
|
1796 |
+
G.remove_nodes_from([n for n in G if n not in set(nodes)])
|
1797 |
+
|
1798 |
+
Subgraph views are sometimes NOT what you want. In most cases where
|
1799 |
+
you want to do more than simply look at the induced edges, it makes
|
1800 |
+
more sense to just create the subgraph as its own graph with code like:
|
1801 |
+
|
1802 |
+
::
|
1803 |
+
|
1804 |
+
# Create a subgraph SG based on a (possibly multigraph) G
|
1805 |
+
SG = G.__class__()
|
1806 |
+
SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
|
1807 |
+
if SG.is_multigraph():
|
1808 |
+
SG.add_edges_from(
|
1809 |
+
(n, nbr, key, d)
|
1810 |
+
for n, nbrs in G.adj.items()
|
1811 |
+
if n in largest_wcc
|
1812 |
+
for nbr, keydict in nbrs.items()
|
1813 |
+
if nbr in largest_wcc
|
1814 |
+
for key, d in keydict.items()
|
1815 |
+
)
|
1816 |
+
else:
|
1817 |
+
SG.add_edges_from(
|
1818 |
+
(n, nbr, d)
|
1819 |
+
for n, nbrs in G.adj.items()
|
1820 |
+
if n in largest_wcc
|
1821 |
+
for nbr, d in nbrs.items()
|
1822 |
+
if nbr in largest_wcc
|
1823 |
+
)
|
1824 |
+
SG.graph.update(G.graph)
|
1825 |
+
|
1826 |
+
Examples
|
1827 |
+
--------
|
1828 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1829 |
+
>>> H = G.subgraph([0, 1, 2])
|
1830 |
+
>>> list(H.edges)
|
1831 |
+
[(0, 1), (1, 2)]
|
1832 |
+
"""
|
1833 |
+
induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
|
1834 |
+
# if already a subgraph, don't make a chain
|
1835 |
+
subgraph = nx.subgraph_view
|
1836 |
+
if hasattr(self, "_NODE_OK"):
|
1837 |
+
return subgraph(
|
1838 |
+
self._graph, filter_node=induced_nodes, filter_edge=self._EDGE_OK
|
1839 |
+
)
|
1840 |
+
return subgraph(self, filter_node=induced_nodes)
|
1841 |
+
|
1842 |
+
def edge_subgraph(self, edges):
|
1843 |
+
"""Returns the subgraph induced by the specified edges.
|
1844 |
+
|
1845 |
+
The induced subgraph contains each edge in `edges` and each
|
1846 |
+
node incident to any one of those edges.
|
1847 |
+
|
1848 |
+
Parameters
|
1849 |
+
----------
|
1850 |
+
edges : iterable
|
1851 |
+
An iterable of edges in this graph.
|
1852 |
+
|
1853 |
+
Returns
|
1854 |
+
-------
|
1855 |
+
G : Graph
|
1856 |
+
An edge-induced subgraph of this graph with the same edge
|
1857 |
+
attributes.
|
1858 |
+
|
1859 |
+
Notes
|
1860 |
+
-----
|
1861 |
+
The graph, edge, and node attributes in the returned subgraph
|
1862 |
+
view are references to the corresponding attributes in the original
|
1863 |
+
graph. The view is read-only.
|
1864 |
+
|
1865 |
+
To create a full graph version of the subgraph with its own copy
|
1866 |
+
of the edge or node attributes, use::
|
1867 |
+
|
1868 |
+
G.edge_subgraph(edges).copy()
|
1869 |
+
|
1870 |
+
Examples
|
1871 |
+
--------
|
1872 |
+
>>> G = nx.path_graph(5)
|
1873 |
+
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
|
1874 |
+
>>> list(H.nodes)
|
1875 |
+
[0, 1, 3, 4]
|
1876 |
+
>>> list(H.edges)
|
1877 |
+
[(0, 1), (3, 4)]
|
1878 |
+
|
1879 |
+
"""
|
1880 |
+
return nx.edge_subgraph(self, edges)
|
1881 |
+
|
1882 |
+
def size(self, weight=None):
|
1883 |
+
"""Returns the number of edges or total of all edge weights.
|
1884 |
+
|
1885 |
+
Parameters
|
1886 |
+
----------
|
1887 |
+
weight : string or None, optional (default=None)
|
1888 |
+
The edge attribute that holds the numerical value used
|
1889 |
+
as a weight. If None, then each edge has weight 1.
|
1890 |
+
|
1891 |
+
Returns
|
1892 |
+
-------
|
1893 |
+
size : numeric
|
1894 |
+
The number of edges or
|
1895 |
+
(if weight keyword is provided) the total weight sum.
|
1896 |
+
|
1897 |
+
If weight is None, returns an int. Otherwise a float
|
1898 |
+
(or more general numeric if the weights are more general).
|
1899 |
+
|
1900 |
+
See Also
|
1901 |
+
--------
|
1902 |
+
number_of_edges
|
1903 |
+
|
1904 |
+
Examples
|
1905 |
+
--------
|
1906 |
+
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1907 |
+
>>> G.size()
|
1908 |
+
3
|
1909 |
+
|
1910 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
1911 |
+
>>> G.add_edge("a", "b", weight=2)
|
1912 |
+
>>> G.add_edge("b", "c", weight=4)
|
1913 |
+
>>> G.size()
|
1914 |
+
2
|
1915 |
+
>>> G.size(weight="weight")
|
1916 |
+
6.0
|
1917 |
+
"""
|
1918 |
+
s = sum(d for v, d in self.degree(weight=weight))
|
1919 |
+
# If `weight` is None, the sum of the degrees is guaranteed to be
|
1920 |
+
# even, so we can perform integer division and hence return an
|
1921 |
+
# integer. Otherwise, the sum of the weighted degrees is not
|
1922 |
+
# guaranteed to be an integer, so we perform "real" division.
|
1923 |
+
return s // 2 if weight is None else s / 2
|
1924 |
+
|
1925 |
+
def number_of_edges(self, u=None, v=None):
|
1926 |
+
"""Returns the number of edges between two nodes.
|
1927 |
+
|
1928 |
+
Parameters
|
1929 |
+
----------
|
1930 |
+
u, v : nodes, optional (default=all edges)
|
1931 |
+
If u and v are specified, return the number of edges between
|
1932 |
+
u and v. Otherwise return the total number of all edges.
|
1933 |
+
|
1934 |
+
Returns
|
1935 |
+
-------
|
1936 |
+
nedges : int
|
1937 |
+
The number of edges in the graph. If nodes `u` and `v` are
|
1938 |
+
specified return the number of edges between those nodes. If
|
1939 |
+
the graph is directed, this only returns the number of edges
|
1940 |
+
from `u` to `v`.
|
1941 |
+
|
1942 |
+
See Also
|
1943 |
+
--------
|
1944 |
+
size
|
1945 |
+
|
1946 |
+
Examples
|
1947 |
+
--------
|
1948 |
+
For undirected graphs, this method counts the total number of
|
1949 |
+
edges in the graph:
|
1950 |
+
|
1951 |
+
>>> G = nx.path_graph(4)
|
1952 |
+
>>> G.number_of_edges()
|
1953 |
+
3
|
1954 |
+
|
1955 |
+
If you specify two nodes, this counts the total number of edges
|
1956 |
+
joining the two nodes:
|
1957 |
+
|
1958 |
+
>>> G.number_of_edges(0, 1)
|
1959 |
+
1
|
1960 |
+
|
1961 |
+
For directed graphs, this method can count the total number of
|
1962 |
+
directed edges from `u` to `v`:
|
1963 |
+
|
1964 |
+
>>> G = nx.DiGraph()
|
1965 |
+
>>> G.add_edge(0, 1)
|
1966 |
+
>>> G.add_edge(1, 0)
|
1967 |
+
>>> G.number_of_edges(0, 1)
|
1968 |
+
1
|
1969 |
+
|
1970 |
+
"""
|
1971 |
+
if u is None:
|
1972 |
+
return int(self.size())
|
1973 |
+
if v in self._adj[u]:
|
1974 |
+
return 1
|
1975 |
+
return 0
|
1976 |
+
|
1977 |
+
def nbunch_iter(self, nbunch=None):
|
1978 |
+
"""Returns an iterator over nodes contained in nbunch that are
|
1979 |
+
also in the graph.
|
1980 |
+
|
1981 |
+
The nodes in nbunch are checked for membership in the graph
|
1982 |
+
and if not are silently ignored.
|
1983 |
+
|
1984 |
+
Parameters
|
1985 |
+
----------
|
1986 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
1987 |
+
The view will only report edges incident to these nodes.
|
1988 |
+
|
1989 |
+
Returns
|
1990 |
+
-------
|
1991 |
+
niter : iterator
|
1992 |
+
An iterator over nodes in nbunch that are also in the graph.
|
1993 |
+
If nbunch is None, iterate over all nodes in the graph.
|
1994 |
+
|
1995 |
+
Raises
|
1996 |
+
------
|
1997 |
+
NetworkXError
|
1998 |
+
If nbunch is not a node or sequence of nodes.
|
1999 |
+
If a node in nbunch is not hashable.
|
2000 |
+
|
2001 |
+
See Also
|
2002 |
+
--------
|
2003 |
+
Graph.__iter__
|
2004 |
+
|
2005 |
+
Notes
|
2006 |
+
-----
|
2007 |
+
When nbunch is an iterator, the returned iterator yields values
|
2008 |
+
directly from nbunch, becoming exhausted when nbunch is exhausted.
|
2009 |
+
|
2010 |
+
To test whether nbunch is a single node, one can use
|
2011 |
+
"if nbunch in self:", even after processing with this routine.
|
2012 |
+
|
2013 |
+
If nbunch is not a node or a (possibly empty) sequence/iterator
|
2014 |
+
or None, a :exc:`NetworkXError` is raised. Also, if any object in
|
2015 |
+
nbunch is not hashable, a :exc:`NetworkXError` is raised.
|
2016 |
+
"""
|
2017 |
+
if nbunch is None: # include all nodes via iterator
|
2018 |
+
bunch = iter(self._adj)
|
2019 |
+
elif nbunch in self: # if nbunch is a single node
|
2020 |
+
bunch = iter([nbunch])
|
2021 |
+
else: # if nbunch is a sequence of nodes
|
2022 |
+
|
2023 |
+
def bunch_iter(nlist, adj):
|
2024 |
+
try:
|
2025 |
+
for n in nlist:
|
2026 |
+
if n in adj:
|
2027 |
+
yield n
|
2028 |
+
except TypeError as err:
|
2029 |
+
exc, message = err, err.args[0]
|
2030 |
+
# capture error for non-sequence/iterator nbunch.
|
2031 |
+
if "iter" in message:
|
2032 |
+
exc = NetworkXError(
|
2033 |
+
"nbunch is not a node or a sequence of nodes."
|
2034 |
+
)
|
2035 |
+
# capture error for unhashable node.
|
2036 |
+
if "hashable" in message:
|
2037 |
+
exc = NetworkXError(
|
2038 |
+
f"Node {n} in sequence nbunch is not a valid node."
|
2039 |
+
)
|
2040 |
+
raise exc
|
2041 |
+
|
2042 |
+
bunch = bunch_iter(nbunch, self._adj)
|
2043 |
+
return bunch
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/multidigraph.py
ADDED
@@ -0,0 +1,965 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for MultiDiGraph."""
|
2 |
+
from copy import deepcopy
|
3 |
+
from functools import cached_property
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx import convert
|
7 |
+
from networkx.classes.coreviews import MultiAdjacencyView
|
8 |
+
from networkx.classes.digraph import DiGraph
|
9 |
+
from networkx.classes.multigraph import MultiGraph
|
10 |
+
from networkx.classes.reportviews import (
|
11 |
+
DiMultiDegreeView,
|
12 |
+
InMultiDegreeView,
|
13 |
+
InMultiEdgeView,
|
14 |
+
OutMultiDegreeView,
|
15 |
+
OutMultiEdgeView,
|
16 |
+
)
|
17 |
+
from networkx.exception import NetworkXError
|
18 |
+
|
19 |
+
__all__ = ["MultiDiGraph"]
|
20 |
+
|
21 |
+
|
22 |
+
class MultiDiGraph(MultiGraph, DiGraph):
|
23 |
+
"""A directed graph class that can store multiedges.
|
24 |
+
|
25 |
+
Multiedges are multiple edges between two nodes. Each edge
|
26 |
+
can hold optional data or attributes.
|
27 |
+
|
28 |
+
A MultiDiGraph holds directed edges. Self loops are allowed.
|
29 |
+
|
30 |
+
Nodes can be arbitrary (hashable) Python objects with optional
|
31 |
+
key/value attributes. By convention `None` is not used as a node.
|
32 |
+
|
33 |
+
Edges are represented as links between nodes with optional
|
34 |
+
key/value attributes.
|
35 |
+
|
36 |
+
Parameters
|
37 |
+
----------
|
38 |
+
incoming_graph_data : input graph (optional, default: None)
|
39 |
+
Data to initialize graph. If None (default) an empty
|
40 |
+
graph is created. The data can be any format that is supported
|
41 |
+
by the to_networkx_graph() function, currently including edge list,
|
42 |
+
dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
|
43 |
+
sparse matrix, or PyGraphviz graph.
|
44 |
+
|
45 |
+
multigraph_input : bool or None (default None)
|
46 |
+
Note: Only used when `incoming_graph_data` is a dict.
|
47 |
+
If True, `incoming_graph_data` is assumed to be a
|
48 |
+
dict-of-dict-of-dict-of-dict structure keyed by
|
49 |
+
node to neighbor to edge keys to edge data for multi-edges.
|
50 |
+
A NetworkXError is raised if this is not the case.
|
51 |
+
If False, :func:`to_networkx_graph` is used to try to determine
|
52 |
+
the dict's graph data structure as either a dict-of-dict-of-dict
|
53 |
+
keyed by node to neighbor to edge data, or a dict-of-iterable
|
54 |
+
keyed by node to neighbors.
|
55 |
+
If None, the treatment for True is tried, but if it fails,
|
56 |
+
the treatment for False is tried.
|
57 |
+
|
58 |
+
attr : keyword arguments, optional (default= no attributes)
|
59 |
+
Attributes to add to graph as key=value pairs.
|
60 |
+
|
61 |
+
See Also
|
62 |
+
--------
|
63 |
+
Graph
|
64 |
+
DiGraph
|
65 |
+
MultiGraph
|
66 |
+
|
67 |
+
Examples
|
68 |
+
--------
|
69 |
+
Create an empty graph structure (a "null graph") with no nodes and
|
70 |
+
no edges.
|
71 |
+
|
72 |
+
>>> G = nx.MultiDiGraph()
|
73 |
+
|
74 |
+
G can be grown in several ways.
|
75 |
+
|
76 |
+
**Nodes:**
|
77 |
+
|
78 |
+
Add one node at a time:
|
79 |
+
|
80 |
+
>>> G.add_node(1)
|
81 |
+
|
82 |
+
Add the nodes from any container (a list, dict, set or
|
83 |
+
even the lines from a file or the nodes from another graph).
|
84 |
+
|
85 |
+
>>> G.add_nodes_from([2, 3])
|
86 |
+
>>> G.add_nodes_from(range(100, 110))
|
87 |
+
>>> H = nx.path_graph(10)
|
88 |
+
>>> G.add_nodes_from(H)
|
89 |
+
|
90 |
+
In addition to strings and integers any hashable Python object
|
91 |
+
(except None) can represent a node, e.g. a customized node object,
|
92 |
+
or even another Graph.
|
93 |
+
|
94 |
+
>>> G.add_node(H)
|
95 |
+
|
96 |
+
**Edges:**
|
97 |
+
|
98 |
+
G can also be grown by adding edges.
|
99 |
+
|
100 |
+
Add one edge,
|
101 |
+
|
102 |
+
>>> key = G.add_edge(1, 2)
|
103 |
+
|
104 |
+
a list of edges,
|
105 |
+
|
106 |
+
>>> keys = G.add_edges_from([(1, 2), (1, 3)])
|
107 |
+
|
108 |
+
or a collection of edges,
|
109 |
+
|
110 |
+
>>> keys = G.add_edges_from(H.edges)
|
111 |
+
|
112 |
+
If some edges connect nodes not yet in the graph, the nodes
|
113 |
+
are added automatically. If an edge already exists, an additional
|
114 |
+
edge is created and stored using a key to identify the edge.
|
115 |
+
By default the key is the lowest unused integer.
|
116 |
+
|
117 |
+
>>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
|
118 |
+
>>> G[4]
|
119 |
+
AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
|
120 |
+
|
121 |
+
**Attributes:**
|
122 |
+
|
123 |
+
Each graph, node, and edge can hold key/value attribute pairs
|
124 |
+
in an associated attribute dictionary (the keys must be hashable).
|
125 |
+
By default these are empty, but can be added or changed using
|
126 |
+
add_edge, add_node or direct manipulation of the attribute
|
127 |
+
dictionaries named graph, node and edge respectively.
|
128 |
+
|
129 |
+
>>> G = nx.MultiDiGraph(day="Friday")
|
130 |
+
>>> G.graph
|
131 |
+
{'day': 'Friday'}
|
132 |
+
|
133 |
+
Add node attributes using add_node(), add_nodes_from() or G.nodes
|
134 |
+
|
135 |
+
>>> G.add_node(1, time="5pm")
|
136 |
+
>>> G.add_nodes_from([3], time="2pm")
|
137 |
+
>>> G.nodes[1]
|
138 |
+
{'time': '5pm'}
|
139 |
+
>>> G.nodes[1]["room"] = 714
|
140 |
+
>>> del G.nodes[1]["room"] # remove attribute
|
141 |
+
>>> list(G.nodes(data=True))
|
142 |
+
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
|
143 |
+
|
144 |
+
Add edge attributes using add_edge(), add_edges_from(), subscript
|
145 |
+
notation, or G.edges.
|
146 |
+
|
147 |
+
>>> key = G.add_edge(1, 2, weight=4.7)
|
148 |
+
>>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
|
149 |
+
>>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
|
150 |
+
>>> G[1][2][0]["weight"] = 4.7
|
151 |
+
>>> G.edges[1, 2, 0]["weight"] = 4
|
152 |
+
|
153 |
+
Warning: we protect the graph data structure by making `G.edges[1,
|
154 |
+
2, 0]` a read-only dict-like structure. However, you can assign to
|
155 |
+
attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
|
156 |
+
to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
|
157 |
+
(for multigraphs the edge key is required: `MG.edges[u, v,
|
158 |
+
key][name] = value`).
|
159 |
+
|
160 |
+
**Shortcuts:**
|
161 |
+
|
162 |
+
Many common graph features allow python syntax to speed reporting.
|
163 |
+
|
164 |
+
>>> 1 in G # check if node in graph
|
165 |
+
True
|
166 |
+
>>> [n for n in G if n < 3] # iterate through nodes
|
167 |
+
[1, 2]
|
168 |
+
>>> len(G) # number of nodes in graph
|
169 |
+
5
|
170 |
+
>>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
|
171 |
+
AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
|
172 |
+
|
173 |
+
Often the best way to traverse all edges of a graph is via the neighbors.
|
174 |
+
The neighbors are available as an adjacency-view `G.adj` object or via
|
175 |
+
the method `G.adjacency()`.
|
176 |
+
|
177 |
+
>>> for n, nbrsdict in G.adjacency():
|
178 |
+
... for nbr, keydict in nbrsdict.items():
|
179 |
+
... for key, eattr in keydict.items():
|
180 |
+
... if "weight" in eattr:
|
181 |
+
... # Do something useful with the edges
|
182 |
+
... pass
|
183 |
+
|
184 |
+
But the edges() method is often more convenient:
|
185 |
+
|
186 |
+
>>> for u, v, keys, weight in G.edges(data="weight", keys=True):
|
187 |
+
... if weight is not None:
|
188 |
+
... # Do something useful with the edges
|
189 |
+
... pass
|
190 |
+
|
191 |
+
**Reporting:**
|
192 |
+
|
193 |
+
Simple graph information is obtained using methods and object-attributes.
|
194 |
+
Reporting usually provides views instead of containers to reduce memory
|
195 |
+
usage. The views update as the graph is updated similarly to dict-views.
|
196 |
+
The objects `nodes`, `edges` and `adj` provide access to data attributes
|
197 |
+
via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
|
198 |
+
(e.g. `nodes.items()`, `nodes.data('color')`,
|
199 |
+
`nodes.data('color', default='blue')` and similarly for `edges`)
|
200 |
+
Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
|
201 |
+
|
202 |
+
For details on these and other miscellaneous methods, see below.
|
203 |
+
|
204 |
+
**Subclasses (Advanced):**
|
205 |
+
|
206 |
+
The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
|
207 |
+
The outer dict (node_dict) holds adjacency information keyed by node.
|
208 |
+
The next dict (adjlist_dict) represents the adjacency information
|
209 |
+
and holds edge_key dicts keyed by neighbor. The edge_key dict holds
|
210 |
+
each edge_attr dict keyed by edge key. The inner dict
|
211 |
+
(edge_attr_dict) represents the edge data and holds edge attribute
|
212 |
+
values keyed by attribute names.
|
213 |
+
|
214 |
+
Each of these four dicts in the dict-of-dict-of-dict-of-dict
|
215 |
+
structure can be replaced by a user defined dict-like object.
|
216 |
+
In general, the dict-like features should be maintained but
|
217 |
+
extra features can be added. To replace one of the dicts create
|
218 |
+
a new graph class by changing the class(!) variable holding the
|
219 |
+
factory for that dict-like structure. The variable names are
|
220 |
+
node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
|
221 |
+
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
|
222 |
+
and graph_attr_dict_factory.
|
223 |
+
|
224 |
+
node_dict_factory : function, (default: dict)
|
225 |
+
Factory function to be used to create the dict containing node
|
226 |
+
attributes, keyed by node id.
|
227 |
+
It should require no arguments and return a dict-like object
|
228 |
+
|
229 |
+
node_attr_dict_factory: function, (default: dict)
|
230 |
+
Factory function to be used to create the node attribute
|
231 |
+
dict which holds attribute values keyed by attribute name.
|
232 |
+
It should require no arguments and return a dict-like object
|
233 |
+
|
234 |
+
adjlist_outer_dict_factory : function, (default: dict)
|
235 |
+
Factory function to be used to create the outer-most dict
|
236 |
+
in the data structure that holds adjacency info keyed by node.
|
237 |
+
It should require no arguments and return a dict-like object.
|
238 |
+
|
239 |
+
adjlist_inner_dict_factory : function, (default: dict)
|
240 |
+
Factory function to be used to create the adjacency list
|
241 |
+
dict which holds multiedge key dicts keyed by neighbor.
|
242 |
+
It should require no arguments and return a dict-like object.
|
243 |
+
|
244 |
+
edge_key_dict_factory : function, (default: dict)
|
245 |
+
Factory function to be used to create the edge key dict
|
246 |
+
which holds edge data keyed by edge key.
|
247 |
+
It should require no arguments and return a dict-like object.
|
248 |
+
|
249 |
+
edge_attr_dict_factory : function, (default: dict)
|
250 |
+
Factory function to be used to create the edge attribute
|
251 |
+
dict which holds attribute values keyed by attribute name.
|
252 |
+
It should require no arguments and return a dict-like object.
|
253 |
+
|
254 |
+
graph_attr_dict_factory : function, (default: dict)
|
255 |
+
Factory function to be used to create the graph attribute
|
256 |
+
dict which holds attribute values keyed by attribute name.
|
257 |
+
It should require no arguments and return a dict-like object.
|
258 |
+
|
259 |
+
Typically, if your extension doesn't impact the data structure all
|
260 |
+
methods will inherited without issue except: `to_directed/to_undirected`.
|
261 |
+
By default these methods create a DiGraph/Graph class and you probably
|
262 |
+
want them to create your extension of a DiGraph/Graph. To facilitate
|
263 |
+
this we define two class variables that you can set in your subclass.
|
264 |
+
|
265 |
+
to_directed_class : callable, (default: DiGraph or MultiDiGraph)
|
266 |
+
Class to create a new graph structure in the `to_directed` method.
|
267 |
+
If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
|
268 |
+
|
269 |
+
to_undirected_class : callable, (default: Graph or MultiGraph)
|
270 |
+
Class to create a new graph structure in the `to_undirected` method.
|
271 |
+
If `None`, a NetworkX class (Graph or MultiGraph) is used.
|
272 |
+
|
273 |
+
**Subclassing Example**
|
274 |
+
|
275 |
+
Create a low memory graph class that effectively disallows edge
|
276 |
+
attributes by using a single attribute dict for all edges.
|
277 |
+
This reduces the memory used, but you lose edge attributes.
|
278 |
+
|
279 |
+
>>> class ThinGraph(nx.Graph):
|
280 |
+
... all_edge_dict = {"weight": 1}
|
281 |
+
...
|
282 |
+
... def single_edge_dict(self):
|
283 |
+
... return self.all_edge_dict
|
284 |
+
...
|
285 |
+
... edge_attr_dict_factory = single_edge_dict
|
286 |
+
>>> G = ThinGraph()
|
287 |
+
>>> G.add_edge(2, 1)
|
288 |
+
>>> G[2][1]
|
289 |
+
{'weight': 1}
|
290 |
+
>>> G.add_edge(2, 2)
|
291 |
+
>>> G[2][1] is G[2][2]
|
292 |
+
True
|
293 |
+
"""
|
294 |
+
|
295 |
+
# node_dict_factory = dict # already assigned in Graph
|
296 |
+
# adjlist_outer_dict_factory = dict
|
297 |
+
# adjlist_inner_dict_factory = dict
|
298 |
+
edge_key_dict_factory = dict
|
299 |
+
# edge_attr_dict_factory = dict
|
300 |
+
|
301 |
+
def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
|
302 |
+
"""Initialize a graph with edges, name, or graph attributes.
|
303 |
+
|
304 |
+
Parameters
|
305 |
+
----------
|
306 |
+
incoming_graph_data : input graph
|
307 |
+
Data to initialize graph. If incoming_graph_data=None (default)
|
308 |
+
an empty graph is created. The data can be an edge list, or any
|
309 |
+
NetworkX graph object. If the corresponding optional Python
|
310 |
+
packages are installed the data can also be a 2D NumPy array, a
|
311 |
+
SciPy sparse array, or a PyGraphviz graph.
|
312 |
+
|
313 |
+
multigraph_input : bool or None (default None)
|
314 |
+
Note: Only used when `incoming_graph_data` is a dict.
|
315 |
+
If True, `incoming_graph_data` is assumed to be a
|
316 |
+
dict-of-dict-of-dict-of-dict structure keyed by
|
317 |
+
node to neighbor to edge keys to edge data for multi-edges.
|
318 |
+
A NetworkXError is raised if this is not the case.
|
319 |
+
If False, :func:`to_networkx_graph` is used to try to determine
|
320 |
+
the dict's graph data structure as either a dict-of-dict-of-dict
|
321 |
+
keyed by node to neighbor to edge data, or a dict-of-iterable
|
322 |
+
keyed by node to neighbors.
|
323 |
+
If None, the treatment for True is tried, but if it fails,
|
324 |
+
the treatment for False is tried.
|
325 |
+
|
326 |
+
attr : keyword arguments, optional (default= no attributes)
|
327 |
+
Attributes to add to graph as key=value pairs.
|
328 |
+
|
329 |
+
See Also
|
330 |
+
--------
|
331 |
+
convert
|
332 |
+
|
333 |
+
Examples
|
334 |
+
--------
|
335 |
+
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
|
336 |
+
>>> G = nx.Graph(name="my graph")
|
337 |
+
>>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
|
338 |
+
>>> G = nx.Graph(e)
|
339 |
+
|
340 |
+
Arbitrary graph attribute pairs (key=value) may be assigned
|
341 |
+
|
342 |
+
>>> G = nx.Graph(e, day="Friday")
|
343 |
+
>>> G.graph
|
344 |
+
{'day': 'Friday'}
|
345 |
+
|
346 |
+
"""
|
347 |
+
# multigraph_input can be None/True/False. So check "is not False"
|
348 |
+
if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
|
349 |
+
DiGraph.__init__(self)
|
350 |
+
try:
|
351 |
+
convert.from_dict_of_dicts(
|
352 |
+
incoming_graph_data, create_using=self, multigraph_input=True
|
353 |
+
)
|
354 |
+
self.graph.update(attr)
|
355 |
+
except Exception as err:
|
356 |
+
if multigraph_input is True:
|
357 |
+
raise nx.NetworkXError(
|
358 |
+
f"converting multigraph_input raised:\n{type(err)}: {err}"
|
359 |
+
)
|
360 |
+
DiGraph.__init__(self, incoming_graph_data, **attr)
|
361 |
+
else:
|
362 |
+
DiGraph.__init__(self, incoming_graph_data, **attr)
|
363 |
+
|
364 |
+
@cached_property
|
365 |
+
def adj(self):
|
366 |
+
"""Graph adjacency object holding the neighbors of each node.
|
367 |
+
|
368 |
+
This object is a read-only dict-like structure with node keys
|
369 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
370 |
+
to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
371 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
372 |
+
|
373 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
374 |
+
`for nbr, datadict in G.adj[n].items():`.
|
375 |
+
|
376 |
+
The neighbor information is also provided by subscripting the graph.
|
377 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
378 |
+
|
379 |
+
For directed graphs, `G.adj` holds outgoing (successor) info.
|
380 |
+
"""
|
381 |
+
return MultiAdjacencyView(self._succ)
|
382 |
+
|
383 |
+
@cached_property
|
384 |
+
def succ(self):
|
385 |
+
"""Graph adjacency object holding the successors of each node.
|
386 |
+
|
387 |
+
This object is a read-only dict-like structure with node keys
|
388 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
389 |
+
to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
390 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
391 |
+
|
392 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
393 |
+
`for nbr, datadict in G.adj[n].items():`.
|
394 |
+
|
395 |
+
The neighbor information is also provided by subscripting the graph.
|
396 |
+
So `for nbr, foovalue in G[node].data('foo', default=1):` works.
|
397 |
+
|
398 |
+
For directed graphs, `G.succ` is identical to `G.adj`.
|
399 |
+
"""
|
400 |
+
return MultiAdjacencyView(self._succ)
|
401 |
+
|
402 |
+
@cached_property
|
403 |
+
def pred(self):
|
404 |
+
"""Graph adjacency object holding the predecessors of each node.
|
405 |
+
|
406 |
+
This object is a read-only dict-like structure with node keys
|
407 |
+
and neighbor-dict values. The neighbor-dict is keyed by neighbor
|
408 |
+
to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
|
409 |
+
the color of the edge `(3, 2, 0)` to `"blue"`.
|
410 |
+
|
411 |
+
Iterating over G.adj behaves like a dict. Useful idioms include
|
412 |
+
`for nbr, datadict in G.adj[n].items():`.
|
413 |
+
"""
|
414 |
+
return MultiAdjacencyView(self._pred)
|
415 |
+
|
416 |
+
def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
|
417 |
+
"""Add an edge between u and v.
|
418 |
+
|
419 |
+
The nodes u and v will be automatically added if they are
|
420 |
+
not already in the graph.
|
421 |
+
|
422 |
+
Edge attributes can be specified with keywords or by directly
|
423 |
+
accessing the edge's attribute dictionary. See examples below.
|
424 |
+
|
425 |
+
Parameters
|
426 |
+
----------
|
427 |
+
u_for_edge, v_for_edge : nodes
|
428 |
+
Nodes can be, for example, strings or numbers.
|
429 |
+
Nodes must be hashable (and not None) Python objects.
|
430 |
+
key : hashable identifier, optional (default=lowest unused integer)
|
431 |
+
Used to distinguish multiedges between a pair of nodes.
|
432 |
+
attr : keyword arguments, optional
|
433 |
+
Edge data (or labels or objects) can be assigned using
|
434 |
+
keyword arguments.
|
435 |
+
|
436 |
+
Returns
|
437 |
+
-------
|
438 |
+
The edge key assigned to the edge.
|
439 |
+
|
440 |
+
See Also
|
441 |
+
--------
|
442 |
+
add_edges_from : add a collection of edges
|
443 |
+
|
444 |
+
Notes
|
445 |
+
-----
|
446 |
+
To replace/update edge data, use the optional key argument
|
447 |
+
to identify a unique edge. Otherwise a new edge will be created.
|
448 |
+
|
449 |
+
NetworkX algorithms designed for weighted graphs cannot use
|
450 |
+
multigraphs directly because it is not clear how to handle
|
451 |
+
multiedge weights. Convert to Graph using edge attribute
|
452 |
+
'weight' to enable weighted graph algorithms.
|
453 |
+
|
454 |
+
Default keys are generated using the method `new_edge_key()`.
|
455 |
+
This method can be overridden by subclassing the base class and
|
456 |
+
providing a custom `new_edge_key()` method.
|
457 |
+
|
458 |
+
Examples
|
459 |
+
--------
|
460 |
+
The following all add the edge e=(1, 2) to graph G:
|
461 |
+
|
462 |
+
>>> G = nx.MultiDiGraph()
|
463 |
+
>>> e = (1, 2)
|
464 |
+
>>> key = G.add_edge(1, 2) # explicit two-node form
|
465 |
+
>>> G.add_edge(*e) # single edge as tuple of two nodes
|
466 |
+
1
|
467 |
+
>>> G.add_edges_from([(1, 2)]) # add edges from iterable container
|
468 |
+
[2]
|
469 |
+
|
470 |
+
Associate data to edges using keywords:
|
471 |
+
|
472 |
+
>>> key = G.add_edge(1, 2, weight=3)
|
473 |
+
>>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
|
474 |
+
>>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
|
475 |
+
|
476 |
+
For non-string attribute keys, use subscript notation.
|
477 |
+
|
478 |
+
>>> ekey = G.add_edge(1, 2)
|
479 |
+
>>> G[1][2][0].update({0: 5})
|
480 |
+
>>> G.edges[1, 2, 0].update({0: 5})
|
481 |
+
"""
|
482 |
+
u, v = u_for_edge, v_for_edge
|
483 |
+
# add nodes
|
484 |
+
if u not in self._succ:
|
485 |
+
if u is None:
|
486 |
+
raise ValueError("None cannot be a node")
|
487 |
+
self._succ[u] = self.adjlist_inner_dict_factory()
|
488 |
+
self._pred[u] = self.adjlist_inner_dict_factory()
|
489 |
+
self._node[u] = self.node_attr_dict_factory()
|
490 |
+
if v not in self._succ:
|
491 |
+
if v is None:
|
492 |
+
raise ValueError("None cannot be a node")
|
493 |
+
self._succ[v] = self.adjlist_inner_dict_factory()
|
494 |
+
self._pred[v] = self.adjlist_inner_dict_factory()
|
495 |
+
self._node[v] = self.node_attr_dict_factory()
|
496 |
+
if key is None:
|
497 |
+
key = self.new_edge_key(u, v)
|
498 |
+
if v in self._succ[u]:
|
499 |
+
keydict = self._adj[u][v]
|
500 |
+
datadict = keydict.get(key, self.edge_attr_dict_factory())
|
501 |
+
datadict.update(attr)
|
502 |
+
keydict[key] = datadict
|
503 |
+
else:
|
504 |
+
# selfloops work this way without special treatment
|
505 |
+
datadict = self.edge_attr_dict_factory()
|
506 |
+
datadict.update(attr)
|
507 |
+
keydict = self.edge_key_dict_factory()
|
508 |
+
keydict[key] = datadict
|
509 |
+
self._succ[u][v] = keydict
|
510 |
+
self._pred[v][u] = keydict
|
511 |
+
nx._clear_cache(self)
|
512 |
+
return key
|
513 |
+
|
514 |
+
def remove_edge(self, u, v, key=None):
|
515 |
+
"""Remove an edge between u and v.
|
516 |
+
|
517 |
+
Parameters
|
518 |
+
----------
|
519 |
+
u, v : nodes
|
520 |
+
Remove an edge between nodes u and v.
|
521 |
+
key : hashable identifier, optional (default=None)
|
522 |
+
Used to distinguish multiple edges between a pair of nodes.
|
523 |
+
If None, remove a single edge between u and v. If there are
|
524 |
+
multiple edges, removes the last edge added in terms of
|
525 |
+
insertion order.
|
526 |
+
|
527 |
+
Raises
|
528 |
+
------
|
529 |
+
NetworkXError
|
530 |
+
If there is not an edge between u and v, or
|
531 |
+
if there is no edge with the specified key.
|
532 |
+
|
533 |
+
See Also
|
534 |
+
--------
|
535 |
+
remove_edges_from : remove a collection of edges
|
536 |
+
|
537 |
+
Examples
|
538 |
+
--------
|
539 |
+
>>> G = nx.MultiDiGraph()
|
540 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
541 |
+
>>> G.remove_edge(0, 1)
|
542 |
+
>>> e = (1, 2)
|
543 |
+
>>> G.remove_edge(*e) # unpacks e from an edge tuple
|
544 |
+
|
545 |
+
For multiple edges
|
546 |
+
|
547 |
+
>>> G = nx.MultiDiGraph()
|
548 |
+
>>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
|
549 |
+
[0, 1, 2]
|
550 |
+
|
551 |
+
When ``key=None`` (the default), edges are removed in the opposite
|
552 |
+
order that they were added:
|
553 |
+
|
554 |
+
>>> G.remove_edge(1, 2)
|
555 |
+
>>> G.edges(keys=True)
|
556 |
+
OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
|
557 |
+
|
558 |
+
For edges with keys
|
559 |
+
|
560 |
+
>>> G = nx.MultiDiGraph()
|
561 |
+
>>> G.add_edge(1, 2, key="first")
|
562 |
+
'first'
|
563 |
+
>>> G.add_edge(1, 2, key="second")
|
564 |
+
'second'
|
565 |
+
>>> G.remove_edge(1, 2, key="first")
|
566 |
+
>>> G.edges(keys=True)
|
567 |
+
OutMultiEdgeView([(1, 2, 'second')])
|
568 |
+
|
569 |
+
"""
|
570 |
+
try:
|
571 |
+
d = self._adj[u][v]
|
572 |
+
except KeyError as err:
|
573 |
+
raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
|
574 |
+
# remove the edge with specified data
|
575 |
+
if key is None:
|
576 |
+
d.popitem()
|
577 |
+
else:
|
578 |
+
try:
|
579 |
+
del d[key]
|
580 |
+
except KeyError as err:
|
581 |
+
msg = f"The edge {u}-{v} with key {key} is not in the graph."
|
582 |
+
raise NetworkXError(msg) from err
|
583 |
+
if len(d) == 0:
|
584 |
+
# remove the key entries if last edge
|
585 |
+
del self._succ[u][v]
|
586 |
+
del self._pred[v][u]
|
587 |
+
nx._clear_cache(self)
|
588 |
+
|
589 |
+
@cached_property
|
590 |
+
def edges(self):
|
591 |
+
"""An OutMultiEdgeView of the Graph as G.edges or G.edges().
|
592 |
+
|
593 |
+
edges(self, nbunch=None, data=False, keys=False, default=None)
|
594 |
+
|
595 |
+
The OutMultiEdgeView provides set-like operations on the edge-tuples
|
596 |
+
as well as edge attribute lookup. When called, it also provides
|
597 |
+
an EdgeDataView object which allows control of access to edge
|
598 |
+
attributes (but does not provide set-like operations).
|
599 |
+
Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
|
600 |
+
attribute for the edge from ``u`` to ``v`` with key ``k`` while
|
601 |
+
``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
|
602 |
+
iterates through all the edges yielding the color attribute with
|
603 |
+
default `'red'` if no color attribute exists.
|
604 |
+
|
605 |
+
Edges are returned as tuples with optional data and keys
|
606 |
+
in the order (node, neighbor, key, data). If ``keys=True`` is not
|
607 |
+
provided, the tuples will just be (node, neighbor, data), but
|
608 |
+
multiple tuples with the same node and neighbor will be
|
609 |
+
generated when multiple edges between two nodes exist.
|
610 |
+
|
611 |
+
Parameters
|
612 |
+
----------
|
613 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
614 |
+
The view will only report edges from these nodes.
|
615 |
+
data : string or bool, optional (default=False)
|
616 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
617 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
618 |
+
If False, return 2-tuple (u, v).
|
619 |
+
keys : bool, optional (default=False)
|
620 |
+
If True, return edge keys with each edge, creating (u, v, k,
|
621 |
+
d) tuples when data is also requested (the default) and (u,
|
622 |
+
v, k) tuples when data is not requested.
|
623 |
+
default : value, optional (default=None)
|
624 |
+
Value used for edges that don't have the requested attribute.
|
625 |
+
Only relevant if data is not True or False.
|
626 |
+
|
627 |
+
Returns
|
628 |
+
-------
|
629 |
+
edges : OutMultiEdgeView
|
630 |
+
A view of edge attributes, usually it iterates over (u, v)
|
631 |
+
(u, v, k) or (u, v, k, d) tuples of edges, but can also be
|
632 |
+
used for attribute lookup as ``edges[u, v, k]['foo']``.
|
633 |
+
|
634 |
+
Notes
|
635 |
+
-----
|
636 |
+
Nodes in nbunch that are not in the graph will be (quietly) ignored.
|
637 |
+
For directed graphs this returns the out-edges.
|
638 |
+
|
639 |
+
Examples
|
640 |
+
--------
|
641 |
+
>>> G = nx.MultiDiGraph()
|
642 |
+
>>> nx.add_path(G, [0, 1, 2])
|
643 |
+
>>> key = G.add_edge(2, 3, weight=5)
|
644 |
+
>>> key2 = G.add_edge(1, 2) # second edge between these nodes
|
645 |
+
>>> [e for e in G.edges()]
|
646 |
+
[(0, 1), (1, 2), (1, 2), (2, 3)]
|
647 |
+
>>> list(G.edges(data=True)) # default data is {} (empty dict)
|
648 |
+
[(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
|
649 |
+
>>> list(G.edges(data="weight", default=1))
|
650 |
+
[(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
|
651 |
+
>>> list(G.edges(keys=True)) # default keys are integers
|
652 |
+
[(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
|
653 |
+
>>> list(G.edges(data=True, keys=True))
|
654 |
+
[(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
|
655 |
+
>>> list(G.edges(data="weight", default=1, keys=True))
|
656 |
+
[(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
|
657 |
+
>>> list(G.edges([0, 2]))
|
658 |
+
[(0, 1), (2, 3)]
|
659 |
+
>>> list(G.edges(0))
|
660 |
+
[(0, 1)]
|
661 |
+
>>> list(G.edges(1))
|
662 |
+
[(1, 2), (1, 2)]
|
663 |
+
|
664 |
+
See Also
|
665 |
+
--------
|
666 |
+
in_edges, out_edges
|
667 |
+
"""
|
668 |
+
return OutMultiEdgeView(self)
|
669 |
+
|
670 |
+
# alias out_edges to edges
|
671 |
+
@cached_property
|
672 |
+
def out_edges(self):
|
673 |
+
return OutMultiEdgeView(self)
|
674 |
+
|
675 |
+
out_edges.__doc__ = edges.__doc__
|
676 |
+
|
677 |
+
@cached_property
|
678 |
+
def in_edges(self):
|
679 |
+
"""A view of the in edges of the graph as G.in_edges or G.in_edges().
|
680 |
+
|
681 |
+
in_edges(self, nbunch=None, data=False, keys=False, default=None)
|
682 |
+
|
683 |
+
Parameters
|
684 |
+
----------
|
685 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
686 |
+
The view will only report edges incident to these nodes.
|
687 |
+
data : string or bool, optional (default=False)
|
688 |
+
The edge attribute returned in 3-tuple (u, v, ddict[data]).
|
689 |
+
If True, return edge attribute dict in 3-tuple (u, v, ddict).
|
690 |
+
If False, return 2-tuple (u, v).
|
691 |
+
keys : bool, optional (default=False)
|
692 |
+
If True, return edge keys with each edge, creating 3-tuples
|
693 |
+
(u, v, k) or with data, 4-tuples (u, v, k, d).
|
694 |
+
default : value, optional (default=None)
|
695 |
+
Value used for edges that don't have the requested attribute.
|
696 |
+
Only relevant if data is not True or False.
|
697 |
+
|
698 |
+
Returns
|
699 |
+
-------
|
700 |
+
in_edges : InMultiEdgeView or InMultiEdgeDataView
|
701 |
+
A view of edge attributes, usually it iterates over (u, v)
|
702 |
+
or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
|
703 |
+
used for attribute lookup as `edges[u, v, k]['foo']`.
|
704 |
+
|
705 |
+
See Also
|
706 |
+
--------
|
707 |
+
edges
|
708 |
+
"""
|
709 |
+
return InMultiEdgeView(self)
|
710 |
+
|
711 |
+
@cached_property
|
712 |
+
def degree(self):
|
713 |
+
"""A DegreeView for the Graph as G.degree or G.degree().
|
714 |
+
|
715 |
+
The node degree is the number of edges adjacent to the node.
|
716 |
+
The weighted node degree is the sum of the edge weights for
|
717 |
+
edges incident to that node.
|
718 |
+
|
719 |
+
This object provides an iterator for (node, degree) as well as
|
720 |
+
lookup for the degree for a single node.
|
721 |
+
|
722 |
+
Parameters
|
723 |
+
----------
|
724 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
725 |
+
The view will only report edges incident to these nodes.
|
726 |
+
|
727 |
+
weight : string or None, optional (default=None)
|
728 |
+
The name of an edge attribute that holds the numerical value used
|
729 |
+
as a weight. If None, then each edge has weight 1.
|
730 |
+
The degree is the sum of the edge weights adjacent to the node.
|
731 |
+
|
732 |
+
Returns
|
733 |
+
-------
|
734 |
+
DiMultiDegreeView or int
|
735 |
+
If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
|
736 |
+
mapping nodes to their degree.
|
737 |
+
If a single node is requested, returns the degree of the node as an integer.
|
738 |
+
|
739 |
+
See Also
|
740 |
+
--------
|
741 |
+
out_degree, in_degree
|
742 |
+
|
743 |
+
Examples
|
744 |
+
--------
|
745 |
+
>>> G = nx.MultiDiGraph()
|
746 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
747 |
+
>>> G.degree(0) # node 0 with degree 1
|
748 |
+
1
|
749 |
+
>>> list(G.degree([0, 1, 2]))
|
750 |
+
[(0, 1), (1, 2), (2, 2)]
|
751 |
+
>>> G.add_edge(0, 1) # parallel edge
|
752 |
+
1
|
753 |
+
>>> list(G.degree([0, 1, 2])) # parallel edges are counted
|
754 |
+
[(0, 2), (1, 3), (2, 2)]
|
755 |
+
|
756 |
+
"""
|
757 |
+
return DiMultiDegreeView(self)
|
758 |
+
|
759 |
+
@cached_property
|
760 |
+
def in_degree(self):
|
761 |
+
"""A DegreeView for (node, in_degree) or in_degree for single node.
|
762 |
+
|
763 |
+
The node in-degree is the number of edges pointing into the node.
|
764 |
+
The weighted node degree is the sum of the edge weights for
|
765 |
+
edges incident to that node.
|
766 |
+
|
767 |
+
This object provides an iterator for (node, degree) as well as
|
768 |
+
lookup for the degree for a single node.
|
769 |
+
|
770 |
+
Parameters
|
771 |
+
----------
|
772 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
773 |
+
The view will only report edges incident to these nodes.
|
774 |
+
|
775 |
+
weight : string or None, optional (default=None)
|
776 |
+
The edge attribute that holds the numerical value used
|
777 |
+
as a weight. If None, then each edge has weight 1.
|
778 |
+
The degree is the sum of the edge weights adjacent to the node.
|
779 |
+
|
780 |
+
Returns
|
781 |
+
-------
|
782 |
+
If a single node is requested
|
783 |
+
deg : int
|
784 |
+
Degree of the node
|
785 |
+
|
786 |
+
OR if multiple nodes are requested
|
787 |
+
nd_iter : iterator
|
788 |
+
The iterator returns two-tuples of (node, in-degree).
|
789 |
+
|
790 |
+
See Also
|
791 |
+
--------
|
792 |
+
degree, out_degree
|
793 |
+
|
794 |
+
Examples
|
795 |
+
--------
|
796 |
+
>>> G = nx.MultiDiGraph()
|
797 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
798 |
+
>>> G.in_degree(0) # node 0 with degree 0
|
799 |
+
0
|
800 |
+
>>> list(G.in_degree([0, 1, 2]))
|
801 |
+
[(0, 0), (1, 1), (2, 1)]
|
802 |
+
>>> G.add_edge(0, 1) # parallel edge
|
803 |
+
1
|
804 |
+
>>> list(G.in_degree([0, 1, 2])) # parallel edges counted
|
805 |
+
[(0, 0), (1, 2), (2, 1)]
|
806 |
+
|
807 |
+
"""
|
808 |
+
return InMultiDegreeView(self)
|
809 |
+
|
810 |
+
@cached_property
|
811 |
+
def out_degree(self):
|
812 |
+
"""Returns an iterator for (node, out-degree) or out-degree for single node.
|
813 |
+
|
814 |
+
out_degree(self, nbunch=None, weight=None)
|
815 |
+
|
816 |
+
The node out-degree is the number of edges pointing out of the node.
|
817 |
+
This function returns the out-degree for a single node or an iterator
|
818 |
+
for a bunch of nodes or if nothing is passed as argument.
|
819 |
+
|
820 |
+
Parameters
|
821 |
+
----------
|
822 |
+
nbunch : single node, container, or all nodes (default= all nodes)
|
823 |
+
The view will only report edges incident to these nodes.
|
824 |
+
|
825 |
+
weight : string or None, optional (default=None)
|
826 |
+
The edge attribute that holds the numerical value used
|
827 |
+
as a weight. If None, then each edge has weight 1.
|
828 |
+
The degree is the sum of the edge weights.
|
829 |
+
|
830 |
+
Returns
|
831 |
+
-------
|
832 |
+
If a single node is requested
|
833 |
+
deg : int
|
834 |
+
Degree of the node
|
835 |
+
|
836 |
+
OR if multiple nodes are requested
|
837 |
+
nd_iter : iterator
|
838 |
+
The iterator returns two-tuples of (node, out-degree).
|
839 |
+
|
840 |
+
See Also
|
841 |
+
--------
|
842 |
+
degree, in_degree
|
843 |
+
|
844 |
+
Examples
|
845 |
+
--------
|
846 |
+
>>> G = nx.MultiDiGraph()
|
847 |
+
>>> nx.add_path(G, [0, 1, 2, 3])
|
848 |
+
>>> G.out_degree(0) # node 0 with degree 1
|
849 |
+
1
|
850 |
+
>>> list(G.out_degree([0, 1, 2]))
|
851 |
+
[(0, 1), (1, 1), (2, 1)]
|
852 |
+
>>> G.add_edge(0, 1) # parallel edge
|
853 |
+
1
|
854 |
+
>>> list(G.out_degree([0, 1, 2])) # counts parallel edges
|
855 |
+
[(0, 2), (1, 1), (2, 1)]
|
856 |
+
|
857 |
+
"""
|
858 |
+
return OutMultiDegreeView(self)
|
859 |
+
|
860 |
+
def is_multigraph(self):
|
861 |
+
"""Returns True if graph is a multigraph, False otherwise."""
|
862 |
+
return True
|
863 |
+
|
864 |
+
def is_directed(self):
|
865 |
+
"""Returns True if graph is directed, False otherwise."""
|
866 |
+
return True
|
867 |
+
|
868 |
+
def to_undirected(self, reciprocal=False, as_view=False):
|
869 |
+
"""Returns an undirected representation of the digraph.
|
870 |
+
|
871 |
+
Parameters
|
872 |
+
----------
|
873 |
+
reciprocal : bool (optional)
|
874 |
+
If True only keep edges that appear in both directions
|
875 |
+
in the original digraph.
|
876 |
+
as_view : bool (optional, default=False)
|
877 |
+
If True return an undirected view of the original directed graph.
|
878 |
+
|
879 |
+
Returns
|
880 |
+
-------
|
881 |
+
G : MultiGraph
|
882 |
+
An undirected graph with the same name and nodes and
|
883 |
+
with edge (u, v, data) if either (u, v, data) or (v, u, data)
|
884 |
+
is in the digraph. If both edges exist in digraph and
|
885 |
+
their edge data is different, only one edge is created
|
886 |
+
with an arbitrary choice of which edge data to use.
|
887 |
+
You must check and correct for this manually if desired.
|
888 |
+
|
889 |
+
See Also
|
890 |
+
--------
|
891 |
+
MultiGraph, copy, add_edge, add_edges_from
|
892 |
+
|
893 |
+
Notes
|
894 |
+
-----
|
895 |
+
This returns a "deepcopy" of the edge, node, and
|
896 |
+
graph attributes which attempts to completely copy
|
897 |
+
all of the data and references.
|
898 |
+
|
899 |
+
This is in contrast to the similar D=MultiDiGraph(G) which
|
900 |
+
returns a shallow copy of the data.
|
901 |
+
|
902 |
+
See the Python copy module for more information on shallow
|
903 |
+
and deep copies, https://docs.python.org/3/library/copy.html.
|
904 |
+
|
905 |
+
Warning: If you have subclassed MultiDiGraph to use dict-like
|
906 |
+
objects in the data structure, those changes do not transfer
|
907 |
+
to the MultiGraph created by this method.
|
908 |
+
|
909 |
+
Examples
|
910 |
+
--------
|
911 |
+
>>> G = nx.path_graph(2) # or MultiGraph, etc
|
912 |
+
>>> H = G.to_directed()
|
913 |
+
>>> list(H.edges)
|
914 |
+
[(0, 1), (1, 0)]
|
915 |
+
>>> G2 = H.to_undirected()
|
916 |
+
>>> list(G2.edges)
|
917 |
+
[(0, 1)]
|
918 |
+
"""
|
919 |
+
graph_class = self.to_undirected_class()
|
920 |
+
if as_view is True:
|
921 |
+
return nx.graphviews.generic_graph_view(self, graph_class)
|
922 |
+
# deepcopy when not a view
|
923 |
+
G = graph_class()
|
924 |
+
G.graph.update(deepcopy(self.graph))
|
925 |
+
G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
926 |
+
if reciprocal is True:
|
927 |
+
G.add_edges_from(
|
928 |
+
(u, v, key, deepcopy(data))
|
929 |
+
for u, nbrs in self._adj.items()
|
930 |
+
for v, keydict in nbrs.items()
|
931 |
+
for key, data in keydict.items()
|
932 |
+
if v in self._pred[u] and key in self._pred[u][v]
|
933 |
+
)
|
934 |
+
else:
|
935 |
+
G.add_edges_from(
|
936 |
+
(u, v, key, deepcopy(data))
|
937 |
+
for u, nbrs in self._adj.items()
|
938 |
+
for v, keydict in nbrs.items()
|
939 |
+
for key, data in keydict.items()
|
940 |
+
)
|
941 |
+
return G
|
942 |
+
|
943 |
+
def reverse(self, copy=True):
|
944 |
+
"""Returns the reverse of the graph.
|
945 |
+
|
946 |
+
The reverse is a graph with the same nodes and edges
|
947 |
+
but with the directions of the edges reversed.
|
948 |
+
|
949 |
+
Parameters
|
950 |
+
----------
|
951 |
+
copy : bool optional (default=True)
|
952 |
+
If True, return a new DiGraph holding the reversed edges.
|
953 |
+
If False, the reverse graph is created using a view of
|
954 |
+
the original graph.
|
955 |
+
"""
|
956 |
+
if copy:
|
957 |
+
H = self.__class__()
|
958 |
+
H.graph.update(deepcopy(self.graph))
|
959 |
+
H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
|
960 |
+
H.add_edges_from(
|
961 |
+
(v, u, k, deepcopy(d))
|
962 |
+
for u, v, k, d in self.edges(keys=True, data=True)
|
963 |
+
)
|
964 |
+
return H
|
965 |
+
return nx.reverse_view(self)
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (195 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/dispatch_interface.cpython-310.pyc
ADDED
Binary file (4.98 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/historical_tests.cpython-310.pyc
ADDED
Binary file (14 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_coreviews.cpython-310.pyc
ADDED
Binary file (13.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_digraph.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_filters.cpython-310.pyc
ADDED
Binary file (5.05 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graph.cpython-310.pyc
ADDED
Binary file (31.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_graphviews.cpython-310.pyc
ADDED
Binary file (13.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_multidigraph.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_reportviews.cpython-310.pyc
ADDED
Binary file (41.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_special.cpython-310.pyc
ADDED
Binary file (5.18 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/__pycache__/test_subgraphviews.cpython-310.pyc
ADDED
Binary file (12.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/dispatch_interface.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file contains utilities for testing the dispatching feature
|
2 |
+
|
3 |
+
# A full test of all dispatchable algorithms is performed by
|
4 |
+
# modifying the pytest invocation and setting an environment variable
|
5 |
+
# NETWORKX_TEST_BACKEND=nx-loopback pytest
|
6 |
+
# This is comprehensive, but only tests the `test_override_dispatch`
|
7 |
+
# function in networkx.classes.backends.
|
8 |
+
|
9 |
+
# To test the `_dispatchable` function directly, several tests scattered throughout
|
10 |
+
# NetworkX have been augmented to test normal and dispatch mode.
|
11 |
+
# Searching for `dispatch_interface` should locate the specific tests.
|
12 |
+
|
13 |
+
import networkx as nx
|
14 |
+
from networkx import DiGraph, Graph, MultiDiGraph, MultiGraph, PlanarEmbedding
|
15 |
+
from networkx.classes.reportviews import NodeView
|
16 |
+
|
17 |
+
|
18 |
+
class LoopbackGraph(Graph):
|
19 |
+
__networkx_backend__ = "nx-loopback"
|
20 |
+
|
21 |
+
|
22 |
+
class LoopbackDiGraph(DiGraph):
|
23 |
+
__networkx_backend__ = "nx-loopback"
|
24 |
+
|
25 |
+
|
26 |
+
class LoopbackMultiGraph(MultiGraph):
|
27 |
+
__networkx_backend__ = "nx-loopback"
|
28 |
+
|
29 |
+
|
30 |
+
class LoopbackMultiDiGraph(MultiDiGraph):
|
31 |
+
__networkx_backend__ = "nx-loopback"
|
32 |
+
|
33 |
+
|
34 |
+
class LoopbackPlanarEmbedding(PlanarEmbedding):
|
35 |
+
__networkx_backend__ = "nx-loopback"
|
36 |
+
|
37 |
+
|
38 |
+
def convert(graph):
|
39 |
+
if isinstance(graph, PlanarEmbedding):
|
40 |
+
return LoopbackPlanarEmbedding(graph)
|
41 |
+
if isinstance(graph, MultiDiGraph):
|
42 |
+
return LoopbackMultiDiGraph(graph)
|
43 |
+
if isinstance(graph, MultiGraph):
|
44 |
+
return LoopbackMultiGraph(graph)
|
45 |
+
if isinstance(graph, DiGraph):
|
46 |
+
return LoopbackDiGraph(graph)
|
47 |
+
if isinstance(graph, Graph):
|
48 |
+
return LoopbackGraph(graph)
|
49 |
+
raise TypeError(f"Unsupported type of graph: {type(graph)}")
|
50 |
+
|
51 |
+
|
52 |
+
class LoopbackDispatcher:
|
53 |
+
def __getattr__(self, item):
|
54 |
+
try:
|
55 |
+
return nx.utils.backends._registered_algorithms[item].orig_func
|
56 |
+
except KeyError:
|
57 |
+
raise AttributeError(item) from None
|
58 |
+
|
59 |
+
@staticmethod
|
60 |
+
def convert_from_nx(
|
61 |
+
graph,
|
62 |
+
*,
|
63 |
+
edge_attrs=None,
|
64 |
+
node_attrs=None,
|
65 |
+
preserve_edge_attrs=None,
|
66 |
+
preserve_node_attrs=None,
|
67 |
+
preserve_graph_attrs=None,
|
68 |
+
name=None,
|
69 |
+
graph_name=None,
|
70 |
+
):
|
71 |
+
if name in {
|
72 |
+
# Raise if input graph changes
|
73 |
+
"lexicographical_topological_sort",
|
74 |
+
"topological_generations",
|
75 |
+
"topological_sort",
|
76 |
+
# Sensitive tests (iteration order matters)
|
77 |
+
"dfs_labeled_edges",
|
78 |
+
}:
|
79 |
+
return graph
|
80 |
+
if isinstance(graph, NodeView):
|
81 |
+
# Convert to a Graph with only nodes (no edges)
|
82 |
+
new_graph = Graph()
|
83 |
+
new_graph.add_nodes_from(graph.items())
|
84 |
+
graph = new_graph
|
85 |
+
G = LoopbackGraph()
|
86 |
+
elif not isinstance(graph, Graph):
|
87 |
+
raise TypeError(
|
88 |
+
f"Bad type for graph argument {graph_name} in {name}: {type(graph)}"
|
89 |
+
)
|
90 |
+
elif graph.__class__ in {Graph, LoopbackGraph}:
|
91 |
+
G = LoopbackGraph()
|
92 |
+
elif graph.__class__ in {DiGraph, LoopbackDiGraph}:
|
93 |
+
G = LoopbackDiGraph()
|
94 |
+
elif graph.__class__ in {MultiGraph, LoopbackMultiGraph}:
|
95 |
+
G = LoopbackMultiGraph()
|
96 |
+
elif graph.__class__ in {MultiDiGraph, LoopbackMultiDiGraph}:
|
97 |
+
G = LoopbackMultiDiGraph()
|
98 |
+
elif graph.__class__ in {PlanarEmbedding, LoopbackPlanarEmbedding}:
|
99 |
+
G = LoopbackDiGraph() # or LoopbackPlanarEmbedding
|
100 |
+
else:
|
101 |
+
# It would be nice to be able to convert _AntiGraph to a regular Graph
|
102 |
+
# nx.algorithms.approximation.kcomponents._AntiGraph
|
103 |
+
# nx.algorithms.tree.branchings.MultiDiGraph_EdgeKey
|
104 |
+
# nx.classes.tests.test_multidigraph.MultiDiGraphSubClass
|
105 |
+
# nx.classes.tests.test_multigraph.MultiGraphSubClass
|
106 |
+
G = graph.__class__()
|
107 |
+
|
108 |
+
if preserve_graph_attrs:
|
109 |
+
G.graph.update(graph.graph)
|
110 |
+
|
111 |
+
if preserve_node_attrs:
|
112 |
+
G.add_nodes_from(graph.nodes(data=True))
|
113 |
+
elif node_attrs:
|
114 |
+
G.add_nodes_from(
|
115 |
+
(
|
116 |
+
node,
|
117 |
+
{
|
118 |
+
k: datadict.get(k, default)
|
119 |
+
for k, default in node_attrs.items()
|
120 |
+
if default is not None or k in datadict
|
121 |
+
},
|
122 |
+
)
|
123 |
+
for node, datadict in graph.nodes(data=True)
|
124 |
+
)
|
125 |
+
else:
|
126 |
+
G.add_nodes_from(graph)
|
127 |
+
|
128 |
+
if graph.is_multigraph():
|
129 |
+
if preserve_edge_attrs:
|
130 |
+
G.add_edges_from(
|
131 |
+
(u, v, key, datadict)
|
132 |
+
for u, nbrs in graph._adj.items()
|
133 |
+
for v, keydict in nbrs.items()
|
134 |
+
for key, datadict in keydict.items()
|
135 |
+
)
|
136 |
+
elif edge_attrs:
|
137 |
+
G.add_edges_from(
|
138 |
+
(
|
139 |
+
u,
|
140 |
+
v,
|
141 |
+
key,
|
142 |
+
{
|
143 |
+
k: datadict.get(k, default)
|
144 |
+
for k, default in edge_attrs.items()
|
145 |
+
if default is not None or k in datadict
|
146 |
+
},
|
147 |
+
)
|
148 |
+
for u, nbrs in graph._adj.items()
|
149 |
+
for v, keydict in nbrs.items()
|
150 |
+
for key, datadict in keydict.items()
|
151 |
+
)
|
152 |
+
else:
|
153 |
+
G.add_edges_from(
|
154 |
+
(u, v, key, {})
|
155 |
+
for u, nbrs in graph._adj.items()
|
156 |
+
for v, keydict in nbrs.items()
|
157 |
+
for key, datadict in keydict.items()
|
158 |
+
)
|
159 |
+
elif preserve_edge_attrs:
|
160 |
+
G.add_edges_from(graph.edges(data=True))
|
161 |
+
elif edge_attrs:
|
162 |
+
G.add_edges_from(
|
163 |
+
(
|
164 |
+
u,
|
165 |
+
v,
|
166 |
+
{
|
167 |
+
k: datadict.get(k, default)
|
168 |
+
for k, default in edge_attrs.items()
|
169 |
+
if default is not None or k in datadict
|
170 |
+
},
|
171 |
+
)
|
172 |
+
for u, v, datadict in graph.edges(data=True)
|
173 |
+
)
|
174 |
+
else:
|
175 |
+
G.add_edges_from(graph.edges)
|
176 |
+
return G
|
177 |
+
|
178 |
+
@staticmethod
|
179 |
+
def convert_to_nx(obj, *, name=None):
|
180 |
+
return obj
|
181 |
+
|
182 |
+
@staticmethod
|
183 |
+
def on_start_tests(items):
|
184 |
+
# Verify that items can be xfailed
|
185 |
+
for item in items:
|
186 |
+
assert hasattr(item, "add_marker")
|
187 |
+
|
188 |
+
def can_run(self, name, args, kwargs):
|
189 |
+
# It is unnecessary to define this function if algorithms are fully supported.
|
190 |
+
# We include it for illustration purposes.
|
191 |
+
return hasattr(self, name)
|
192 |
+
|
193 |
+
|
194 |
+
dispatcher = LoopbackDispatcher()
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/historical_tests.py
ADDED
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Original NetworkX graph tests"""
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import networkx as nx
|
5 |
+
from networkx import convert_node_labels_to_integers as cnlti
|
6 |
+
from networkx.utils import edges_equal, nodes_equal
|
7 |
+
|
8 |
+
|
9 |
+
class HistoricalTests:
|
10 |
+
@classmethod
|
11 |
+
def setup_class(cls):
|
12 |
+
cls.null = nx.null_graph()
|
13 |
+
cls.P1 = cnlti(nx.path_graph(1), first_label=1)
|
14 |
+
cls.P3 = cnlti(nx.path_graph(3), first_label=1)
|
15 |
+
cls.P10 = cnlti(nx.path_graph(10), first_label=1)
|
16 |
+
cls.K1 = cnlti(nx.complete_graph(1), first_label=1)
|
17 |
+
cls.K3 = cnlti(nx.complete_graph(3), first_label=1)
|
18 |
+
cls.K4 = cnlti(nx.complete_graph(4), first_label=1)
|
19 |
+
cls.K5 = cnlti(nx.complete_graph(5), first_label=1)
|
20 |
+
cls.K10 = cnlti(nx.complete_graph(10), first_label=1)
|
21 |
+
cls.G = nx.Graph
|
22 |
+
|
23 |
+
def test_name(self):
|
24 |
+
G = self.G(name="test")
|
25 |
+
assert G.name == "test"
|
26 |
+
H = self.G()
|
27 |
+
assert H.name == ""
|
28 |
+
|
29 |
+
# Nodes
|
30 |
+
|
31 |
+
def test_add_remove_node(self):
|
32 |
+
G = self.G()
|
33 |
+
G.add_node("A")
|
34 |
+
assert G.has_node("A")
|
35 |
+
G.remove_node("A")
|
36 |
+
assert not G.has_node("A")
|
37 |
+
|
38 |
+
def test_nonhashable_node(self):
|
39 |
+
# Test if a non-hashable object is in the Graph. A python dict will
|
40 |
+
# raise a TypeError, but for a Graph class a simple False should be
|
41 |
+
# returned (see Graph __contains__). If it cannot be a node then it is
|
42 |
+
# not a node.
|
43 |
+
G = self.G()
|
44 |
+
assert not G.has_node(["A"])
|
45 |
+
assert not G.has_node({"A": 1})
|
46 |
+
|
47 |
+
def test_add_nodes_from(self):
|
48 |
+
G = self.G()
|
49 |
+
G.add_nodes_from(list("ABCDEFGHIJKL"))
|
50 |
+
assert G.has_node("L")
|
51 |
+
G.remove_nodes_from(["H", "I", "J", "K", "L"])
|
52 |
+
G.add_nodes_from([1, 2, 3, 4])
|
53 |
+
assert sorted(G.nodes(), key=str) == [
|
54 |
+
1,
|
55 |
+
2,
|
56 |
+
3,
|
57 |
+
4,
|
58 |
+
"A",
|
59 |
+
"B",
|
60 |
+
"C",
|
61 |
+
"D",
|
62 |
+
"E",
|
63 |
+
"F",
|
64 |
+
"G",
|
65 |
+
]
|
66 |
+
# test __iter__
|
67 |
+
assert sorted(G, key=str) == [1, 2, 3, 4, "A", "B", "C", "D", "E", "F", "G"]
|
68 |
+
|
69 |
+
def test_contains(self):
|
70 |
+
G = self.G()
|
71 |
+
G.add_node("A")
|
72 |
+
assert "A" in G
|
73 |
+
assert [] not in G # never raise a Key or TypeError in this test
|
74 |
+
assert {1: 1} not in G
|
75 |
+
|
76 |
+
def test_add_remove(self):
|
77 |
+
# Test add_node and remove_node acting for various nbunch
|
78 |
+
G = self.G()
|
79 |
+
G.add_node("m")
|
80 |
+
assert G.has_node("m")
|
81 |
+
G.add_node("m") # no complaints
|
82 |
+
pytest.raises(nx.NetworkXError, G.remove_node, "j")
|
83 |
+
G.remove_node("m")
|
84 |
+
assert list(G) == []
|
85 |
+
|
86 |
+
def test_nbunch_is_list(self):
|
87 |
+
G = self.G()
|
88 |
+
G.add_nodes_from(list("ABCD"))
|
89 |
+
G.add_nodes_from(self.P3) # add nbunch of nodes (nbunch=Graph)
|
90 |
+
assert sorted(G.nodes(), key=str) == [1, 2, 3, "A", "B", "C", "D"]
|
91 |
+
G.remove_nodes_from(self.P3) # remove nbunch of nodes (nbunch=Graph)
|
92 |
+
assert sorted(G.nodes(), key=str) == ["A", "B", "C", "D"]
|
93 |
+
|
94 |
+
def test_nbunch_is_set(self):
|
95 |
+
G = self.G()
|
96 |
+
nbunch = set("ABCDEFGHIJKL")
|
97 |
+
G.add_nodes_from(nbunch)
|
98 |
+
assert G.has_node("L")
|
99 |
+
|
100 |
+
def test_nbunch_dict(self):
|
101 |
+
# nbunch is a dict with nodes as keys
|
102 |
+
G = self.G()
|
103 |
+
nbunch = set("ABCDEFGHIJKL")
|
104 |
+
G.add_nodes_from(nbunch)
|
105 |
+
nbunch = {"I": "foo", "J": 2, "K": True, "L": "spam"}
|
106 |
+
G.remove_nodes_from(nbunch)
|
107 |
+
assert sorted(G.nodes(), key=str), ["A", "B", "C", "D", "E", "F", "G", "H"]
|
108 |
+
|
109 |
+
def test_nbunch_iterator(self):
|
110 |
+
G = self.G()
|
111 |
+
G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
|
112 |
+
n_iter = self.P3.nodes()
|
113 |
+
G.add_nodes_from(n_iter)
|
114 |
+
assert sorted(G.nodes(), key=str) == [
|
115 |
+
1,
|
116 |
+
2,
|
117 |
+
3,
|
118 |
+
"A",
|
119 |
+
"B",
|
120 |
+
"C",
|
121 |
+
"D",
|
122 |
+
"E",
|
123 |
+
"F",
|
124 |
+
"G",
|
125 |
+
"H",
|
126 |
+
]
|
127 |
+
n_iter = self.P3.nodes() # rebuild same iterator
|
128 |
+
G.remove_nodes_from(n_iter) # remove nbunch of nodes (nbunch=iterator)
|
129 |
+
assert sorted(G.nodes(), key=str) == ["A", "B", "C", "D", "E", "F", "G", "H"]
|
130 |
+
|
131 |
+
def test_nbunch_graph(self):
|
132 |
+
G = self.G()
|
133 |
+
G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
|
134 |
+
nbunch = self.K3
|
135 |
+
G.add_nodes_from(nbunch)
|
136 |
+
assert sorted(G.nodes(), key=str), [
|
137 |
+
1,
|
138 |
+
2,
|
139 |
+
3,
|
140 |
+
"A",
|
141 |
+
"B",
|
142 |
+
"C",
|
143 |
+
"D",
|
144 |
+
"E",
|
145 |
+
"F",
|
146 |
+
"G",
|
147 |
+
"H",
|
148 |
+
]
|
149 |
+
|
150 |
+
# Edges
|
151 |
+
|
152 |
+
def test_add_edge(self):
|
153 |
+
G = self.G()
|
154 |
+
pytest.raises(TypeError, G.add_edge, "A")
|
155 |
+
|
156 |
+
G.add_edge("A", "B") # testing add_edge()
|
157 |
+
G.add_edge("A", "B") # should fail silently
|
158 |
+
assert G.has_edge("A", "B")
|
159 |
+
assert not G.has_edge("A", "C")
|
160 |
+
assert G.has_edge(*("A", "B"))
|
161 |
+
if G.is_directed():
|
162 |
+
assert not G.has_edge("B", "A")
|
163 |
+
else:
|
164 |
+
# G is undirected, so B->A is an edge
|
165 |
+
assert G.has_edge("B", "A")
|
166 |
+
|
167 |
+
G.add_edge("A", "C") # test directedness
|
168 |
+
G.add_edge("C", "A")
|
169 |
+
G.remove_edge("C", "A")
|
170 |
+
if G.is_directed():
|
171 |
+
assert G.has_edge("A", "C")
|
172 |
+
else:
|
173 |
+
assert not G.has_edge("A", "C")
|
174 |
+
assert not G.has_edge("C", "A")
|
175 |
+
|
176 |
+
def test_self_loop(self):
|
177 |
+
G = self.G()
|
178 |
+
G.add_edge("A", "A") # test self loops
|
179 |
+
assert G.has_edge("A", "A")
|
180 |
+
G.remove_edge("A", "A")
|
181 |
+
G.add_edge("X", "X")
|
182 |
+
assert G.has_node("X")
|
183 |
+
G.remove_node("X")
|
184 |
+
G.add_edge("A", "Z") # should add the node silently
|
185 |
+
assert G.has_node("Z")
|
186 |
+
|
187 |
+
def test_add_edges_from(self):
|
188 |
+
G = self.G()
|
189 |
+
G.add_edges_from([("B", "C")]) # test add_edges_from()
|
190 |
+
assert G.has_edge("B", "C")
|
191 |
+
if G.is_directed():
|
192 |
+
assert not G.has_edge("C", "B")
|
193 |
+
else:
|
194 |
+
assert G.has_edge("C", "B") # undirected
|
195 |
+
|
196 |
+
G.add_edges_from([("D", "F"), ("B", "D")])
|
197 |
+
assert G.has_edge("D", "F")
|
198 |
+
assert G.has_edge("B", "D")
|
199 |
+
|
200 |
+
if G.is_directed():
|
201 |
+
assert not G.has_edge("D", "B")
|
202 |
+
else:
|
203 |
+
assert G.has_edge("D", "B") # undirected
|
204 |
+
|
205 |
+
def test_add_edges_from2(self):
|
206 |
+
G = self.G()
|
207 |
+
# after failing silently, should add 2nd edge
|
208 |
+
G.add_edges_from([tuple("IJ"), list("KK"), tuple("JK")])
|
209 |
+
assert G.has_edge(*("I", "J"))
|
210 |
+
assert G.has_edge(*("K", "K"))
|
211 |
+
assert G.has_edge(*("J", "K"))
|
212 |
+
if G.is_directed():
|
213 |
+
assert not G.has_edge(*("K", "J"))
|
214 |
+
else:
|
215 |
+
assert G.has_edge(*("K", "J"))
|
216 |
+
|
217 |
+
def test_add_edges_from3(self):
|
218 |
+
G = self.G()
|
219 |
+
G.add_edges_from(zip(list("ACD"), list("CDE")))
|
220 |
+
assert G.has_edge("D", "E")
|
221 |
+
assert not G.has_edge("E", "C")
|
222 |
+
|
223 |
+
def test_remove_edge(self):
|
224 |
+
G = self.G()
|
225 |
+
G.add_nodes_from([1, 2, 3, "A", "B", "C", "D", "E", "F", "G", "H"])
|
226 |
+
|
227 |
+
G.add_edges_from(zip(list("MNOP"), list("NOPM")))
|
228 |
+
assert G.has_edge("O", "P")
|
229 |
+
assert G.has_edge("P", "M")
|
230 |
+
G.remove_node("P") # tests remove_node()'s handling of edges.
|
231 |
+
assert not G.has_edge("P", "M")
|
232 |
+
pytest.raises(TypeError, G.remove_edge, "M")
|
233 |
+
|
234 |
+
G.add_edge("N", "M")
|
235 |
+
assert G.has_edge("M", "N")
|
236 |
+
G.remove_edge("M", "N")
|
237 |
+
assert not G.has_edge("M", "N")
|
238 |
+
|
239 |
+
# self loop fails silently
|
240 |
+
G.remove_edges_from([list("HI"), list("DF"), tuple("KK"), tuple("JK")])
|
241 |
+
assert not G.has_edge("H", "I")
|
242 |
+
assert not G.has_edge("J", "K")
|
243 |
+
G.remove_edges_from([list("IJ"), list("KK"), list("JK")])
|
244 |
+
assert not G.has_edge("I", "J")
|
245 |
+
G.remove_nodes_from(set("ZEFHIMNO"))
|
246 |
+
G.add_edge("J", "K")
|
247 |
+
|
248 |
+
def test_edges_nbunch(self):
|
249 |
+
# Test G.edges(nbunch) with various forms of nbunch
|
250 |
+
G = self.G()
|
251 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
252 |
+
# node not in nbunch should be quietly ignored
|
253 |
+
pytest.raises(nx.NetworkXError, G.edges, 6)
|
254 |
+
assert list(G.edges("Z")) == [] # iterable non-node
|
255 |
+
# nbunch can be an empty list
|
256 |
+
assert list(G.edges([])) == []
|
257 |
+
if G.is_directed():
|
258 |
+
elist = [("A", "B"), ("A", "C"), ("B", "D")]
|
259 |
+
else:
|
260 |
+
elist = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D")]
|
261 |
+
# nbunch can be a list
|
262 |
+
assert edges_equal(list(G.edges(["A", "B"])), elist)
|
263 |
+
# nbunch can be a set
|
264 |
+
assert edges_equal(G.edges({"A", "B"}), elist)
|
265 |
+
# nbunch can be a graph
|
266 |
+
G1 = self.G()
|
267 |
+
G1.add_nodes_from("AB")
|
268 |
+
assert edges_equal(G.edges(G1), elist)
|
269 |
+
# nbunch can be a dict with nodes as keys
|
270 |
+
ndict = {"A": "thing1", "B": "thing2"}
|
271 |
+
assert edges_equal(G.edges(ndict), elist)
|
272 |
+
# nbunch can be a single node
|
273 |
+
assert edges_equal(list(G.edges("A")), [("A", "B"), ("A", "C")])
|
274 |
+
assert nodes_equal(sorted(G), ["A", "B", "C", "D"])
|
275 |
+
|
276 |
+
# nbunch can be nothing (whole graph)
|
277 |
+
assert edges_equal(
|
278 |
+
list(G.edges()),
|
279 |
+
[("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")],
|
280 |
+
)
|
281 |
+
|
282 |
+
def test_degree(self):
|
283 |
+
G = self.G()
|
284 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
285 |
+
assert G.degree("A") == 2
|
286 |
+
|
287 |
+
# degree of single node in iterable container must return dict
|
288 |
+
assert list(G.degree(["A"])) == [("A", 2)]
|
289 |
+
assert sorted(d for n, d in G.degree(["A", "B"])) == [2, 3]
|
290 |
+
assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3]
|
291 |
+
|
292 |
+
def test_degree2(self):
|
293 |
+
H = self.G()
|
294 |
+
H.add_edges_from([(1, 24), (1, 2)])
|
295 |
+
assert sorted(d for n, d in H.degree([1, 24])) == [1, 2]
|
296 |
+
|
297 |
+
def test_degree_graph(self):
|
298 |
+
P3 = nx.path_graph(3)
|
299 |
+
P5 = nx.path_graph(5)
|
300 |
+
# silently ignore nodes not in P3
|
301 |
+
assert dict(d for n, d in P3.degree(["A", "B"])) == {}
|
302 |
+
# nbunch can be a graph
|
303 |
+
assert sorted(d for n, d in P5.degree(P3)) == [1, 2, 2]
|
304 |
+
# nbunch can be a graph that's way too big
|
305 |
+
assert sorted(d for n, d in P3.degree(P5)) == [1, 1, 2]
|
306 |
+
assert list(P5.degree([])) == []
|
307 |
+
assert dict(P5.degree([])) == {}
|
308 |
+
|
309 |
+
def test_null(self):
|
310 |
+
null = nx.null_graph()
|
311 |
+
assert list(null.degree()) == []
|
312 |
+
assert dict(null.degree()) == {}
|
313 |
+
|
314 |
+
def test_order_size(self):
|
315 |
+
G = self.G()
|
316 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
317 |
+
assert G.order() == 4
|
318 |
+
assert G.size() == 5
|
319 |
+
assert G.number_of_edges() == 5
|
320 |
+
assert G.number_of_edges("A", "B") == 1
|
321 |
+
assert G.number_of_edges("A", "D") == 0
|
322 |
+
|
323 |
+
def test_copy(self):
|
324 |
+
G = self.G()
|
325 |
+
H = G.copy() # copy
|
326 |
+
assert H.adj == G.adj
|
327 |
+
assert H.name == G.name
|
328 |
+
assert H is not G
|
329 |
+
|
330 |
+
def test_subgraph(self):
|
331 |
+
G = self.G()
|
332 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
333 |
+
SG = G.subgraph(["A", "B", "D"])
|
334 |
+
assert nodes_equal(list(SG), ["A", "B", "D"])
|
335 |
+
assert edges_equal(list(SG.edges()), [("A", "B"), ("B", "D")])
|
336 |
+
|
337 |
+
def test_to_directed(self):
|
338 |
+
G = self.G()
|
339 |
+
if not G.is_directed():
|
340 |
+
G.add_edges_from(
|
341 |
+
[("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
|
342 |
+
)
|
343 |
+
|
344 |
+
DG = G.to_directed()
|
345 |
+
assert DG is not G # directed copy or copy
|
346 |
+
|
347 |
+
assert DG.is_directed()
|
348 |
+
assert DG.name == G.name
|
349 |
+
assert DG.adj == G.adj
|
350 |
+
assert sorted(DG.out_edges(list("AB"))) == [
|
351 |
+
("A", "B"),
|
352 |
+
("A", "C"),
|
353 |
+
("B", "A"),
|
354 |
+
("B", "C"),
|
355 |
+
("B", "D"),
|
356 |
+
]
|
357 |
+
DG.remove_edge("A", "B")
|
358 |
+
assert DG.has_edge("B", "A") # this removes B-A but not A-B
|
359 |
+
assert not DG.has_edge("A", "B")
|
360 |
+
|
361 |
+
def test_to_undirected(self):
|
362 |
+
G = self.G()
|
363 |
+
if G.is_directed():
|
364 |
+
G.add_edges_from(
|
365 |
+
[("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
|
366 |
+
)
|
367 |
+
UG = G.to_undirected() # to_undirected
|
368 |
+
assert UG is not G
|
369 |
+
assert not UG.is_directed()
|
370 |
+
assert G.is_directed()
|
371 |
+
assert UG.name == G.name
|
372 |
+
assert UG.adj != G.adj
|
373 |
+
assert sorted(UG.edges(list("AB"))) == [
|
374 |
+
("A", "B"),
|
375 |
+
("A", "C"),
|
376 |
+
("B", "C"),
|
377 |
+
("B", "D"),
|
378 |
+
]
|
379 |
+
assert sorted(UG.edges(["A", "B"])) == [
|
380 |
+
("A", "B"),
|
381 |
+
("A", "C"),
|
382 |
+
("B", "C"),
|
383 |
+
("B", "D"),
|
384 |
+
]
|
385 |
+
UG.remove_edge("A", "B")
|
386 |
+
assert not UG.has_edge("B", "A")
|
387 |
+
assert not UG.has_edge("A", "B")
|
388 |
+
|
389 |
+
def test_neighbors(self):
|
390 |
+
G = self.G()
|
391 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
392 |
+
G.add_nodes_from("GJK")
|
393 |
+
assert sorted(G["A"]) == ["B", "C"]
|
394 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
395 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
396 |
+
assert sorted(G.neighbors("G")) == []
|
397 |
+
pytest.raises(nx.NetworkXError, G.neighbors, "j")
|
398 |
+
|
399 |
+
def test_iterators(self):
|
400 |
+
G = self.G()
|
401 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")])
|
402 |
+
G.add_nodes_from("GJK")
|
403 |
+
assert sorted(G.nodes()) == ["A", "B", "C", "D", "G", "J", "K"]
|
404 |
+
assert edges_equal(
|
405 |
+
G.edges(), [("A", "B"), ("A", "C"), ("B", "D"), ("C", "B"), ("C", "D")]
|
406 |
+
)
|
407 |
+
|
408 |
+
assert sorted(v for k, v in G.degree()) == [0, 0, 0, 2, 2, 3, 3]
|
409 |
+
assert sorted(G.degree(), key=str) == [
|
410 |
+
("A", 2),
|
411 |
+
("B", 3),
|
412 |
+
("C", 3),
|
413 |
+
("D", 2),
|
414 |
+
("G", 0),
|
415 |
+
("J", 0),
|
416 |
+
("K", 0),
|
417 |
+
]
|
418 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
419 |
+
pytest.raises(nx.NetworkXError, G.neighbors, "X")
|
420 |
+
G.clear()
|
421 |
+
assert nx.number_of_nodes(G) == 0
|
422 |
+
assert nx.number_of_edges(G) == 0
|
423 |
+
|
424 |
+
def test_null_subgraph(self):
|
425 |
+
# Subgraph of a null graph is a null graph
|
426 |
+
nullgraph = nx.null_graph()
|
427 |
+
G = nx.null_graph()
|
428 |
+
H = G.subgraph([])
|
429 |
+
assert nx.is_isomorphic(H, nullgraph)
|
430 |
+
|
431 |
+
def test_empty_subgraph(self):
|
432 |
+
# Subgraph of an empty graph is an empty graph. test 1
|
433 |
+
nullgraph = nx.null_graph()
|
434 |
+
E5 = nx.empty_graph(5)
|
435 |
+
E10 = nx.empty_graph(10)
|
436 |
+
H = E10.subgraph([])
|
437 |
+
assert nx.is_isomorphic(H, nullgraph)
|
438 |
+
H = E10.subgraph([1, 2, 3, 4, 5])
|
439 |
+
assert nx.is_isomorphic(H, E5)
|
440 |
+
|
441 |
+
def test_complete_subgraph(self):
|
442 |
+
# Subgraph of a complete graph is a complete graph
|
443 |
+
K1 = nx.complete_graph(1)
|
444 |
+
K3 = nx.complete_graph(3)
|
445 |
+
K5 = nx.complete_graph(5)
|
446 |
+
H = K5.subgraph([1, 2, 3])
|
447 |
+
assert nx.is_isomorphic(H, K3)
|
448 |
+
|
449 |
+
def test_subgraph_nbunch(self):
|
450 |
+
nullgraph = nx.null_graph()
|
451 |
+
K1 = nx.complete_graph(1)
|
452 |
+
K3 = nx.complete_graph(3)
|
453 |
+
K5 = nx.complete_graph(5)
|
454 |
+
# Test G.subgraph(nbunch), where nbunch is a single node
|
455 |
+
H = K5.subgraph(1)
|
456 |
+
assert nx.is_isomorphic(H, K1)
|
457 |
+
# Test G.subgraph(nbunch), where nbunch is a set
|
458 |
+
H = K5.subgraph({1})
|
459 |
+
assert nx.is_isomorphic(H, K1)
|
460 |
+
# Test G.subgraph(nbunch), where nbunch is an iterator
|
461 |
+
H = K5.subgraph(iter(K3))
|
462 |
+
assert nx.is_isomorphic(H, K3)
|
463 |
+
# Test G.subgraph(nbunch), where nbunch is another graph
|
464 |
+
H = K5.subgraph(K3)
|
465 |
+
assert nx.is_isomorphic(H, K3)
|
466 |
+
H = K5.subgraph([9])
|
467 |
+
assert nx.is_isomorphic(H, nullgraph)
|
468 |
+
|
469 |
+
def test_node_tuple_issue(self):
|
470 |
+
H = self.G()
|
471 |
+
# Test error handling of tuple as a node
|
472 |
+
pytest.raises(nx.NetworkXError, H.remove_node, (1, 2))
|
473 |
+
H.remove_nodes_from([(1, 2)]) # no error
|
474 |
+
pytest.raises(nx.NetworkXError, H.neighbors, (1, 2))
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_coreviews.py
ADDED
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pickle
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
|
8 |
+
class TestAtlasView:
|
9 |
+
# node->data
|
10 |
+
def setup_method(self):
|
11 |
+
self.d = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
|
12 |
+
self.av = nx.classes.coreviews.AtlasView(self.d)
|
13 |
+
|
14 |
+
def test_pickle(self):
|
15 |
+
view = self.av
|
16 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
17 |
+
assert view == pview
|
18 |
+
assert view.__slots__ == pview.__slots__
|
19 |
+
pview = pickle.loads(pickle.dumps(view))
|
20 |
+
assert view == pview
|
21 |
+
assert view.__slots__ == pview.__slots__
|
22 |
+
|
23 |
+
def test_len(self):
|
24 |
+
assert len(self.av) == len(self.d)
|
25 |
+
|
26 |
+
def test_iter(self):
|
27 |
+
assert list(self.av) == list(self.d)
|
28 |
+
|
29 |
+
def test_getitem(self):
|
30 |
+
assert self.av[1] is self.d[1]
|
31 |
+
assert self.av[2]["color"] == 1
|
32 |
+
pytest.raises(KeyError, self.av.__getitem__, 3)
|
33 |
+
|
34 |
+
def test_copy(self):
|
35 |
+
avcopy = self.av.copy()
|
36 |
+
assert avcopy[0] == self.av[0]
|
37 |
+
assert avcopy == self.av
|
38 |
+
assert avcopy[0] is not self.av[0]
|
39 |
+
assert avcopy is not self.av
|
40 |
+
avcopy[5] = {}
|
41 |
+
assert avcopy != self.av
|
42 |
+
|
43 |
+
avcopy[0]["ht"] = 4
|
44 |
+
assert avcopy[0] != self.av[0]
|
45 |
+
self.av[0]["ht"] = 4
|
46 |
+
assert avcopy[0] == self.av[0]
|
47 |
+
del self.av[0]["ht"]
|
48 |
+
|
49 |
+
assert not hasattr(self.av, "__setitem__")
|
50 |
+
|
51 |
+
def test_items(self):
|
52 |
+
assert sorted(self.av.items()) == sorted(self.d.items())
|
53 |
+
|
54 |
+
def test_str(self):
|
55 |
+
out = str(self.d)
|
56 |
+
assert str(self.av) == out
|
57 |
+
|
58 |
+
def test_repr(self):
|
59 |
+
out = "AtlasView(" + str(self.d) + ")"
|
60 |
+
assert repr(self.av) == out
|
61 |
+
|
62 |
+
|
63 |
+
class TestAdjacencyView:
|
64 |
+
# node->nbr->data
|
65 |
+
def setup_method(self):
|
66 |
+
dd = {"color": "blue", "weight": 1.2}
|
67 |
+
self.nd = {0: dd, 1: {}, 2: {"color": 1}}
|
68 |
+
self.adj = {3: self.nd, 0: {3: dd}, 1: {}, 2: {3: {"color": 1}}}
|
69 |
+
self.adjview = nx.classes.coreviews.AdjacencyView(self.adj)
|
70 |
+
|
71 |
+
def test_pickle(self):
|
72 |
+
view = self.adjview
|
73 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
74 |
+
assert view == pview
|
75 |
+
assert view.__slots__ == pview.__slots__
|
76 |
+
|
77 |
+
def test_len(self):
|
78 |
+
assert len(self.adjview) == len(self.adj)
|
79 |
+
|
80 |
+
def test_iter(self):
|
81 |
+
assert list(self.adjview) == list(self.adj)
|
82 |
+
|
83 |
+
def test_getitem(self):
|
84 |
+
assert self.adjview[1] is not self.adj[1]
|
85 |
+
assert self.adjview[3][0] is self.adjview[0][3]
|
86 |
+
assert self.adjview[2][3]["color"] == 1
|
87 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
88 |
+
|
89 |
+
def test_copy(self):
|
90 |
+
avcopy = self.adjview.copy()
|
91 |
+
assert avcopy[0] == self.adjview[0]
|
92 |
+
assert avcopy[0] is not self.adjview[0]
|
93 |
+
|
94 |
+
avcopy[2][3]["ht"] = 4
|
95 |
+
assert avcopy[2] != self.adjview[2]
|
96 |
+
self.adjview[2][3]["ht"] = 4
|
97 |
+
assert avcopy[2] == self.adjview[2]
|
98 |
+
del self.adjview[2][3]["ht"]
|
99 |
+
|
100 |
+
assert not hasattr(self.adjview, "__setitem__")
|
101 |
+
|
102 |
+
def test_items(self):
|
103 |
+
view_items = sorted((n, dict(d)) for n, d in self.adjview.items())
|
104 |
+
assert view_items == sorted(self.adj.items())
|
105 |
+
|
106 |
+
def test_str(self):
|
107 |
+
out = str(dict(self.adj))
|
108 |
+
assert str(self.adjview) == out
|
109 |
+
|
110 |
+
def test_repr(self):
|
111 |
+
out = self.adjview.__class__.__name__ + "(" + str(self.adj) + ")"
|
112 |
+
assert repr(self.adjview) == out
|
113 |
+
|
114 |
+
|
115 |
+
class TestMultiAdjacencyView(TestAdjacencyView):
|
116 |
+
# node->nbr->key->data
|
117 |
+
def setup_method(self):
|
118 |
+
dd = {"color": "blue", "weight": 1.2}
|
119 |
+
self.kd = {0: dd, 1: {}, 2: {"color": 1}}
|
120 |
+
self.nd = {3: self.kd, 0: {3: dd}, 1: {0: {}}, 2: {3: {"color": 1}}}
|
121 |
+
self.adj = {3: self.nd, 0: {3: {3: dd}}, 1: {}, 2: {3: {8: {}}}}
|
122 |
+
self.adjview = nx.classes.coreviews.MultiAdjacencyView(self.adj)
|
123 |
+
|
124 |
+
def test_getitem(self):
|
125 |
+
assert self.adjview[1] is not self.adj[1]
|
126 |
+
assert self.adjview[3][0][3] is self.adjview[0][3][3]
|
127 |
+
assert self.adjview[3][2][3]["color"] == 1
|
128 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
129 |
+
|
130 |
+
def test_copy(self):
|
131 |
+
avcopy = self.adjview.copy()
|
132 |
+
assert avcopy[0] == self.adjview[0]
|
133 |
+
assert avcopy[0] is not self.adjview[0]
|
134 |
+
|
135 |
+
avcopy[2][3][8]["ht"] = 4
|
136 |
+
assert avcopy[2] != self.adjview[2]
|
137 |
+
self.adjview[2][3][8]["ht"] = 4
|
138 |
+
assert avcopy[2] == self.adjview[2]
|
139 |
+
del self.adjview[2][3][8]["ht"]
|
140 |
+
|
141 |
+
assert not hasattr(self.adjview, "__setitem__")
|
142 |
+
|
143 |
+
|
144 |
+
class TestUnionAtlas:
|
145 |
+
# node->data
|
146 |
+
def setup_method(self):
|
147 |
+
self.s = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
|
148 |
+
self.p = {3: {"color": "blue", "weight": 1.2}, 4: {}, 2: {"watch": 2}}
|
149 |
+
self.av = nx.classes.coreviews.UnionAtlas(self.s, self.p)
|
150 |
+
|
151 |
+
def test_pickle(self):
|
152 |
+
view = self.av
|
153 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
154 |
+
assert view == pview
|
155 |
+
assert view.__slots__ == pview.__slots__
|
156 |
+
|
157 |
+
def test_len(self):
|
158 |
+
assert len(self.av) == len(self.s.keys() | self.p.keys()) == 5
|
159 |
+
|
160 |
+
def test_iter(self):
|
161 |
+
assert set(self.av) == set(self.s) | set(self.p)
|
162 |
+
|
163 |
+
def test_getitem(self):
|
164 |
+
assert self.av[0] is self.s[0]
|
165 |
+
assert self.av[4] is self.p[4]
|
166 |
+
assert self.av[2]["color"] == 1
|
167 |
+
pytest.raises(KeyError, self.av[2].__getitem__, "watch")
|
168 |
+
pytest.raises(KeyError, self.av.__getitem__, 8)
|
169 |
+
|
170 |
+
def test_copy(self):
|
171 |
+
avcopy = self.av.copy()
|
172 |
+
assert avcopy[0] == self.av[0]
|
173 |
+
assert avcopy[0] is not self.av[0]
|
174 |
+
assert avcopy is not self.av
|
175 |
+
avcopy[5] = {}
|
176 |
+
assert avcopy != self.av
|
177 |
+
|
178 |
+
avcopy[0]["ht"] = 4
|
179 |
+
assert avcopy[0] != self.av[0]
|
180 |
+
self.av[0]["ht"] = 4
|
181 |
+
assert avcopy[0] == self.av[0]
|
182 |
+
del self.av[0]["ht"]
|
183 |
+
|
184 |
+
assert not hasattr(self.av, "__setitem__")
|
185 |
+
|
186 |
+
def test_items(self):
|
187 |
+
expected = dict(self.p.items())
|
188 |
+
expected.update(self.s)
|
189 |
+
assert sorted(self.av.items()) == sorted(expected.items())
|
190 |
+
|
191 |
+
def test_str(self):
|
192 |
+
out = str(dict(self.av))
|
193 |
+
assert str(self.av) == out
|
194 |
+
|
195 |
+
def test_repr(self):
|
196 |
+
out = f"{self.av.__class__.__name__}({self.s}, {self.p})"
|
197 |
+
assert repr(self.av) == out
|
198 |
+
|
199 |
+
|
200 |
+
class TestUnionAdjacency:
|
201 |
+
# node->nbr->data
|
202 |
+
def setup_method(self):
|
203 |
+
dd = {"color": "blue", "weight": 1.2}
|
204 |
+
self.nd = {0: dd, 1: {}, 2: {"color": 1}}
|
205 |
+
self.s = {3: self.nd, 0: {}, 1: {}, 2: {3: {"color": 1}}}
|
206 |
+
self.p = {3: {}, 0: {3: dd}, 1: {0: {}}, 2: {1: {"color": 1}}}
|
207 |
+
self.adjview = nx.classes.coreviews.UnionAdjacency(self.s, self.p)
|
208 |
+
|
209 |
+
def test_pickle(self):
|
210 |
+
view = self.adjview
|
211 |
+
pview = pickle.loads(pickle.dumps(view, -1))
|
212 |
+
assert view == pview
|
213 |
+
assert view.__slots__ == pview.__slots__
|
214 |
+
|
215 |
+
def test_len(self):
|
216 |
+
assert len(self.adjview) == len(self.s)
|
217 |
+
|
218 |
+
def test_iter(self):
|
219 |
+
assert sorted(self.adjview) == sorted(self.s)
|
220 |
+
|
221 |
+
def test_getitem(self):
|
222 |
+
assert self.adjview[1] is not self.s[1]
|
223 |
+
assert self.adjview[3][0] is self.adjview[0][3]
|
224 |
+
assert self.adjview[2][3]["color"] == 1
|
225 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
226 |
+
|
227 |
+
def test_copy(self):
|
228 |
+
avcopy = self.adjview.copy()
|
229 |
+
assert avcopy[0] == self.adjview[0]
|
230 |
+
assert avcopy[0] is not self.adjview[0]
|
231 |
+
|
232 |
+
avcopy[2][3]["ht"] = 4
|
233 |
+
assert avcopy[2] != self.adjview[2]
|
234 |
+
self.adjview[2][3]["ht"] = 4
|
235 |
+
assert avcopy[2] == self.adjview[2]
|
236 |
+
del self.adjview[2][3]["ht"]
|
237 |
+
|
238 |
+
assert not hasattr(self.adjview, "__setitem__")
|
239 |
+
|
240 |
+
def test_str(self):
|
241 |
+
out = str(dict(self.adjview))
|
242 |
+
assert str(self.adjview) == out
|
243 |
+
|
244 |
+
def test_repr(self):
|
245 |
+
clsname = self.adjview.__class__.__name__
|
246 |
+
out = f"{clsname}({self.s}, {self.p})"
|
247 |
+
assert repr(self.adjview) == out
|
248 |
+
|
249 |
+
|
250 |
+
class TestUnionMultiInner(TestUnionAdjacency):
|
251 |
+
# nbr->key->data
|
252 |
+
def setup_method(self):
|
253 |
+
dd = {"color": "blue", "weight": 1.2}
|
254 |
+
self.kd = {7: {}, "ekey": {}, 9: {"color": 1}}
|
255 |
+
self.s = {3: self.kd, 0: {7: dd}, 1: {}, 2: {"key": {"color": 1}}}
|
256 |
+
self.p = {3: {}, 0: {3: dd}, 1: {}, 2: {1: {"span": 2}}}
|
257 |
+
self.adjview = nx.classes.coreviews.UnionMultiInner(self.s, self.p)
|
258 |
+
|
259 |
+
def test_len(self):
|
260 |
+
assert len(self.adjview) == len(self.s.keys() | self.p.keys()) == 4
|
261 |
+
|
262 |
+
def test_getitem(self):
|
263 |
+
assert self.adjview[1] is not self.s[1]
|
264 |
+
assert self.adjview[0][7] is self.adjview[0][3]
|
265 |
+
assert self.adjview[2]["key"]["color"] == 1
|
266 |
+
assert self.adjview[2][1]["span"] == 2
|
267 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
268 |
+
pytest.raises(KeyError, self.adjview[1].__getitem__, "key")
|
269 |
+
|
270 |
+
def test_copy(self):
|
271 |
+
avcopy = self.adjview.copy()
|
272 |
+
assert avcopy[0] == self.adjview[0]
|
273 |
+
assert avcopy[0] is not self.adjview[0]
|
274 |
+
|
275 |
+
avcopy[2][1]["width"] = 8
|
276 |
+
assert avcopy[2] != self.adjview[2]
|
277 |
+
self.adjview[2][1]["width"] = 8
|
278 |
+
assert avcopy[2] == self.adjview[2]
|
279 |
+
del self.adjview[2][1]["width"]
|
280 |
+
|
281 |
+
assert not hasattr(self.adjview, "__setitem__")
|
282 |
+
assert hasattr(avcopy, "__setitem__")
|
283 |
+
|
284 |
+
|
285 |
+
class TestUnionMultiAdjacency(TestUnionAdjacency):
|
286 |
+
# node->nbr->key->data
|
287 |
+
def setup_method(self):
|
288 |
+
dd = {"color": "blue", "weight": 1.2}
|
289 |
+
self.kd = {7: {}, 8: {}, 9: {"color": 1}}
|
290 |
+
self.nd = {3: self.kd, 0: {9: dd}, 1: {8: {}}, 2: {9: {"color": 1}}}
|
291 |
+
self.s = {3: self.nd, 0: {3: {7: dd}}, 1: {}, 2: {3: {8: {}}}}
|
292 |
+
self.p = {3: {}, 0: {3: {9: dd}}, 1: {}, 2: {1: {8: {}}}}
|
293 |
+
self.adjview = nx.classes.coreviews.UnionMultiAdjacency(self.s, self.p)
|
294 |
+
|
295 |
+
def test_getitem(self):
|
296 |
+
assert self.adjview[1] is not self.s[1]
|
297 |
+
assert self.adjview[3][0][9] is self.adjview[0][3][9]
|
298 |
+
assert self.adjview[3][2][9]["color"] == 1
|
299 |
+
pytest.raises(KeyError, self.adjview.__getitem__, 4)
|
300 |
+
|
301 |
+
def test_copy(self):
|
302 |
+
avcopy = self.adjview.copy()
|
303 |
+
assert avcopy[0] == self.adjview[0]
|
304 |
+
assert avcopy[0] is not self.adjview[0]
|
305 |
+
|
306 |
+
avcopy[2][3][8]["ht"] = 4
|
307 |
+
assert avcopy[2] != self.adjview[2]
|
308 |
+
self.adjview[2][3][8]["ht"] = 4
|
309 |
+
assert avcopy[2] == self.adjview[2]
|
310 |
+
del self.adjview[2][3][8]["ht"]
|
311 |
+
|
312 |
+
assert not hasattr(self.adjview, "__setitem__")
|
313 |
+
assert hasattr(avcopy, "__setitem__")
|
314 |
+
|
315 |
+
|
316 |
+
class TestFilteredGraphs:
|
317 |
+
def setup_method(self):
|
318 |
+
self.Graphs = [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
|
319 |
+
|
320 |
+
def test_hide_show_nodes(self):
|
321 |
+
SubGraph = nx.subgraph_view
|
322 |
+
for Graph in self.Graphs:
|
323 |
+
G = nx.path_graph(4, Graph)
|
324 |
+
SG = G.subgraph([2, 3])
|
325 |
+
RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
|
326 |
+
assert SG.nodes == RG.nodes
|
327 |
+
assert SG.edges == RG.edges
|
328 |
+
SGC = SG.copy()
|
329 |
+
RGC = RG.copy()
|
330 |
+
assert SGC.nodes == RGC.nodes
|
331 |
+
assert SGC.edges == RGC.edges
|
332 |
+
|
333 |
+
def test_str_repr(self):
|
334 |
+
SubGraph = nx.subgraph_view
|
335 |
+
for Graph in self.Graphs:
|
336 |
+
G = nx.path_graph(4, Graph)
|
337 |
+
SG = G.subgraph([2, 3])
|
338 |
+
RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
|
339 |
+
str(SG.adj)
|
340 |
+
str(RG.adj)
|
341 |
+
repr(SG.adj)
|
342 |
+
repr(RG.adj)
|
343 |
+
str(SG.adj[2])
|
344 |
+
str(RG.adj[2])
|
345 |
+
repr(SG.adj[2])
|
346 |
+
repr(RG.adj[2])
|
347 |
+
|
348 |
+
def test_copy(self):
|
349 |
+
SubGraph = nx.subgraph_view
|
350 |
+
for Graph in self.Graphs:
|
351 |
+
G = nx.path_graph(4, Graph)
|
352 |
+
SG = G.subgraph([2, 3])
|
353 |
+
RG = SubGraph(G, filter_node=nx.filters.hide_nodes([0, 1]))
|
354 |
+
RsG = SubGraph(G, filter_node=nx.filters.show_nodes([2, 3]))
|
355 |
+
assert G.adj.copy() == G.adj
|
356 |
+
assert G.adj[2].copy() == G.adj[2]
|
357 |
+
assert SG.adj.copy() == SG.adj
|
358 |
+
assert SG.adj[2].copy() == SG.adj[2]
|
359 |
+
assert RG.adj.copy() == RG.adj
|
360 |
+
assert RG.adj[2].copy() == RG.adj[2]
|
361 |
+
assert RsG.adj.copy() == RsG.adj
|
362 |
+
assert RsG.adj[2].copy() == RsG.adj[2]
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_digraph.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
from networkx.utils import nodes_equal
|
5 |
+
|
6 |
+
from .test_graph import BaseAttrGraphTester, BaseGraphTester
|
7 |
+
from .test_graph import TestEdgeSubgraph as _TestGraphEdgeSubgraph
|
8 |
+
from .test_graph import TestGraph as _TestGraph
|
9 |
+
|
10 |
+
|
11 |
+
class BaseDiGraphTester(BaseGraphTester):
|
12 |
+
def test_has_successor(self):
|
13 |
+
G = self.K3
|
14 |
+
assert G.has_successor(0, 1)
|
15 |
+
assert not G.has_successor(0, -1)
|
16 |
+
|
17 |
+
def test_successors(self):
|
18 |
+
G = self.K3
|
19 |
+
assert sorted(G.successors(0)) == [1, 2]
|
20 |
+
with pytest.raises(nx.NetworkXError):
|
21 |
+
G.successors(-1)
|
22 |
+
|
23 |
+
def test_has_predecessor(self):
|
24 |
+
G = self.K3
|
25 |
+
assert G.has_predecessor(0, 1)
|
26 |
+
assert not G.has_predecessor(0, -1)
|
27 |
+
|
28 |
+
def test_predecessors(self):
|
29 |
+
G = self.K3
|
30 |
+
assert sorted(G.predecessors(0)) == [1, 2]
|
31 |
+
with pytest.raises(nx.NetworkXError):
|
32 |
+
G.predecessors(-1)
|
33 |
+
|
34 |
+
def test_edges(self):
|
35 |
+
G = self.K3
|
36 |
+
assert sorted(G.edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
37 |
+
assert sorted(G.edges(0)) == [(0, 1), (0, 2)]
|
38 |
+
assert sorted(G.edges([0, 1])) == [(0, 1), (0, 2), (1, 0), (1, 2)]
|
39 |
+
with pytest.raises(nx.NetworkXError):
|
40 |
+
G.edges(-1)
|
41 |
+
|
42 |
+
def test_out_edges(self):
|
43 |
+
G = self.K3
|
44 |
+
assert sorted(G.out_edges()) == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
|
45 |
+
assert sorted(G.out_edges(0)) == [(0, 1), (0, 2)]
|
46 |
+
with pytest.raises(nx.NetworkXError):
|
47 |
+
G.out_edges(-1)
|
48 |
+
|
49 |
+
def test_out_edges_dir(self):
|
50 |
+
G = self.P3
|
51 |
+
assert sorted(G.out_edges()) == [(0, 1), (1, 2)]
|
52 |
+
assert sorted(G.out_edges(0)) == [(0, 1)]
|
53 |
+
assert sorted(G.out_edges(2)) == []
|
54 |
+
|
55 |
+
def test_out_edges_data(self):
|
56 |
+
G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})])
|
57 |
+
assert sorted(G.out_edges(data=True)) == [(0, 1, {"data": 0}), (1, 0, {})]
|
58 |
+
assert sorted(G.out_edges(0, data=True)) == [(0, 1, {"data": 0})]
|
59 |
+
assert sorted(G.out_edges(data="data")) == [(0, 1, 0), (1, 0, None)]
|
60 |
+
assert sorted(G.out_edges(0, data="data")) == [(0, 1, 0)]
|
61 |
+
|
62 |
+
def test_in_edges_dir(self):
|
63 |
+
G = self.P3
|
64 |
+
assert sorted(G.in_edges()) == [(0, 1), (1, 2)]
|
65 |
+
assert sorted(G.in_edges(0)) == []
|
66 |
+
assert sorted(G.in_edges(2)) == [(1, 2)]
|
67 |
+
|
68 |
+
def test_in_edges_data(self):
|
69 |
+
G = nx.DiGraph([(0, 1, {"data": 0}), (1, 0, {})])
|
70 |
+
assert sorted(G.in_edges(data=True)) == [(0, 1, {"data": 0}), (1, 0, {})]
|
71 |
+
assert sorted(G.in_edges(1, data=True)) == [(0, 1, {"data": 0})]
|
72 |
+
assert sorted(G.in_edges(data="data")) == [(0, 1, 0), (1, 0, None)]
|
73 |
+
assert sorted(G.in_edges(1, data="data")) == [(0, 1, 0)]
|
74 |
+
|
75 |
+
def test_degree(self):
|
76 |
+
G = self.K3
|
77 |
+
assert sorted(G.degree()) == [(0, 4), (1, 4), (2, 4)]
|
78 |
+
assert dict(G.degree()) == {0: 4, 1: 4, 2: 4}
|
79 |
+
assert G.degree(0) == 4
|
80 |
+
assert list(G.degree(iter([0]))) == [(0, 4)] # run through iterator
|
81 |
+
|
82 |
+
def test_in_degree(self):
|
83 |
+
G = self.K3
|
84 |
+
assert sorted(G.in_degree()) == [(0, 2), (1, 2), (2, 2)]
|
85 |
+
assert dict(G.in_degree()) == {0: 2, 1: 2, 2: 2}
|
86 |
+
assert G.in_degree(0) == 2
|
87 |
+
assert list(G.in_degree(iter([0]))) == [(0, 2)] # run through iterator
|
88 |
+
|
89 |
+
def test_out_degree(self):
|
90 |
+
G = self.K3
|
91 |
+
assert sorted(G.out_degree()) == [(0, 2), (1, 2), (2, 2)]
|
92 |
+
assert dict(G.out_degree()) == {0: 2, 1: 2, 2: 2}
|
93 |
+
assert G.out_degree(0) == 2
|
94 |
+
assert list(G.out_degree(iter([0]))) == [(0, 2)]
|
95 |
+
|
96 |
+
def test_size(self):
|
97 |
+
G = self.K3
|
98 |
+
assert G.size() == 6
|
99 |
+
assert G.number_of_edges() == 6
|
100 |
+
|
101 |
+
def test_to_undirected_reciprocal(self):
|
102 |
+
G = self.Graph()
|
103 |
+
G.add_edge(1, 2)
|
104 |
+
assert G.to_undirected().has_edge(1, 2)
|
105 |
+
assert not G.to_undirected(reciprocal=True).has_edge(1, 2)
|
106 |
+
G.add_edge(2, 1)
|
107 |
+
assert G.to_undirected(reciprocal=True).has_edge(1, 2)
|
108 |
+
|
109 |
+
def test_reverse_copy(self):
|
110 |
+
G = nx.DiGraph([(0, 1), (1, 2)])
|
111 |
+
R = G.reverse()
|
112 |
+
assert sorted(R.edges()) == [(1, 0), (2, 1)]
|
113 |
+
R.remove_edge(1, 0)
|
114 |
+
assert sorted(R.edges()) == [(2, 1)]
|
115 |
+
assert sorted(G.edges()) == [(0, 1), (1, 2)]
|
116 |
+
|
117 |
+
def test_reverse_nocopy(self):
|
118 |
+
G = nx.DiGraph([(0, 1), (1, 2)])
|
119 |
+
R = G.reverse(copy=False)
|
120 |
+
assert sorted(R.edges()) == [(1, 0), (2, 1)]
|
121 |
+
with pytest.raises(nx.NetworkXError):
|
122 |
+
R.remove_edge(1, 0)
|
123 |
+
|
124 |
+
def test_reverse_hashable(self):
|
125 |
+
class Foo:
|
126 |
+
pass
|
127 |
+
|
128 |
+
x = Foo()
|
129 |
+
y = Foo()
|
130 |
+
G = nx.DiGraph()
|
131 |
+
G.add_edge(x, y)
|
132 |
+
assert nodes_equal(G.nodes(), G.reverse().nodes())
|
133 |
+
assert [(y, x)] == list(G.reverse().edges())
|
134 |
+
|
135 |
+
def test_di_cache_reset(self):
|
136 |
+
G = self.K3.copy()
|
137 |
+
old_succ = G.succ
|
138 |
+
assert id(G.succ) == id(old_succ)
|
139 |
+
old_adj = G.adj
|
140 |
+
assert id(G.adj) == id(old_adj)
|
141 |
+
|
142 |
+
G._succ = {}
|
143 |
+
assert id(G.succ) != id(old_succ)
|
144 |
+
assert id(G.adj) != id(old_adj)
|
145 |
+
|
146 |
+
old_pred = G.pred
|
147 |
+
assert id(G.pred) == id(old_pred)
|
148 |
+
G._pred = {}
|
149 |
+
assert id(G.pred) != id(old_pred)
|
150 |
+
|
151 |
+
def test_di_attributes_cached(self):
|
152 |
+
G = self.K3.copy()
|
153 |
+
assert id(G.in_edges) == id(G.in_edges)
|
154 |
+
assert id(G.out_edges) == id(G.out_edges)
|
155 |
+
assert id(G.in_degree) == id(G.in_degree)
|
156 |
+
assert id(G.out_degree) == id(G.out_degree)
|
157 |
+
assert id(G.succ) == id(G.succ)
|
158 |
+
assert id(G.pred) == id(G.pred)
|
159 |
+
|
160 |
+
|
161 |
+
class BaseAttrDiGraphTester(BaseDiGraphTester, BaseAttrGraphTester):
|
162 |
+
def test_edges_data(self):
|
163 |
+
G = self.K3
|
164 |
+
all_edges = [
|
165 |
+
(0, 1, {}),
|
166 |
+
(0, 2, {}),
|
167 |
+
(1, 0, {}),
|
168 |
+
(1, 2, {}),
|
169 |
+
(2, 0, {}),
|
170 |
+
(2, 1, {}),
|
171 |
+
]
|
172 |
+
assert sorted(G.edges(data=True)) == all_edges
|
173 |
+
assert sorted(G.edges(0, data=True)) == all_edges[:2]
|
174 |
+
assert sorted(G.edges([0, 1], data=True)) == all_edges[:4]
|
175 |
+
with pytest.raises(nx.NetworkXError):
|
176 |
+
G.edges(-1, True)
|
177 |
+
|
178 |
+
def test_in_degree_weighted(self):
|
179 |
+
G = self.K3.copy()
|
180 |
+
G.add_edge(0, 1, weight=0.3, other=1.2)
|
181 |
+
assert sorted(G.in_degree(weight="weight")) == [(0, 2), (1, 1.3), (2, 2)]
|
182 |
+
assert dict(G.in_degree(weight="weight")) == {0: 2, 1: 1.3, 2: 2}
|
183 |
+
assert G.in_degree(1, weight="weight") == 1.3
|
184 |
+
assert sorted(G.in_degree(weight="other")) == [(0, 2), (1, 2.2), (2, 2)]
|
185 |
+
assert dict(G.in_degree(weight="other")) == {0: 2, 1: 2.2, 2: 2}
|
186 |
+
assert G.in_degree(1, weight="other") == 2.2
|
187 |
+
assert list(G.in_degree(iter([1]), weight="other")) == [(1, 2.2)]
|
188 |
+
|
189 |
+
def test_out_degree_weighted(self):
|
190 |
+
G = self.K3.copy()
|
191 |
+
G.add_edge(0, 1, weight=0.3, other=1.2)
|
192 |
+
assert sorted(G.out_degree(weight="weight")) == [(0, 1.3), (1, 2), (2, 2)]
|
193 |
+
assert dict(G.out_degree(weight="weight")) == {0: 1.3, 1: 2, 2: 2}
|
194 |
+
assert G.out_degree(0, weight="weight") == 1.3
|
195 |
+
assert sorted(G.out_degree(weight="other")) == [(0, 2.2), (1, 2), (2, 2)]
|
196 |
+
assert dict(G.out_degree(weight="other")) == {0: 2.2, 1: 2, 2: 2}
|
197 |
+
assert G.out_degree(0, weight="other") == 2.2
|
198 |
+
assert list(G.out_degree(iter([0]), weight="other")) == [(0, 2.2)]
|
199 |
+
|
200 |
+
|
201 |
+
class TestDiGraph(BaseAttrDiGraphTester, _TestGraph):
|
202 |
+
"""Tests specific to dict-of-dict-of-dict digraph data structure"""
|
203 |
+
|
204 |
+
def setup_method(self):
|
205 |
+
self.Graph = nx.DiGraph
|
206 |
+
# build dict-of-dict-of-dict K3
|
207 |
+
ed1, ed2, ed3, ed4, ed5, ed6 = ({}, {}, {}, {}, {}, {})
|
208 |
+
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
|
209 |
+
self.k3edges = [(0, 1), (0, 2), (1, 2)]
|
210 |
+
self.k3nodes = [0, 1, 2]
|
211 |
+
self.K3 = self.Graph()
|
212 |
+
self.K3._succ = self.k3adj # K3._adj is synced with K3._succ
|
213 |
+
self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
|
214 |
+
self.K3._node = {}
|
215 |
+
self.K3._node[0] = {}
|
216 |
+
self.K3._node[1] = {}
|
217 |
+
self.K3._node[2] = {}
|
218 |
+
|
219 |
+
ed1, ed2 = ({}, {})
|
220 |
+
self.P3 = self.Graph()
|
221 |
+
self.P3._succ = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
|
222 |
+
self.P3._pred = {0: {}, 1: {0: ed1}, 2: {1: ed2}}
|
223 |
+
# P3._adj is synced with P3._succ
|
224 |
+
self.P3._node = {}
|
225 |
+
self.P3._node[0] = {}
|
226 |
+
self.P3._node[1] = {}
|
227 |
+
self.P3._node[2] = {}
|
228 |
+
|
229 |
+
def test_data_input(self):
|
230 |
+
G = self.Graph({1: [2], 2: [1]}, name="test")
|
231 |
+
assert G.name == "test"
|
232 |
+
assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
|
233 |
+
assert sorted(G.succ.items()) == [(1, {2: {}}), (2, {1: {}})]
|
234 |
+
assert sorted(G.pred.items()) == [(1, {2: {}}), (2, {1: {}})]
|
235 |
+
|
236 |
+
def test_add_edge(self):
|
237 |
+
G = self.Graph()
|
238 |
+
G.add_edge(0, 1)
|
239 |
+
assert G.adj == {0: {1: {}}, 1: {}}
|
240 |
+
assert G.succ == {0: {1: {}}, 1: {}}
|
241 |
+
assert G.pred == {0: {}, 1: {0: {}}}
|
242 |
+
G = self.Graph()
|
243 |
+
G.add_edge(*(0, 1))
|
244 |
+
assert G.adj == {0: {1: {}}, 1: {}}
|
245 |
+
assert G.succ == {0: {1: {}}, 1: {}}
|
246 |
+
assert G.pred == {0: {}, 1: {0: {}}}
|
247 |
+
with pytest.raises(ValueError, match="None cannot be a node"):
|
248 |
+
G.add_edge(None, 3)
|
249 |
+
|
250 |
+
def test_add_edges_from(self):
|
251 |
+
G = self.Graph()
|
252 |
+
G.add_edges_from([(0, 1), (0, 2, {"data": 3})], data=2)
|
253 |
+
assert G.adj == {0: {1: {"data": 2}, 2: {"data": 3}}, 1: {}, 2: {}}
|
254 |
+
assert G.succ == {0: {1: {"data": 2}, 2: {"data": 3}}, 1: {}, 2: {}}
|
255 |
+
assert G.pred == {0: {}, 1: {0: {"data": 2}}, 2: {0: {"data": 3}}}
|
256 |
+
|
257 |
+
with pytest.raises(nx.NetworkXError):
|
258 |
+
G.add_edges_from([(0,)]) # too few in tuple
|
259 |
+
with pytest.raises(nx.NetworkXError):
|
260 |
+
G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
|
261 |
+
with pytest.raises(TypeError):
|
262 |
+
G.add_edges_from([0]) # not a tuple
|
263 |
+
with pytest.raises(ValueError, match="None cannot be a node"):
|
264 |
+
G.add_edges_from([(None, 3), (3, 2)])
|
265 |
+
|
266 |
+
def test_remove_edge(self):
|
267 |
+
G = self.K3.copy()
|
268 |
+
G.remove_edge(0, 1)
|
269 |
+
assert G.succ == {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}}
|
270 |
+
assert G.pred == {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
|
271 |
+
with pytest.raises(nx.NetworkXError):
|
272 |
+
G.remove_edge(-1, 0)
|
273 |
+
|
274 |
+
def test_remove_edges_from(self):
|
275 |
+
G = self.K3.copy()
|
276 |
+
G.remove_edges_from([(0, 1)])
|
277 |
+
assert G.succ == {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}}
|
278 |
+
assert G.pred == {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
|
279 |
+
G.remove_edges_from([(0, 0)]) # silent fail
|
280 |
+
|
281 |
+
def test_clear(self):
|
282 |
+
G = self.K3
|
283 |
+
G.graph["name"] = "K3"
|
284 |
+
G.clear()
|
285 |
+
assert list(G.nodes) == []
|
286 |
+
assert G.succ == {}
|
287 |
+
assert G.pred == {}
|
288 |
+
assert G.graph == {}
|
289 |
+
|
290 |
+
def test_clear_edges(self):
|
291 |
+
G = self.K3
|
292 |
+
G.graph["name"] = "K3"
|
293 |
+
nodes = list(G.nodes)
|
294 |
+
G.clear_edges()
|
295 |
+
assert list(G.nodes) == nodes
|
296 |
+
expected = {0: {}, 1: {}, 2: {}}
|
297 |
+
assert G.succ == expected
|
298 |
+
assert G.pred == expected
|
299 |
+
assert list(G.edges) == []
|
300 |
+
assert G.graph["name"] == "K3"
|
301 |
+
|
302 |
+
|
303 |
+
class TestEdgeSubgraph(_TestGraphEdgeSubgraph):
|
304 |
+
"""Unit tests for the :meth:`DiGraph.edge_subgraph` method."""
|
305 |
+
|
306 |
+
def setup_method(self):
|
307 |
+
# Create a doubly-linked path graph on five nodes.
|
308 |
+
G = nx.DiGraph(nx.path_graph(5))
|
309 |
+
# Add some node, edge, and graph attributes.
|
310 |
+
for i in range(5):
|
311 |
+
G.nodes[i]["name"] = f"node{i}"
|
312 |
+
G.edges[0, 1]["name"] = "edge01"
|
313 |
+
G.edges[3, 4]["name"] = "edge34"
|
314 |
+
G.graph["name"] = "graph"
|
315 |
+
# Get the subgraph induced by the first and last edges.
|
316 |
+
self.G = G
|
317 |
+
self.H = G.edge_subgraph([(0, 1), (3, 4)])
|
318 |
+
|
319 |
+
def test_pred_succ(self):
|
320 |
+
"""Test that nodes are added to predecessors and successors.
|
321 |
+
|
322 |
+
For more information, see GitHub issue #2370.
|
323 |
+
|
324 |
+
"""
|
325 |
+
G = nx.DiGraph()
|
326 |
+
G.add_edge(0, 1)
|
327 |
+
H = G.edge_subgraph([(0, 1)])
|
328 |
+
assert list(H.predecessors(0)) == []
|
329 |
+
assert list(H.successors(0)) == [1]
|
330 |
+
assert list(H.predecessors(1)) == [0]
|
331 |
+
assert list(H.successors(1)) == []
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_digraph_historical.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Original NetworkX graph tests"""
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
import networkx
|
5 |
+
import networkx as nx
|
6 |
+
|
7 |
+
from .historical_tests import HistoricalTests
|
8 |
+
|
9 |
+
|
10 |
+
class TestDiGraphHistorical(HistoricalTests):
|
11 |
+
@classmethod
|
12 |
+
def setup_class(cls):
|
13 |
+
HistoricalTests.setup_class()
|
14 |
+
cls.G = nx.DiGraph
|
15 |
+
|
16 |
+
def test_in_degree(self):
|
17 |
+
G = self.G()
|
18 |
+
G.add_nodes_from("GJK")
|
19 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
|
20 |
+
|
21 |
+
assert sorted(d for n, d in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2]
|
22 |
+
assert dict(G.in_degree()) == {
|
23 |
+
"A": 0,
|
24 |
+
"C": 2,
|
25 |
+
"B": 1,
|
26 |
+
"D": 2,
|
27 |
+
"G": 0,
|
28 |
+
"K": 0,
|
29 |
+
"J": 0,
|
30 |
+
}
|
31 |
+
|
32 |
+
def test_out_degree(self):
|
33 |
+
G = self.G()
|
34 |
+
G.add_nodes_from("GJK")
|
35 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
|
36 |
+
assert sorted(v for k, v in G.in_degree()) == [0, 0, 0, 0, 1, 2, 2]
|
37 |
+
assert dict(G.out_degree()) == {
|
38 |
+
"A": 2,
|
39 |
+
"C": 1,
|
40 |
+
"B": 2,
|
41 |
+
"D": 0,
|
42 |
+
"G": 0,
|
43 |
+
"K": 0,
|
44 |
+
"J": 0,
|
45 |
+
}
|
46 |
+
|
47 |
+
def test_degree_digraph(self):
|
48 |
+
H = nx.DiGraph()
|
49 |
+
H.add_edges_from([(1, 24), (1, 2)])
|
50 |
+
assert sorted(d for n, d in H.in_degree([1, 24])) == [0, 1]
|
51 |
+
assert sorted(d for n, d in H.out_degree([1, 24])) == [0, 2]
|
52 |
+
assert sorted(d for n, d in H.degree([1, 24])) == [1, 2]
|
53 |
+
|
54 |
+
def test_neighbors(self):
|
55 |
+
G = self.G()
|
56 |
+
G.add_nodes_from("GJK")
|
57 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
|
58 |
+
|
59 |
+
assert sorted(G.neighbors("C")) == ["D"]
|
60 |
+
assert sorted(G["C"]) == ["D"]
|
61 |
+
assert sorted(G.neighbors("A")) == ["B", "C"]
|
62 |
+
pytest.raises(nx.NetworkXError, G.neighbors, "j")
|
63 |
+
pytest.raises(nx.NetworkXError, G.neighbors, "j")
|
64 |
+
|
65 |
+
def test_successors(self):
|
66 |
+
G = self.G()
|
67 |
+
G.add_nodes_from("GJK")
|
68 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
|
69 |
+
assert sorted(G.successors("A")) == ["B", "C"]
|
70 |
+
assert sorted(G.successors("A")) == ["B", "C"]
|
71 |
+
assert sorted(G.successors("G")) == []
|
72 |
+
assert sorted(G.successors("D")) == []
|
73 |
+
assert sorted(G.successors("G")) == []
|
74 |
+
pytest.raises(nx.NetworkXError, G.successors, "j")
|
75 |
+
pytest.raises(nx.NetworkXError, G.successors, "j")
|
76 |
+
|
77 |
+
def test_predecessors(self):
|
78 |
+
G = self.G()
|
79 |
+
G.add_nodes_from("GJK")
|
80 |
+
G.add_edges_from([("A", "B"), ("A", "C"), ("B", "D"), ("B", "C"), ("C", "D")])
|
81 |
+
assert sorted(G.predecessors("C")) == ["A", "B"]
|
82 |
+
assert sorted(G.predecessors("C")) == ["A", "B"]
|
83 |
+
assert sorted(G.predecessors("G")) == []
|
84 |
+
assert sorted(G.predecessors("A")) == []
|
85 |
+
assert sorted(G.predecessors("G")) == []
|
86 |
+
assert sorted(G.predecessors("A")) == []
|
87 |
+
assert sorted(G.successors("D")) == []
|
88 |
+
|
89 |
+
pytest.raises(nx.NetworkXError, G.predecessors, "j")
|
90 |
+
pytest.raises(nx.NetworkXError, G.predecessors, "j")
|
91 |
+
|
92 |
+
def test_reverse(self):
|
93 |
+
G = nx.complete_graph(10)
|
94 |
+
H = G.to_directed()
|
95 |
+
HR = H.reverse()
|
96 |
+
assert nx.is_isomorphic(H, HR)
|
97 |
+
assert sorted(H.edges()) == sorted(HR.edges())
|
98 |
+
|
99 |
+
def test_reverse2(self):
|
100 |
+
H = nx.DiGraph()
|
101 |
+
foo = [H.add_edge(u, u + 1) for u in range(5)]
|
102 |
+
HR = H.reverse()
|
103 |
+
for u in range(5):
|
104 |
+
assert HR.has_edge(u + 1, u)
|
105 |
+
|
106 |
+
def test_reverse3(self):
|
107 |
+
H = nx.DiGraph()
|
108 |
+
H.add_nodes_from([1, 2, 3, 4])
|
109 |
+
HR = H.reverse()
|
110 |
+
assert sorted(HR.nodes()) == [1, 2, 3, 4]
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_filters.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
import networkx as nx
|
4 |
+
|
5 |
+
|
6 |
+
class TestFilterFactory:
|
7 |
+
def test_no_filter(self):
|
8 |
+
nf = nx.filters.no_filter
|
9 |
+
assert nf()
|
10 |
+
assert nf(1)
|
11 |
+
assert nf(2, 1)
|
12 |
+
|
13 |
+
def test_hide_nodes(self):
|
14 |
+
f = nx.classes.filters.hide_nodes([1, 2, 3])
|
15 |
+
assert not f(1)
|
16 |
+
assert not f(2)
|
17 |
+
assert not f(3)
|
18 |
+
assert f(4)
|
19 |
+
assert f(0)
|
20 |
+
assert f("a")
|
21 |
+
pytest.raises(TypeError, f, 1, 2)
|
22 |
+
pytest.raises(TypeError, f)
|
23 |
+
|
24 |
+
def test_show_nodes(self):
|
25 |
+
f = nx.classes.filters.show_nodes([1, 2, 3])
|
26 |
+
assert f(1)
|
27 |
+
assert f(2)
|
28 |
+
assert f(3)
|
29 |
+
assert not f(4)
|
30 |
+
assert not f(0)
|
31 |
+
assert not f("a")
|
32 |
+
pytest.raises(TypeError, f, 1, 2)
|
33 |
+
pytest.raises(TypeError, f)
|
34 |
+
|
35 |
+
def test_hide_edges(self):
|
36 |
+
factory = nx.classes.filters.hide_edges
|
37 |
+
f = factory([(1, 2), (3, 4)])
|
38 |
+
assert not f(1, 2)
|
39 |
+
assert not f(3, 4)
|
40 |
+
assert not f(4, 3)
|
41 |
+
assert f(2, 3)
|
42 |
+
assert f(0, -1)
|
43 |
+
assert f("a", "b")
|
44 |
+
pytest.raises(TypeError, f, 1, 2, 3)
|
45 |
+
pytest.raises(TypeError, f, 1)
|
46 |
+
pytest.raises(TypeError, f)
|
47 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
48 |
+
pytest.raises(ValueError, factory, [(1, 2, 3)])
|
49 |
+
|
50 |
+
def test_show_edges(self):
|
51 |
+
factory = nx.classes.filters.show_edges
|
52 |
+
f = factory([(1, 2), (3, 4)])
|
53 |
+
assert f(1, 2)
|
54 |
+
assert f(3, 4)
|
55 |
+
assert f(4, 3)
|
56 |
+
assert not f(2, 3)
|
57 |
+
assert not f(0, -1)
|
58 |
+
assert not f("a", "b")
|
59 |
+
pytest.raises(TypeError, f, 1, 2, 3)
|
60 |
+
pytest.raises(TypeError, f, 1)
|
61 |
+
pytest.raises(TypeError, f)
|
62 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
63 |
+
pytest.raises(ValueError, factory, [(1, 2, 3)])
|
64 |
+
|
65 |
+
def test_hide_diedges(self):
|
66 |
+
factory = nx.classes.filters.hide_diedges
|
67 |
+
f = factory([(1, 2), (3, 4)])
|
68 |
+
assert not f(1, 2)
|
69 |
+
assert not f(3, 4)
|
70 |
+
assert f(4, 3)
|
71 |
+
assert f(2, 3)
|
72 |
+
assert f(0, -1)
|
73 |
+
assert f("a", "b")
|
74 |
+
pytest.raises(TypeError, f, 1, 2, 3)
|
75 |
+
pytest.raises(TypeError, f, 1)
|
76 |
+
pytest.raises(TypeError, f)
|
77 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
78 |
+
pytest.raises(ValueError, factory, [(1, 2, 3)])
|
79 |
+
|
80 |
+
def test_show_diedges(self):
|
81 |
+
factory = nx.classes.filters.show_diedges
|
82 |
+
f = factory([(1, 2), (3, 4)])
|
83 |
+
assert f(1, 2)
|
84 |
+
assert f(3, 4)
|
85 |
+
assert not f(4, 3)
|
86 |
+
assert not f(2, 3)
|
87 |
+
assert not f(0, -1)
|
88 |
+
assert not f("a", "b")
|
89 |
+
pytest.raises(TypeError, f, 1, 2, 3)
|
90 |
+
pytest.raises(TypeError, f, 1)
|
91 |
+
pytest.raises(TypeError, f)
|
92 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
93 |
+
pytest.raises(ValueError, factory, [(1, 2, 3)])
|
94 |
+
|
95 |
+
def test_hide_multiedges(self):
|
96 |
+
factory = nx.classes.filters.hide_multiedges
|
97 |
+
f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
|
98 |
+
assert not f(1, 2, 0)
|
99 |
+
assert not f(1, 2, 1)
|
100 |
+
assert f(1, 2, 2)
|
101 |
+
assert f(3, 4, 0)
|
102 |
+
assert not f(3, 4, 1)
|
103 |
+
assert not f(4, 3, 1)
|
104 |
+
assert f(4, 3, 0)
|
105 |
+
assert f(2, 3, 0)
|
106 |
+
assert f(0, -1, 0)
|
107 |
+
assert f("a", "b", 0)
|
108 |
+
pytest.raises(TypeError, f, 1, 2, 3, 4)
|
109 |
+
pytest.raises(TypeError, f, 1, 2)
|
110 |
+
pytest.raises(TypeError, f, 1)
|
111 |
+
pytest.raises(TypeError, f)
|
112 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
113 |
+
pytest.raises(ValueError, factory, [(1, 2)])
|
114 |
+
pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
|
115 |
+
|
116 |
+
def test_show_multiedges(self):
|
117 |
+
factory = nx.classes.filters.show_multiedges
|
118 |
+
f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
|
119 |
+
assert f(1, 2, 0)
|
120 |
+
assert f(1, 2, 1)
|
121 |
+
assert not f(1, 2, 2)
|
122 |
+
assert not f(3, 4, 0)
|
123 |
+
assert f(3, 4, 1)
|
124 |
+
assert f(4, 3, 1)
|
125 |
+
assert not f(4, 3, 0)
|
126 |
+
assert not f(2, 3, 0)
|
127 |
+
assert not f(0, -1, 0)
|
128 |
+
assert not f("a", "b", 0)
|
129 |
+
pytest.raises(TypeError, f, 1, 2, 3, 4)
|
130 |
+
pytest.raises(TypeError, f, 1, 2)
|
131 |
+
pytest.raises(TypeError, f, 1)
|
132 |
+
pytest.raises(TypeError, f)
|
133 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
134 |
+
pytest.raises(ValueError, factory, [(1, 2)])
|
135 |
+
pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
|
136 |
+
|
137 |
+
def test_hide_multidiedges(self):
|
138 |
+
factory = nx.classes.filters.hide_multidiedges
|
139 |
+
f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
|
140 |
+
assert not f(1, 2, 0)
|
141 |
+
assert not f(1, 2, 1)
|
142 |
+
assert f(1, 2, 2)
|
143 |
+
assert f(3, 4, 0)
|
144 |
+
assert not f(3, 4, 1)
|
145 |
+
assert f(4, 3, 1)
|
146 |
+
assert f(4, 3, 0)
|
147 |
+
assert f(2, 3, 0)
|
148 |
+
assert f(0, -1, 0)
|
149 |
+
assert f("a", "b", 0)
|
150 |
+
pytest.raises(TypeError, f, 1, 2, 3, 4)
|
151 |
+
pytest.raises(TypeError, f, 1, 2)
|
152 |
+
pytest.raises(TypeError, f, 1)
|
153 |
+
pytest.raises(TypeError, f)
|
154 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
155 |
+
pytest.raises(ValueError, factory, [(1, 2)])
|
156 |
+
pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
|
157 |
+
|
158 |
+
def test_show_multidiedges(self):
|
159 |
+
factory = nx.classes.filters.show_multidiedges
|
160 |
+
f = factory([(1, 2, 0), (3, 4, 1), (1, 2, 1)])
|
161 |
+
assert f(1, 2, 0)
|
162 |
+
assert f(1, 2, 1)
|
163 |
+
assert not f(1, 2, 2)
|
164 |
+
assert not f(3, 4, 0)
|
165 |
+
assert f(3, 4, 1)
|
166 |
+
assert not f(4, 3, 1)
|
167 |
+
assert not f(4, 3, 0)
|
168 |
+
assert not f(2, 3, 0)
|
169 |
+
assert not f(0, -1, 0)
|
170 |
+
assert not f("a", "b", 0)
|
171 |
+
pytest.raises(TypeError, f, 1, 2, 3, 4)
|
172 |
+
pytest.raises(TypeError, f, 1, 2)
|
173 |
+
pytest.raises(TypeError, f, 1)
|
174 |
+
pytest.raises(TypeError, f)
|
175 |
+
pytest.raises(TypeError, factory, [1, 2, 3])
|
176 |
+
pytest.raises(ValueError, factory, [(1, 2)])
|
177 |
+
pytest.raises(ValueError, factory, [(1, 2, 3, 4)])
|
llmeval-env/lib/python3.10/site-packages/networkx/classes/tests/test_function.py
ADDED
@@ -0,0 +1,787 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
import networkx as nx
|
6 |
+
from networkx.utils import edges_equal, nodes_equal
|
7 |
+
|
8 |
+
|
9 |
+
def test_degree_histogram_empty():
|
10 |
+
G = nx.Graph()
|
11 |
+
assert nx.degree_histogram(G) == []
|
12 |
+
|
13 |
+
|
14 |
+
class TestFunction:
|
15 |
+
def setup_method(self):
|
16 |
+
self.G = nx.Graph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}, name="Test")
|
17 |
+
self.Gdegree = {0: 3, 1: 2, 2: 2, 3: 1, 4: 0}
|
18 |
+
self.Gnodes = list(range(5))
|
19 |
+
self.Gedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
|
20 |
+
self.DG = nx.DiGraph({0: [1, 2, 3], 1: [1, 2, 0], 4: []})
|
21 |
+
self.DGin_degree = {0: 1, 1: 2, 2: 2, 3: 1, 4: 0}
|
22 |
+
self.DGout_degree = {0: 3, 1: 3, 2: 0, 3: 0, 4: 0}
|
23 |
+
self.DGnodes = list(range(5))
|
24 |
+
self.DGedges = [(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)]
|
25 |
+
|
26 |
+
def test_nodes(self):
|
27 |
+
assert nodes_equal(self.G.nodes(), list(nx.nodes(self.G)))
|
28 |
+
assert nodes_equal(self.DG.nodes(), list(nx.nodes(self.DG)))
|
29 |
+
|
30 |
+
def test_edges(self):
|
31 |
+
assert edges_equal(self.G.edges(), list(nx.edges(self.G)))
|
32 |
+
assert sorted(self.DG.edges()) == sorted(nx.edges(self.DG))
|
33 |
+
assert edges_equal(
|
34 |
+
self.G.edges(nbunch=[0, 1, 3]), list(nx.edges(self.G, nbunch=[0, 1, 3]))
|
35 |
+
)
|
36 |
+
assert sorted(self.DG.edges(nbunch=[0, 1, 3])) == sorted(
|
37 |
+
nx.edges(self.DG, nbunch=[0, 1, 3])
|
38 |
+
)
|
39 |
+
|
40 |
+
def test_degree(self):
|
41 |
+
assert edges_equal(self.G.degree(), list(nx.degree(self.G)))
|
42 |
+
assert sorted(self.DG.degree()) == sorted(nx.degree(self.DG))
|
43 |
+
assert edges_equal(
|
44 |
+
self.G.degree(nbunch=[0, 1]), list(nx.degree(self.G, nbunch=[0, 1]))
|
45 |
+
)
|
46 |
+
assert sorted(self.DG.degree(nbunch=[0, 1])) == sorted(
|
47 |
+
nx.degree(self.DG, nbunch=[0, 1])
|
48 |
+
)
|
49 |
+
assert edges_equal(
|
50 |
+
self.G.degree(weight="weight"), list(nx.degree(self.G, weight="weight"))
|
51 |
+
)
|
52 |
+
assert sorted(self.DG.degree(weight="weight")) == sorted(
|
53 |
+
nx.degree(self.DG, weight="weight")
|
54 |
+
)
|
55 |
+
|
56 |
+
def test_neighbors(self):
|
57 |
+
assert list(self.G.neighbors(1)) == list(nx.neighbors(self.G, 1))
|
58 |
+
assert list(self.DG.neighbors(1)) == list(nx.neighbors(self.DG, 1))
|
59 |
+
|
60 |
+
def test_number_of_nodes(self):
|
61 |
+
assert self.G.number_of_nodes() == nx.number_of_nodes(self.G)
|
62 |
+
assert self.DG.number_of_nodes() == nx.number_of_nodes(self.DG)
|
63 |
+
|
64 |
+
def test_number_of_edges(self):
|
65 |
+
assert self.G.number_of_edges() == nx.number_of_edges(self.G)
|
66 |
+
assert self.DG.number_of_edges() == nx.number_of_edges(self.DG)
|
67 |
+
|
68 |
+
def test_is_directed(self):
|
69 |
+
assert self.G.is_directed() == nx.is_directed(self.G)
|
70 |
+
assert self.DG.is_directed() == nx.is_directed(self.DG)
|
71 |
+
|
72 |
+
def test_add_star(self):
|
73 |
+
G = self.G.copy()
|
74 |
+
nlist = [12, 13, 14, 15]
|
75 |
+
nx.add_star(G, nlist)
|
76 |
+
assert edges_equal(G.edges(nlist), [(12, 13), (12, 14), (12, 15)])
|
77 |
+
|
78 |
+
G = self.G.copy()
|
79 |
+
nx.add_star(G, nlist, weight=2.0)
|
80 |
+
assert edges_equal(
|
81 |
+
G.edges(nlist, data=True),
|
82 |
+
[
|
83 |
+
(12, 13, {"weight": 2.0}),
|
84 |
+
(12, 14, {"weight": 2.0}),
|
85 |
+
(12, 15, {"weight": 2.0}),
|
86 |
+
],
|
87 |
+
)
|
88 |
+
|
89 |
+
G = self.G.copy()
|
90 |
+
nlist = [12]
|
91 |
+
nx.add_star(G, nlist)
|
92 |
+
assert nodes_equal(G, list(self.G) + nlist)
|
93 |
+
|
94 |
+
G = self.G.copy()
|
95 |
+
nlist = []
|
96 |
+
nx.add_star(G, nlist)
|
97 |
+
assert nodes_equal(G.nodes, self.Gnodes)
|
98 |
+
assert edges_equal(G.edges, self.G.edges)
|
99 |
+
|
100 |
+
def test_add_path(self):
|
101 |
+
G = self.G.copy()
|
102 |
+
nlist = [12, 13, 14, 15]
|
103 |
+
nx.add_path(G, nlist)
|
104 |
+
assert edges_equal(G.edges(nlist), [(12, 13), (13, 14), (14, 15)])
|
105 |
+
G = self.G.copy()
|
106 |
+
nx.add_path(G, nlist, weight=2.0)
|
107 |
+
assert edges_equal(
|
108 |
+
G.edges(nlist, data=True),
|
109 |
+
[
|
110 |
+
(12, 13, {"weight": 2.0}),
|
111 |
+
(13, 14, {"weight": 2.0}),
|
112 |
+
(14, 15, {"weight": 2.0}),
|
113 |
+
],
|
114 |
+
)
|
115 |
+
|
116 |
+
G = self.G.copy()
|
117 |
+
nlist = ["node"]
|
118 |
+
nx.add_path(G, nlist)
|
119 |
+
assert edges_equal(G.edges(nlist), [])
|
120 |
+
assert nodes_equal(G, list(self.G) + ["node"])
|
121 |
+
|
122 |
+
G = self.G.copy()
|
123 |
+
nlist = iter(["node"])
|
124 |
+
nx.add_path(G, nlist)
|
125 |
+
assert edges_equal(G.edges(["node"]), [])
|
126 |
+
assert nodes_equal(G, list(self.G) + ["node"])
|
127 |
+
|
128 |
+
G = self.G.copy()
|
129 |
+
nlist = [12]
|
130 |
+
nx.add_path(G, nlist)
|
131 |
+
assert edges_equal(G.edges(nlist), [])
|
132 |
+
assert nodes_equal(G, list(self.G) + [12])
|
133 |
+
|
134 |
+
G = self.G.copy()
|
135 |
+
nlist = iter([12])
|
136 |
+
nx.add_path(G, nlist)
|
137 |
+
assert edges_equal(G.edges([12]), [])
|
138 |
+
assert nodes_equal(G, list(self.G) + [12])
|
139 |
+
|
140 |
+
G = self.G.copy()
|
141 |
+
nlist = []
|
142 |
+
nx.add_path(G, nlist)
|
143 |
+
assert edges_equal(G.edges, self.G.edges)
|
144 |
+
assert nodes_equal(G, list(self.G))
|
145 |
+
|
146 |
+
G = self.G.copy()
|
147 |
+
nlist = iter([])
|
148 |
+
nx.add_path(G, nlist)
|
149 |
+
assert edges_equal(G.edges, self.G.edges)
|
150 |
+
assert nodes_equal(G, list(self.G))
|
151 |
+
|
152 |
+
def test_add_cycle(self):
|
153 |
+
G = self.G.copy()
|
154 |
+
nlist = [12, 13, 14, 15]
|
155 |
+
oklists = [
|
156 |
+
[(12, 13), (12, 15), (13, 14), (14, 15)],
|
157 |
+
[(12, 13), (13, 14), (14, 15), (15, 12)],
|
158 |
+
]
|
159 |
+
nx.add_cycle(G, nlist)
|
160 |
+
assert sorted(G.edges(nlist)) in oklists
|
161 |
+
G = self.G.copy()
|
162 |
+
oklists = [
|
163 |
+
[
|
164 |
+
(12, 13, {"weight": 1.0}),
|
165 |
+
(12, 15, {"weight": 1.0}),
|
166 |
+
(13, 14, {"weight": 1.0}),
|
167 |
+
(14, 15, {"weight": 1.0}),
|
168 |
+
],
|
169 |
+
[
|
170 |
+
(12, 13, {"weight": 1.0}),
|
171 |
+
(13, 14, {"weight": 1.0}),
|
172 |
+
(14, 15, {"weight": 1.0}),
|
173 |
+
(15, 12, {"weight": 1.0}),
|
174 |
+
],
|
175 |
+
]
|
176 |
+
nx.add_cycle(G, nlist, weight=1.0)
|
177 |
+
assert sorted(G.edges(nlist, data=True)) in oklists
|
178 |
+
|
179 |
+
G = self.G.copy()
|
180 |
+
nlist = [12]
|
181 |
+
nx.add_cycle(G, nlist)
|
182 |
+
assert nodes_equal(G, list(self.G) + nlist)
|
183 |
+
|
184 |
+
G = self.G.copy()
|
185 |
+
nlist = []
|
186 |
+
nx.add_cycle(G, nlist)
|
187 |
+
assert nodes_equal(G.nodes, self.Gnodes)
|
188 |
+
assert edges_equal(G.edges, self.G.edges)
|
189 |
+
|
190 |
+
def test_subgraph(self):
|
191 |
+
assert (
|
192 |
+
self.G.subgraph([0, 1, 2, 4]).adj == nx.subgraph(self.G, [0, 1, 2, 4]).adj
|
193 |
+
)
|
194 |
+
assert (
|
195 |
+
self.DG.subgraph([0, 1, 2, 4]).adj == nx.subgraph(self.DG, [0, 1, 2, 4]).adj
|
196 |
+
)
|
197 |
+
assert (
|
198 |
+
self.G.subgraph([0, 1, 2, 4]).adj
|
199 |
+
== nx.induced_subgraph(self.G, [0, 1, 2, 4]).adj
|
200 |
+
)
|
201 |
+
assert (
|
202 |
+
self.DG.subgraph([0, 1, 2, 4]).adj
|
203 |
+
== nx.induced_subgraph(self.DG, [0, 1, 2, 4]).adj
|
204 |
+
)
|
205 |
+
# subgraph-subgraph chain is allowed in function interface
|
206 |
+
H = nx.induced_subgraph(self.G.subgraph([0, 1, 2, 4]), [0, 1, 4])
|
207 |
+
assert H._graph is not self.G
|
208 |
+
assert H.adj == self.G.subgraph([0, 1, 4]).adj
|
209 |
+
|
210 |
+
def test_edge_subgraph(self):
|
211 |
+
assert (
|
212 |
+
self.G.edge_subgraph([(1, 2), (0, 3)]).adj
|
213 |
+
== nx.edge_subgraph(self.G, [(1, 2), (0, 3)]).adj
|
214 |
+
)
|
215 |
+
assert (
|
216 |
+
self.DG.edge_subgraph([(1, 2), (0, 3)]).adj
|
217 |
+
== nx.edge_subgraph(self.DG, [(1, 2), (0, 3)]).adj
|
218 |
+
)
|
219 |
+
|
220 |
+
def test_create_empty_copy(self):
|
221 |
+
G = nx.create_empty_copy(self.G, with_data=False)
|
222 |
+
assert nodes_equal(G, list(self.G))
|
223 |
+
assert G.graph == {}
|
224 |
+
assert G._node == {}.fromkeys(self.G.nodes(), {})
|
225 |
+
assert G._adj == {}.fromkeys(self.G.nodes(), {})
|
226 |
+
G = nx.create_empty_copy(self.G)
|
227 |
+
assert nodes_equal(G, list(self.G))
|
228 |
+
assert G.graph == self.G.graph
|
229 |
+
assert G._node == self.G._node
|
230 |
+
assert G._adj == {}.fromkeys(self.G.nodes(), {})
|
231 |
+
|
232 |
+
def test_degree_histogram(self):
|
233 |
+
assert nx.degree_histogram(self.G) == [1, 1, 1, 1, 1]
|
234 |
+
|
235 |
+
def test_density(self):
|
236 |
+
assert nx.density(self.G) == 0.5
|
237 |
+
assert nx.density(self.DG) == 0.3
|
238 |
+
G = nx.Graph()
|
239 |
+
G.add_node(1)
|
240 |
+
assert nx.density(G) == 0.0
|
241 |
+
|
242 |
+
def test_density_selfloop(self):
|
243 |
+
G = nx.Graph()
|
244 |
+
G.add_edge(1, 1)
|
245 |
+
assert nx.density(G) == 0.0
|
246 |
+
G.add_edge(1, 2)
|
247 |
+
assert nx.density(G) == 2.0
|
248 |
+
|
249 |
+
def test_freeze(self):
|
250 |
+
G = nx.freeze(self.G)
|
251 |
+
assert G.frozen
|
252 |
+
pytest.raises(nx.NetworkXError, G.add_node, 1)
|
253 |
+
pytest.raises(nx.NetworkXError, G.add_nodes_from, [1])
|
254 |
+
pytest.raises(nx.NetworkXError, G.remove_node, 1)
|
255 |
+
pytest.raises(nx.NetworkXError, G.remove_nodes_from, [1])
|
256 |
+
pytest.raises(nx.NetworkXError, G.add_edge, 1, 2)
|
257 |
+
pytest.raises(nx.NetworkXError, G.add_edges_from, [(1, 2)])
|
258 |
+
pytest.raises(nx.NetworkXError, G.remove_edge, 1, 2)
|
259 |
+
pytest.raises(nx.NetworkXError, G.remove_edges_from, [(1, 2)])
|
260 |
+
pytest.raises(nx.NetworkXError, G.clear_edges)
|
261 |
+
pytest.raises(nx.NetworkXError, G.clear)
|
262 |
+
|
263 |
+
def test_is_frozen(self):
|
264 |
+
assert not nx.is_frozen(self.G)
|
265 |
+
G = nx.freeze(self.G)
|
266 |
+
assert G.frozen == nx.is_frozen(self.G)
|
267 |
+
assert G.frozen
|
268 |
+
|
269 |
+
def test_node_attributes_are_still_mutable_on_frozen_graph(self):
|
270 |
+
G = nx.freeze(nx.path_graph(3))
|
271 |
+
node = G.nodes[0]
|
272 |
+
node["node_attribute"] = True
|
273 |
+
assert node["node_attribute"] == True
|
274 |
+
|
275 |
+
def test_edge_attributes_are_still_mutable_on_frozen_graph(self):
|
276 |
+
G = nx.freeze(nx.path_graph(3))
|
277 |
+
edge = G.edges[(0, 1)]
|
278 |
+
edge["edge_attribute"] = True
|
279 |
+
assert edge["edge_attribute"] == True
|
280 |
+
|
281 |
+
def test_neighbors_complete_graph(self):
|
282 |
+
graph = nx.complete_graph(100)
|
283 |
+
pop = random.sample(list(graph), 1)
|
284 |
+
nbors = list(nx.neighbors(graph, pop[0]))
|
285 |
+
# should be all the other vertices in the graph
|
286 |
+
assert len(nbors) == len(graph) - 1
|
287 |
+
|
288 |
+
graph = nx.path_graph(100)
|
289 |
+
node = random.sample(list(graph), 1)[0]
|
290 |
+
nbors = list(nx.neighbors(graph, node))
|
291 |
+
# should be all the other vertices in the graph
|
292 |
+
if node != 0 and node != 99:
|
293 |
+
assert len(nbors) == 2
|
294 |
+
else:
|
295 |
+
assert len(nbors) == 1
|
296 |
+
|
297 |
+
# create a star graph with 99 outer nodes
|
298 |
+
graph = nx.star_graph(99)
|
299 |
+
nbors = list(nx.neighbors(graph, 0))
|
300 |
+
assert len(nbors) == 99
|
301 |
+
|
302 |
+
def test_non_neighbors(self):
|
303 |
+
graph = nx.complete_graph(100)
|
304 |
+
pop = random.sample(list(graph), 1)
|
305 |
+
nbors = nx.non_neighbors(graph, pop[0])
|
306 |
+
# should be all the other vertices in the graph
|
307 |
+
assert len(nbors) == 0
|
308 |
+
|
309 |
+
graph = nx.path_graph(100)
|
310 |
+
node = random.sample(list(graph), 1)[0]
|
311 |
+
nbors = nx.non_neighbors(graph, node)
|
312 |
+
# should be all the other vertices in the graph
|
313 |
+
if node != 0 and node != 99:
|
314 |
+
assert len(nbors) == 97
|
315 |
+
else:
|
316 |
+
assert len(nbors) == 98
|
317 |
+
|
318 |
+
# create a star graph with 99 outer nodes
|
319 |
+
graph = nx.star_graph(99)
|
320 |
+
nbors = nx.non_neighbors(graph, 0)
|
321 |
+
assert len(nbors) == 0
|
322 |
+
|
323 |
+
# disconnected graph
|
324 |
+
graph = nx.Graph()
|
325 |
+
graph.add_nodes_from(range(10))
|
326 |
+
nbors = nx.non_neighbors(graph, 0)
|
327 |
+
assert len(nbors) == 9
|
328 |
+
|
329 |
+
def test_non_edges(self):
|
330 |
+
# All possible edges exist
|
331 |
+
graph = nx.complete_graph(5)
|
332 |
+
nedges = list(nx.non_edges(graph))
|
333 |
+
assert len(nedges) == 0
|
334 |
+
|
335 |
+
graph = nx.path_graph(4)
|
336 |
+
expected = [(0, 2), (0, 3), (1, 3)]
|
337 |
+
nedges = list(nx.non_edges(graph))
|
338 |
+
for u, v in expected:
|
339 |
+
assert (u, v) in nedges or (v, u) in nedges
|
340 |
+
|
341 |
+
graph = nx.star_graph(4)
|
342 |
+
expected = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
|
343 |
+
nedges = list(nx.non_edges(graph))
|
344 |
+
for u, v in expected:
|
345 |
+
assert (u, v) in nedges or (v, u) in nedges
|
346 |
+
|
347 |
+
# Directed graphs
|
348 |
+
graph = nx.DiGraph()
|
349 |
+
graph.add_edges_from([(0, 2), (2, 0), (2, 1)])
|
350 |
+
expected = [(0, 1), (1, 0), (1, 2)]
|
351 |
+
nedges = list(nx.non_edges(graph))
|
352 |
+
for e in expected:
|
353 |
+
assert e in nedges
|
354 |
+
|
355 |
+
def test_is_weighted(self):
|
356 |
+
G = nx.Graph()
|
357 |
+
assert not nx.is_weighted(G)
|
358 |
+
|
359 |
+
G = nx.path_graph(4)
|
360 |
+
assert not nx.is_weighted(G)
|
361 |
+
assert not nx.is_weighted(G, (2, 3))
|
362 |
+
|
363 |
+
G.add_node(4)
|
364 |
+
G.add_edge(3, 4, weight=4)
|
365 |
+
assert not nx.is_weighted(G)
|
366 |
+
assert nx.is_weighted(G, (3, 4))
|
367 |
+
|
368 |
+
G = nx.DiGraph()
|
369 |
+
G.add_weighted_edges_from(
|
370 |
+
[
|
371 |
+
("0", "3", 3),
|
372 |
+
("0", "1", -5),
|
373 |
+
("1", "0", -5),
|
374 |
+
("0", "2", 2),
|
375 |
+
("1", "2", 4),
|
376 |
+
("2", "3", 1),
|
377 |
+
]
|
378 |
+
)
|
379 |
+
assert nx.is_weighted(G)
|
380 |
+
assert nx.is_weighted(G, ("1", "0"))
|
381 |
+
|
382 |
+
G = G.to_undirected()
|
383 |
+
assert nx.is_weighted(G)
|
384 |
+
assert nx.is_weighted(G, ("1", "0"))
|
385 |
+
|
386 |
+
pytest.raises(nx.NetworkXError, nx.is_weighted, G, (1, 2))
|
387 |
+
|
388 |
+
def test_is_negatively_weighted(self):
|
389 |
+
G = nx.Graph()
|
390 |
+
assert not nx.is_negatively_weighted(G)
|
391 |
+
|
392 |
+
G.add_node(1)
|
393 |
+
G.add_nodes_from([2, 3, 4, 5])
|
394 |
+
assert not nx.is_negatively_weighted(G)
|
395 |
+
|
396 |
+
G.add_edge(1, 2, weight=4)
|
397 |
+
assert not nx.is_negatively_weighted(G, (1, 2))
|
398 |
+
|
399 |
+
G.add_edges_from([(1, 3), (2, 4), (2, 6)])
|
400 |
+
G[1][3]["color"] = "blue"
|
401 |
+
assert not nx.is_negatively_weighted(G)
|
402 |
+
assert not nx.is_negatively_weighted(G, (1, 3))
|
403 |
+
|
404 |
+
G[2][4]["weight"] = -2
|
405 |
+
assert nx.is_negatively_weighted(G, (2, 4))
|
406 |
+
assert nx.is_negatively_weighted(G)
|
407 |
+
|
408 |
+
G = nx.DiGraph()
|
409 |
+
G.add_weighted_edges_from(
|
410 |
+
[
|
411 |
+
("0", "3", 3),
|
412 |
+
("0", "1", -5),
|
413 |
+
("1", "0", -2),
|
414 |
+
("0", "2", 2),
|
415 |
+
("1", "2", -3),
|
416 |
+
("2", "3", 1),
|
417 |
+
]
|
418 |
+
)
|
419 |
+
assert nx.is_negatively_weighted(G)
|
420 |
+
assert not nx.is_negatively_weighted(G, ("0", "3"))
|
421 |
+
assert nx.is_negatively_weighted(G, ("1", "0"))
|
422 |
+
|
423 |
+
pytest.raises(nx.NetworkXError, nx.is_negatively_weighted, G, (1, 4))
|
424 |
+
|
425 |
+
|
426 |
+
class TestCommonNeighbors:
|
427 |
+
@classmethod
|
428 |
+
def setup_class(cls):
|
429 |
+
cls.func = staticmethod(nx.common_neighbors)
|
430 |
+
|
431 |
+
def test_func(G, u, v, expected):
|
432 |
+
result = sorted(cls.func(G, u, v))
|
433 |
+
assert result == expected
|
434 |
+
|
435 |
+
cls.test = staticmethod(test_func)
|
436 |
+
|
437 |
+
def test_K5(self):
|
438 |
+
G = nx.complete_graph(5)
|
439 |
+
self.test(G, 0, 1, [2, 3, 4])
|
440 |
+
|
441 |
+
def test_P3(self):
|
442 |
+
G = nx.path_graph(3)
|
443 |
+
self.test(G, 0, 2, [1])
|
444 |
+
|
445 |
+
def test_S4(self):
|
446 |
+
G = nx.star_graph(4)
|
447 |
+
self.test(G, 1, 2, [0])
|
448 |
+
|
449 |
+
def test_digraph(self):
|
450 |
+
with pytest.raises(nx.NetworkXNotImplemented):
|
451 |
+
G = nx.DiGraph()
|
452 |
+
G.add_edges_from([(0, 1), (1, 2)])
|
453 |
+
self.func(G, 0, 2)
|
454 |
+
|
455 |
+
def test_nonexistent_nodes(self):
|
456 |
+
G = nx.complete_graph(5)
|
457 |
+
pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 5, 4)
|
458 |
+
pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 4, 5)
|
459 |
+
pytest.raises(nx.NetworkXError, nx.common_neighbors, G, 5, 6)
|
460 |
+
|
461 |
+
def test_custom1(self):
|
462 |
+
"""Case of no common neighbors."""
|
463 |
+
G = nx.Graph()
|
464 |
+
G.add_nodes_from([0, 1])
|
465 |
+
self.test(G, 0, 1, [])
|
466 |
+
|
467 |
+
def test_custom2(self):
|
468 |
+
"""Case of equal nodes."""
|
469 |
+
G = nx.complete_graph(4)
|
470 |
+
self.test(G, 0, 0, [1, 2, 3])
|
471 |
+
|
472 |
+
|
473 |
+
@pytest.mark.parametrize(
|
474 |
+
"graph_type", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
|
475 |
+
)
|
476 |
+
def test_set_node_attributes(graph_type):
|
477 |
+
# Test single value
|
478 |
+
G = nx.path_graph(3, create_using=graph_type)
|
479 |
+
vals = 100
|
480 |
+
attr = "hello"
|
481 |
+
nx.set_node_attributes(G, vals, attr)
|
482 |
+
assert G.nodes[0][attr] == vals
|
483 |
+
assert G.nodes[1][attr] == vals
|
484 |
+
assert G.nodes[2][attr] == vals
|
485 |
+
|
486 |
+
# Test dictionary
|
487 |
+
G = nx.path_graph(3, create_using=graph_type)
|
488 |
+
vals = dict(zip(sorted(G.nodes()), range(len(G))))
|
489 |
+
attr = "hi"
|
490 |
+
nx.set_node_attributes(G, vals, attr)
|
491 |
+
assert G.nodes[0][attr] == 0
|
492 |
+
assert G.nodes[1][attr] == 1
|
493 |
+
assert G.nodes[2][attr] == 2
|
494 |
+
|
495 |
+
# Test dictionary of dictionaries
|
496 |
+
G = nx.path_graph(3, create_using=graph_type)
|
497 |
+
d = {"hi": 0, "hello": 200}
|
498 |
+
vals = dict.fromkeys(G.nodes(), d)
|
499 |
+
vals.pop(0)
|
500 |
+
nx.set_node_attributes(G, vals)
|
501 |
+
assert G.nodes[0] == {}
|
502 |
+
assert G.nodes[1]["hi"] == 0
|
503 |
+
assert G.nodes[2]["hello"] == 200
|
504 |
+
|
505 |
+
|
506 |
+
@pytest.mark.parametrize(
|
507 |
+
("values", "name"),
|
508 |
+
(
|
509 |
+
({0: "red", 1: "blue"}, "color"), # values dictionary
|
510 |
+
({0: {"color": "red"}, 1: {"color": "blue"}}, None), # dict-of-dict
|
511 |
+
),
|
512 |
+
)
|
513 |
+
def test_set_node_attributes_ignores_extra_nodes(values, name):
|
514 |
+
"""
|
515 |
+
When `values` is a dict or dict-of-dict keyed by nodes, ensure that keys
|
516 |
+
that correspond to nodes not in G are ignored.
|
517 |
+
"""
|
518 |
+
G = nx.Graph()
|
519 |
+
G.add_node(0)
|
520 |
+
nx.set_node_attributes(G, values, name)
|
521 |
+
assert G.nodes[0]["color"] == "red"
|
522 |
+
assert 1 not in G.nodes
|
523 |
+
|
524 |
+
|
525 |
+
@pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
|
526 |
+
def test_set_edge_attributes(graph_type):
|
527 |
+
# Test single value
|
528 |
+
G = nx.path_graph(3, create_using=graph_type)
|
529 |
+
attr = "hello"
|
530 |
+
vals = 3
|
531 |
+
nx.set_edge_attributes(G, vals, attr)
|
532 |
+
assert G[0][1][attr] == vals
|
533 |
+
assert G[1][2][attr] == vals
|
534 |
+
|
535 |
+
# Test multiple values
|
536 |
+
G = nx.path_graph(3, create_using=graph_type)
|
537 |
+
attr = "hi"
|
538 |
+
edges = [(0, 1), (1, 2)]
|
539 |
+
vals = dict(zip(edges, range(len(edges))))
|
540 |
+
nx.set_edge_attributes(G, vals, attr)
|
541 |
+
assert G[0][1][attr] == 0
|
542 |
+
assert G[1][2][attr] == 1
|
543 |
+
|
544 |
+
# Test dictionary of dictionaries
|
545 |
+
G = nx.path_graph(3, create_using=graph_type)
|
546 |
+
d = {"hi": 0, "hello": 200}
|
547 |
+
edges = [(0, 1)]
|
548 |
+
vals = dict.fromkeys(edges, d)
|
549 |
+
nx.set_edge_attributes(G, vals)
|
550 |
+
assert G[0][1]["hi"] == 0
|
551 |
+
assert G[0][1]["hello"] == 200
|
552 |
+
assert G[1][2] == {}
|
553 |
+
|
554 |
+
|
555 |
+
@pytest.mark.parametrize(
|
556 |
+
("values", "name"),
|
557 |
+
(
|
558 |
+
({(0, 1): 1.0, (0, 2): 2.0}, "weight"), # values dict
|
559 |
+
({(0, 1): {"weight": 1.0}, (0, 2): {"weight": 2.0}}, None), # values dod
|
560 |
+
),
|
561 |
+
)
|
562 |
+
def test_set_edge_attributes_ignores_extra_edges(values, name):
|
563 |
+
"""If `values` is a dict or dict-of-dicts containing edges that are not in
|
564 |
+
G, data associate with these edges should be ignored.
|
565 |
+
"""
|
566 |
+
G = nx.Graph([(0, 1)])
|
567 |
+
nx.set_edge_attributes(G, values, name)
|
568 |
+
assert G[0][1]["weight"] == 1.0
|
569 |
+
assert (0, 2) not in G.edges
|
570 |
+
|
571 |
+
|
572 |
+
@pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
|
573 |
+
def test_set_edge_attributes_multi(graph_type):
|
574 |
+
# Test single value
|
575 |
+
G = nx.path_graph(3, create_using=graph_type)
|
576 |
+
attr = "hello"
|
577 |
+
vals = 3
|
578 |
+
nx.set_edge_attributes(G, vals, attr)
|
579 |
+
assert G[0][1][0][attr] == vals
|
580 |
+
assert G[1][2][0][attr] == vals
|
581 |
+
|
582 |
+
# Test multiple values
|
583 |
+
G = nx.path_graph(3, create_using=graph_type)
|
584 |
+
attr = "hi"
|
585 |
+
edges = [(0, 1, 0), (1, 2, 0)]
|
586 |
+
vals = dict(zip(edges, range(len(edges))))
|
587 |
+
nx.set_edge_attributes(G, vals, attr)
|
588 |
+
assert G[0][1][0][attr] == 0
|
589 |
+
assert G[1][2][0][attr] == 1
|
590 |
+
|
591 |
+
# Test dictionary of dictionaries
|
592 |
+
G = nx.path_graph(3, create_using=graph_type)
|
593 |
+
d = {"hi": 0, "hello": 200}
|
594 |
+
edges = [(0, 1, 0)]
|
595 |
+
vals = dict.fromkeys(edges, d)
|
596 |
+
nx.set_edge_attributes(G, vals)
|
597 |
+
assert G[0][1][0]["hi"] == 0
|
598 |
+
assert G[0][1][0]["hello"] == 200
|
599 |
+
assert G[1][2][0] == {}
|
600 |
+
|
601 |
+
|
602 |
+
@pytest.mark.parametrize(
|
603 |
+
("values", "name"),
|
604 |
+
(
|
605 |
+
({(0, 1, 0): 1.0, (0, 2, 0): 2.0}, "weight"), # values dict
|
606 |
+
({(0, 1, 0): {"weight": 1.0}, (0, 2, 0): {"weight": 2.0}}, None), # values dod
|
607 |
+
),
|
608 |
+
)
|
609 |
+
def test_set_edge_attributes_multi_ignores_extra_edges(values, name):
|
610 |
+
"""If `values` is a dict or dict-of-dicts containing edges that are not in
|
611 |
+
G, data associate with these edges should be ignored.
|
612 |
+
"""
|
613 |
+
G = nx.MultiGraph([(0, 1, 0), (0, 1, 1)])
|
614 |
+
nx.set_edge_attributes(G, values, name)
|
615 |
+
assert G[0][1][0]["weight"] == 1.0
|
616 |
+
assert G[0][1][1] == {}
|
617 |
+
assert (0, 2) not in G.edges()
|
618 |
+
|
619 |
+
|
620 |
+
def test_get_node_attributes():
|
621 |
+
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
|
622 |
+
for G in graphs:
|
623 |
+
G = nx.path_graph(3, create_using=G)
|
624 |
+
attr = "hello"
|
625 |
+
vals = 100
|
626 |
+
nx.set_node_attributes(G, vals, attr)
|
627 |
+
attrs = nx.get_node_attributes(G, attr)
|
628 |
+
assert attrs[0] == vals
|
629 |
+
assert attrs[1] == vals
|
630 |
+
assert attrs[2] == vals
|
631 |
+
default_val = 1
|
632 |
+
G.add_node(4)
|
633 |
+
attrs = nx.get_node_attributes(G, attr, default=default_val)
|
634 |
+
assert attrs[4] == default_val
|
635 |
+
|
636 |
+
|
637 |
+
def test_get_edge_attributes():
|
638 |
+
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
|
639 |
+
for G in graphs:
|
640 |
+
G = nx.path_graph(3, create_using=G)
|
641 |
+
attr = "hello"
|
642 |
+
vals = 100
|
643 |
+
nx.set_edge_attributes(G, vals, attr)
|
644 |
+
attrs = nx.get_edge_attributes(G, attr)
|
645 |
+
assert len(attrs) == 2
|
646 |
+
|
647 |
+
for edge in G.edges:
|
648 |
+
assert attrs[edge] == vals
|
649 |
+
|
650 |
+
default_val = vals
|
651 |
+
G.add_edge(4, 5)
|
652 |
+
deafult_attrs = nx.get_edge_attributes(G, attr, default=default_val)
|
653 |
+
assert len(deafult_attrs) == 3
|
654 |
+
|
655 |
+
for edge in G.edges:
|
656 |
+
assert deafult_attrs[edge] == vals
|
657 |
+
|
658 |
+
|
659 |
+
def test_is_empty():
|
660 |
+
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
|
661 |
+
for G in graphs:
|
662 |
+
assert nx.is_empty(G)
|
663 |
+
G.add_nodes_from(range(5))
|
664 |
+
assert nx.is_empty(G)
|
665 |
+
G.add_edges_from([(1, 2), (3, 4)])
|
666 |
+
assert not nx.is_empty(G)
|
667 |
+
|
668 |
+
|
669 |
+
@pytest.mark.parametrize(
|
670 |
+
"graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
|
671 |
+
)
|
672 |
+
def test_selfloops(graph_type):
|
673 |
+
G = nx.complete_graph(3, create_using=graph_type)
|
674 |
+
G.add_edge(0, 0)
|
675 |
+
assert nodes_equal(nx.nodes_with_selfloops(G), [0])
|
676 |
+
assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
|
677 |
+
assert edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {})])
|
678 |
+
assert nx.number_of_selfloops(G) == 1
|
679 |
+
|
680 |
+
|
681 |
+
@pytest.mark.parametrize(
|
682 |
+
"graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
|
683 |
+
)
|
684 |
+
def test_selfloop_edges_attr(graph_type):
|
685 |
+
G = nx.complete_graph(3, create_using=graph_type)
|
686 |
+
G.add_edge(0, 0)
|
687 |
+
G.add_edge(1, 1, weight=2)
|
688 |
+
assert edges_equal(
|
689 |
+
nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
|
690 |
+
)
|
691 |
+
assert edges_equal(nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)])
|
692 |
+
|
693 |
+
|
694 |
+
def test_selfloop_edges_multi_with_data_and_keys():
|
695 |
+
G = nx.complete_graph(3, create_using=nx.MultiGraph)
|
696 |
+
G.add_edge(0, 0, weight=10)
|
697 |
+
G.add_edge(0, 0, weight=100)
|
698 |
+
assert edges_equal(
|
699 |
+
nx.selfloop_edges(G, data="weight", keys=True), [(0, 0, 0, 10), (0, 0, 1, 100)]
|
700 |
+
)
|
701 |
+
|
702 |
+
|
703 |
+
@pytest.mark.parametrize("graph_type", [nx.Graph, nx.DiGraph])
|
704 |
+
def test_selfloops_removal(graph_type):
|
705 |
+
G = nx.complete_graph(3, create_using=graph_type)
|
706 |
+
G.add_edge(0, 0)
|
707 |
+
G.remove_edges_from(nx.selfloop_edges(G, keys=True))
|
708 |
+
G.add_edge(0, 0)
|
709 |
+
G.remove_edges_from(nx.selfloop_edges(G, data=True))
|
710 |
+
G.add_edge(0, 0)
|
711 |
+
G.remove_edges_from(nx.selfloop_edges(G, keys=True, data=True))
|
712 |
+
|
713 |
+
|
714 |
+
@pytest.mark.parametrize("graph_type", [nx.MultiGraph, nx.MultiDiGraph])
|
715 |
+
def test_selfloops_removal_multi(graph_type):
|
716 |
+
"""test removing selfloops behavior vis-a-vis altering a dict while iterating.
|
717 |
+
cf. gh-4068"""
|
718 |
+
G = nx.complete_graph(3, create_using=graph_type)
|
719 |
+
# Defaults - see gh-4080
|
720 |
+
G.add_edge(0, 0)
|
721 |
+
G.add_edge(0, 0)
|
722 |
+
G.remove_edges_from(nx.selfloop_edges(G))
|
723 |
+
assert (0, 0) not in G.edges()
|
724 |
+
# With keys
|
725 |
+
G.add_edge(0, 0)
|
726 |
+
G.add_edge(0, 0)
|
727 |
+
with pytest.raises(RuntimeError):
|
728 |
+
G.remove_edges_from(nx.selfloop_edges(G, keys=True))
|
729 |
+
# With data
|
730 |
+
G.add_edge(0, 0)
|
731 |
+
G.add_edge(0, 0)
|
732 |
+
with pytest.raises(TypeError):
|
733 |
+
G.remove_edges_from(nx.selfloop_edges(G, data=True))
|
734 |
+
# With keys and data
|
735 |
+
G.add_edge(0, 0)
|
736 |
+
G.add_edge(0, 0)
|
737 |
+
with pytest.raises(RuntimeError):
|
738 |
+
G.remove_edges_from(nx.selfloop_edges(G, data=True, keys=True))
|
739 |
+
|
740 |
+
|
741 |
+
def test_pathweight():
|
742 |
+
valid_path = [1, 2, 3]
|
743 |
+
invalid_path = [1, 3, 2]
|
744 |
+
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
|
745 |
+
edges = [
|
746 |
+
(1, 2, {"cost": 5, "dist": 6}),
|
747 |
+
(2, 3, {"cost": 3, "dist": 4}),
|
748 |
+
(1, 2, {"cost": 1, "dist": 2}),
|
749 |
+
]
|
750 |
+
for graph in graphs:
|
751 |
+
graph.add_edges_from(edges)
|
752 |
+
assert nx.path_weight(graph, valid_path, "cost") == 4
|
753 |
+
assert nx.path_weight(graph, valid_path, "dist") == 6
|
754 |
+
pytest.raises(nx.NetworkXNoPath, nx.path_weight, graph, invalid_path, "cost")
|
755 |
+
|
756 |
+
|
757 |
+
@pytest.mark.parametrize(
|
758 |
+
"G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
|
759 |
+
)
|
760 |
+
def test_ispath(G):
|
761 |
+
G.add_edges_from([(1, 2), (2, 3), (1, 2), (3, 4)])
|
762 |
+
valid_path = [1, 2, 3, 4]
|
763 |
+
invalid_path = [1, 2, 4, 3] # wrong node order
|
764 |
+
another_invalid_path = [1, 2, 3, 4, 5] # contains node not in G
|
765 |
+
assert nx.is_path(G, valid_path)
|
766 |
+
assert not nx.is_path(G, invalid_path)
|
767 |
+
assert not nx.is_path(G, another_invalid_path)
|
768 |
+
|
769 |
+
|
770 |
+
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
|
771 |
+
def test_restricted_view(G):
|
772 |
+
G.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2)])
|
773 |
+
G.add_node(4)
|
774 |
+
H = nx.restricted_view(G, [0, 2, 5], [(1, 2), (3, 4)])
|
775 |
+
assert set(H.nodes()) == {1, 3, 4}
|
776 |
+
assert set(H.edges()) == {(1, 1)}
|
777 |
+
|
778 |
+
|
779 |
+
@pytest.mark.parametrize("G", (nx.MultiGraph(), nx.MultiDiGraph()))
|
780 |
+
def test_restricted_view_multi(G):
|
781 |
+
G.add_edges_from(
|
782 |
+
[(0, 1, 0), (0, 2, 0), (0, 3, 0), (0, 1, 1), (1, 0, 0), (1, 1, 0), (1, 2, 0)]
|
783 |
+
)
|
784 |
+
G.add_node(4)
|
785 |
+
H = nx.restricted_view(G, [0, 2, 5], [(1, 2, 0), (3, 4, 0)])
|
786 |
+
assert set(H.nodes()) == {1, 3, 4}
|
787 |
+
assert set(H.edges()) == {(1, 1)}
|