content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
from datetime import datetime\n\ndef parse(timestamp: str, utc: bool = ..., produce_naive: bool = ...) -> datetime: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\pyrfc3339\parser.pyi | parser.pyi | Other | 118 | 0.85 | 0.333333 | 0 | awesome-app | 342 | 2023-10-29T22:29:51.817549 | BSD-3-Clause | false | 77d1951648663db980412c466d14ef1d |
from datetime import datetime, timedelta, tzinfo\nfrom typing import Optional\n\nclass FixedOffset(tzinfo):\n def __init__(self, hours: float, minutes: float) -> None: ...\n def dst(self, dt: Optional[datetime]) -> timedelta: ...\n def utcoffset(self, dt: Optional[datetime]) -> timedelta: ...\n def tzname(self, dt: Optional[datetime]) -> str: ...\n\ndef timedelta_seconds(td: timedelta) -> int: ...\ndef timezone(utcoffset: float) -> str: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\pyrfc3339\utils.pyi | utils.pyi | Other | 447 | 0.85 | 0.636364 | 0 | react-lib | 716 | 2024-03-03T20:05:02.498763 | GPL-3.0 | false | 8c32200ca6ff3b21934c0c72825eb1b5 |
from .generator import generate as generate\nfrom .parser import parse as parse\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\pyrfc3339\__init__.pyi | __init__.pyi | Other | 79 | 0.65 | 0 | 0 | node-utils | 276 | 2025-06-11T22:50:07.083642 | Apache-2.0 | false | 483953c7c7e2428cd4f0f5fd68dab588 |
from __future__ import print_function\n\nimport types\nimport typing\nimport unittest\nfrom builtins import next as next\nfrom functools import wraps as wraps\nfrom io import BytesIO as BytesIO, StringIO as StringIO\nfrom typing import (\n Any,\n AnyStr,\n Callable,\n Dict,\n ItemsView,\n Iterable,\n KeysView,\n Mapping,\n NoReturn,\n Optional,\n Pattern,\n Tuple,\n Type,\n TypeVar,\n Union,\n ValuesView,\n overload,\n)\n\nfrom . import moves as moves\n\n_T = TypeVar("_T")\n_K = TypeVar("_K")\n_V = TypeVar("_V")\n\n__version__: str\n\n# TODO make constant, then move this stub to 2and3\n# https://github.com/python/typeshed/issues/17\nPY2 = False\nPY3 = True\nPY34: bool\n\nstring_types = (str,)\ninteger_types = (int,)\nclass_types = (type,)\ntext_type = str\nbinary_type = bytes\n\nMAXSIZE: int\n\ndef callable(obj: object) -> bool: ...\ndef get_unbound_function(unbound: types.FunctionType) -> types.FunctionType: ...\ndef create_bound_method(func: types.FunctionType, obj: object) -> types.MethodType: ...\ndef create_unbound_method(func: types.FunctionType, cls: type) -> types.FunctionType: ...\n\nIterator = object\n\ndef get_method_function(meth: types.MethodType) -> types.FunctionType: ...\ndef get_method_self(meth: types.MethodType) -> Optional[object]: ...\ndef get_function_closure(fun: types.FunctionType) -> Optional[Tuple[types._Cell, ...]]: ...\ndef get_function_code(fun: types.FunctionType) -> types.CodeType: ...\ndef get_function_defaults(fun: types.FunctionType) -> Optional[Tuple[Any, ...]]: ...\ndef get_function_globals(fun: types.FunctionType) -> Dict[str, Any]: ...\ndef iterkeys(d: Mapping[_K, _V]) -> typing.Iterator[_K]: ...\ndef itervalues(d: Mapping[_K, _V]) -> typing.Iterator[_V]: ...\ndef iteritems(d: Mapping[_K, _V]) -> typing.Iterator[Tuple[_K, _V]]: ...\n\n# def iterlists\n\ndef viewkeys(d: Mapping[_K, _V]) -> KeysView[_K]: ...\ndef viewvalues(d: Mapping[_K, _V]) -> ValuesView[_V]: ...\ndef viewitems(d: Mapping[_K, _V]) -> ItemsView[_K, _V]: ...\ndef b(s: str) -> binary_type: ...\ndef u(s: str) -> text_type: ...\n\nunichr = chr\n\ndef int2byte(i: int) -> bytes: ...\ndef byte2int(bs: binary_type) -> int: ...\ndef indexbytes(buf: binary_type, i: int) -> int: ...\ndef iterbytes(buf: binary_type) -> typing.Iterator[int]: ...\ndef assertCountEqual(self: unittest.TestCase, first: Iterable[_T], second: Iterable[_T], msg: Optional[str] = ...) -> None: ...\n@overload\ndef assertRaisesRegex(self: unittest.TestCase, msg: Optional[str] = ...) -> Any: ...\n@overload\ndef assertRaisesRegex(self: unittest.TestCase, callable_obj: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: ...\ndef assertRegex(\n self: unittest.TestCase, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], msg: Optional[str] = ...\n) -> None: ...\n\nexec_ = exec\n\ndef reraise(\n tp: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[types.TracebackType] = ...\n) -> NoReturn: ...\ndef raise_from(value: Union[BaseException, Type[BaseException]], from_value: Optional[BaseException]) -> NoReturn: ...\n\nprint_ = print\n\ndef with_metaclass(meta: type, *bases: type) -> type: ...\ndef add_metaclass(metaclass: type) -> Callable[[_T], _T]: ...\ndef ensure_binary(s: Union[bytes, str], encoding: str = ..., errors: str = ...) -> bytes: ...\ndef ensure_str(s: Union[bytes, str], encoding: str = ..., errors: str = ...) -> str: ...\ndef ensure_text(s: Union[bytes, str], encoding: str = ..., errors: str = ...) -> str: ...\ndef python_2_unicode_compatible(klass: _T) -> _T: ...\n\nclass _LazyDescriptor:\n name: str\n def __init__(self, name: str) -> None: ...\n def __get__(self, obj: Optional[object], type: Optional[type] = ...) -> Any: ...\n\nclass MovedModule(_LazyDescriptor):\n mod: str\n def __init__(self, name: str, old: str, new: Optional[str] = ...) -> None: ...\n def __getattr__(self, attr: str) -> Any: ...\n\nclass MovedAttribute(_LazyDescriptor):\n mod: str\n attr: str\n def __init__(\n self, name: str, old_mod: str, new_mod: str, old_attr: Optional[str] = ..., new_attr: Optional[str] = ...\n ) -> None: ...\n\ndef add_move(move: Union[MovedModule, MovedAttribute]) -> None: ...\ndef remove_move(name: str) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\__init__.pyi | __init__.pyi | Other | 4,169 | 0.95 | 0.36 | 0.029126 | python-kit | 533 | 2023-12-14T02:08:54.373532 | BSD-3-Clause | false | 2ab19af6dc5271e4d06175d810eba9b0 |
from http.server import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\BaseHTTPServer.pyi | BaseHTTPServer.pyi | Other | 26 | 0.65 | 0 | 0 | react-lib | 574 | 2024-06-17T16:23:29.651083 | MIT | false | 59c113ba8da07ed8b8cf1d9fa0cb0a08 |
from builtins import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\builtins.pyi | builtins.pyi | Other | 23 | 0.65 | 0 | 0 | python-kit | 986 | 2024-04-12T19:14:08.637685 | BSD-3-Clause | false | d7562647d6b71842a4288a4d128e71a4 |
from http.server import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\CGIHTTPServer.pyi | CGIHTTPServer.pyi | Other | 26 | 0.65 | 0 | 0 | node-utils | 452 | 2023-09-21T15:09:28.166355 | BSD-3-Clause | false | 59c113ba8da07ed8b8cf1d9fa0cb0a08 |
from collections.abc import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\collections_abc.pyi | collections_abc.pyi | Other | 30 | 0.65 | 0 | 0 | vue-tools | 524 | 2024-02-04T07:14:56.394188 | MIT | false | 52c1e5277b42ad352d96a1bd5401f7bc |
from configparser import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\configparser.pyi | configparser.pyi | Other | 27 | 0.65 | 0 | 0 | awesome-app | 993 | 2025-06-29T14:53:28.881973 | GPL-3.0 | false | 96f1d00a95381dcfd60ad2aa745d0310 |
from pickle import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\cPickle.pyi | cPickle.pyi | Other | 21 | 0.65 | 0 | 0 | python-kit | 51 | 2024-06-09T00:24:02.377848 | MIT | false | fa259fc7f029620666c8b3d08d025a7f |
from email.mime.base import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\email_mime_base.pyi | email_mime_base.pyi | Other | 30 | 0.65 | 0 | 0 | node-utils | 410 | 2024-03-07T13:27:11.455094 | BSD-3-Clause | false | ff4bcee3cf8667ab29fba8f01d4849e2 |
from email.mime.multipart import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\email_mime_multipart.pyi | email_mime_multipart.pyi | Other | 35 | 0.65 | 0 | 0 | vue-tools | 338 | 2023-11-16T20:48:53.750576 | BSD-3-Clause | false | f117994bd56265ad287f2057dba3800e |
from email.mime.nonmultipart import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\email_mime_nonmultipart.pyi | email_mime_nonmultipart.pyi | Other | 38 | 0.65 | 0 | 0 | awesome-app | 985 | 2024-05-11T19:40:24.834745 | BSD-3-Clause | false | 2f0f0cf7b13e1cb958547790f2565320 |
from email.mime.text import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\email_mime_text.pyi | email_mime_text.pyi | Other | 30 | 0.65 | 0 | 0 | vue-tools | 1 | 2024-04-30T19:22:41.560794 | Apache-2.0 | false | 7d8e766c47b809611a1a25b5b0f7855e |
from html.entities import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\html_entities.pyi | html_entities.pyi | Other | 28 | 0.65 | 0 | 0 | python-kit | 581 | 2024-04-19T15:16:06.818527 | BSD-3-Clause | false | 86724120bd16a713e132aee6f98f18a5 |
from html.parser import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\html_parser.pyi | html_parser.pyi | Other | 26 | 0.65 | 0 | 0 | vue-tools | 183 | 2025-03-11T11:48:10.175388 | BSD-3-Clause | false | 3f03d9d7ed87deaddea2111e9d57ce57 |
from http.client import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\http_client.pyi | http_client.pyi | Other | 26 | 0.65 | 0 | 0 | awesome-app | 266 | 2023-08-02T11:16:08.604673 | Apache-2.0 | false | 97192f2735439f6dc9002060c6f75785 |
from http.cookiejar import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\http_cookiejar.pyi | http_cookiejar.pyi | Other | 29 | 0.65 | 0 | 0 | node-utils | 892 | 2024-06-04T15:31:42.116420 | GPL-3.0 | false | 6e7e18b4d9379e73005f17bc9a0a4944 |
from http.cookies import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\http_cookies.pyi | http_cookies.pyi | Other | 27 | 0.65 | 0 | 0 | python-kit | 784 | 2023-11-23T17:32:04.993337 | BSD-3-Clause | false | dac6ebb3b2573cf231b1ef6de893f4f1 |
from queue import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\queue.pyi | queue.pyi | Other | 20 | 0.65 | 0 | 0 | vue-tools | 204 | 2023-11-14T10:22:35.690395 | MIT | false | 214a90326750594806c01a7cd1eae6a7 |
from reprlib import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\reprlib.pyi | reprlib.pyi | Other | 22 | 0.65 | 0 | 0 | vue-tools | 189 | 2025-07-04T00:23:55.651319 | MIT | false | b5b71c62433c7f2b9e1d676dd0db0230 |
from http.server import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\SimpleHTTPServer.pyi | SimpleHTTPServer.pyi | Other | 26 | 0.65 | 0 | 0 | vue-tools | 282 | 2023-10-16T14:11:14.992780 | MIT | false | 59c113ba8da07ed8b8cf1d9fa0cb0a08 |
from socketserver import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\socketserver.pyi | socketserver.pyi | Other | 27 | 0.65 | 0 | 0 | awesome-app | 261 | 2024-12-30T03:05:31.864035 | BSD-3-Clause | false | 7bc0baff87df93ff705252601462042a |
from tkinter import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter.pyi | tkinter.pyi | Other | 22 | 0.65 | 0 | 0 | vue-tools | 212 | 2023-12-17T00:18:15.066195 | MIT | false | baaac9c43c842bd7ae04c6960eb73619 |
from tkinter.commondialog import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter_commondialog.pyi | tkinter_commondialog.pyi | Other | 35 | 0.65 | 0 | 0 | python-kit | 50 | 2024-04-24T07:05:13.755863 | GPL-3.0 | false | cb565c09a73f00d54159b7a6ce372c19 |
from tkinter.constants import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter_constants.pyi | tkinter_constants.pyi | Other | 32 | 0.65 | 0 | 0 | node-utils | 704 | 2024-02-20T16:23:06.444630 | BSD-3-Clause | false | e5da015ca93d80f76fac834caa92aaa2 |
from tkinter.dialog import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter_dialog.pyi | tkinter_dialog.pyi | Other | 29 | 0.65 | 0 | 0 | python-kit | 566 | 2025-04-21T09:03:43.625908 | Apache-2.0 | false | 5e63a2eace38e60a62d9fda6ac0d6d92 |
from tkinter.filedialog import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter_filedialog.pyi | tkinter_filedialog.pyi | Other | 33 | 0.65 | 0 | 0 | python-kit | 442 | 2024-05-09T11:33:45.006478 | GPL-3.0 | false | f8d574ac9b02c149019de779c681cfa4 |
from tkinter.filedialog import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter_tkfiledialog.pyi | tkinter_tkfiledialog.pyi | Other | 33 | 0.65 | 0 | 0 | node-utils | 706 | 2025-02-05T08:04:08.116173 | GPL-3.0 | false | f8d574ac9b02c149019de779c681cfa4 |
from tkinter.ttk import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\tkinter_ttk.pyi | tkinter_ttk.pyi | Other | 26 | 0.65 | 0 | 0 | awesome-app | 329 | 2024-07-21T07:30:24.056668 | MIT | false | ecac18f17295ffda92d3a5c3372ef0cd |
from urllib.error import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib_error.pyi | urllib_error.pyi | Other | 27 | 0.65 | 0 | 0 | awesome-app | 838 | 2024-03-02T02:47:17.590133 | MIT | false | 3b22755466cb7b3808271a04cbd6eb2b |
from urllib.parse import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib_parse.pyi | urllib_parse.pyi | Other | 27 | 0.65 | 0 | 0 | python-kit | 959 | 2023-11-06T11:00:17.241904 | Apache-2.0 | false | b6559b7c1865cc5d68074152f93a7928 |
from .urllib.request import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib_request.pyi | urllib_request.pyi | Other | 30 | 0.65 | 0 | 0 | node-utils | 955 | 2023-12-24T19:18:11.469548 | Apache-2.0 | false | 6cab3b7235e3533561f8a62233222aa2 |
from .urllib.response import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib_response.pyi | urllib_response.pyi | Other | 31 | 0.65 | 0 | 0 | awesome-app | 300 | 2024-01-03T03:33:43.953342 | BSD-3-Clause | false | 2cdece13bcc1f06cc37015a2bc994768 |
from urllib.robotparser import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib_robotparser.pyi | urllib_robotparser.pyi | Other | 33 | 0.65 | 0 | 0 | react-lib | 360 | 2024-07-16T16:02:51.220541 | BSD-3-Clause | false | eec1c2c31eaf29e9e993aa9c233c8341 |
from _dummy_thread import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\_dummy_thread.pyi | _dummy_thread.pyi | Other | 28 | 0.65 | 0 | 0 | vue-tools | 413 | 2024-04-13T08:51:51.741932 | MIT | false | 3e1afd672458ee6879b8a01798c0f655 |
from _thread import *\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\_thread.pyi | _thread.pyi | Other | 22 | 0.65 | 0 | 0 | awesome-app | 332 | 2023-12-15T15:56:06.841954 | MIT | false | 264bddb3174e841f3290f783e4529e03 |
# Stubs for six.moves\n#\n# Note: Commented out items means they weren't implemented at the time.\n# Uncomment them when the modules have been added to the typeshed.\nimport importlib\nimport shlex\nfrom builtins import filter as filter, input as input, map as map, range as range, zip as zip\nfrom collections import UserDict as UserDict, UserList as UserList, UserString as UserString\nfrom functools import reduce as reduce\nfrom io import StringIO as StringIO\nfrom itertools import filterfalse as filterfalse, zip_longest as zip_longest\nfrom os import getcwd as getcwd, getcwdb as getcwdb\nfrom sys import intern as intern\n\n# import tkinter.font as tkinter_font\n# import tkinter.messagebox as tkinter_messagebox\n# import tkinter.simpledialog as tkinter_tksimpledialog\n# import tkinter.dnd as tkinter_dnd\n# import tkinter.colorchooser as tkinter_colorchooser\n# import tkinter.scrolledtext as tkinter_scrolledtext\n# import tkinter.simpledialog as tkinter_simpledialog\n# import tkinter.tix as tkinter_tix\n# import copyreg as copyreg\n# import dbm.gnu as dbm_gnu\nfrom . import (\n BaseHTTPServer as BaseHTTPServer,\n CGIHTTPServer as CGIHTTPServer,\n SimpleHTTPServer as SimpleHTTPServer,\n _dummy_thread as _dummy_thread,\n _thread as _thread,\n builtins as builtins,\n configparser as configparser,\n cPickle as cPickle,\n email_mime_base as email_mime_base,\n email_mime_multipart as email_mime_multipart,\n email_mime_nonmultipart as email_mime_nonmultipart,\n email_mime_text as email_mime_text,\n html_entities as html_entities,\n html_parser as html_parser,\n http_client as http_client,\n http_cookiejar as http_cookiejar,\n http_cookies as http_cookies,\n queue as queue,\n reprlib as reprlib,\n socketserver as socketserver,\n tkinter as tkinter,\n tkinter_commondialog as tkinter_commondialog,\n tkinter_constants as tkinter_constants,\n tkinter_dialog as tkinter_dialog,\n tkinter_filedialog as tkinter_filedialog,\n tkinter_tkfiledialog as tkinter_tkfiledialog,\n tkinter_ttk as tkinter_ttk,\n urllib as urllib,\n urllib_error as urllib_error,\n urllib_parse as urllib_parse,\n urllib_robotparser as urllib_robotparser,\n)\n\n# import xmlrpc.client as xmlrpc_client\n# import xmlrpc.server as xmlrpc_server\n\nxrange = range\nreload_module = importlib.reload\ncStringIO = StringIO\nshlex_quote = shlex.quote\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\__init__.pyi | __init__.pyi | Other | 2,363 | 0.95 | 0.015385 | 0.258065 | awesome-app | 273 | 2025-02-10T22:56:46.280472 | BSD-3-Clause | false | 09c4590c729d7a5a3903e696c3537330 |
from urllib.error import ContentTooShortError as ContentTooShortError, HTTPError as HTTPError, URLError as URLError\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib\error.pyi | error.pyi | Other | 116 | 0.85 | 0 | 0 | python-kit | 92 | 2023-09-09T03:32:51.197182 | MIT | false | 18bf6b3d9de0b9f9670d9b6c07b55b79 |
# Stubs for six.moves.urllib.parse\n#\n# Note: Commented out items means they weren't implemented at the time.\n# Uncomment them when the modules have been added to the typeshed.\n# from urllib.parse import splitquery as splitquery\n# from urllib.parse import splittag as splittag\n# from urllib.parse import splituser as splituser\nfrom urllib.parse import (\n ParseResult as ParseResult,\n SplitResult as SplitResult,\n parse_qs as parse_qs,\n parse_qsl as parse_qsl,\n quote as quote,\n quote_plus as quote_plus,\n unquote as unquote,\n unquote_plus as unquote_plus,\n unquote_to_bytes as unquote_to_bytes,\n urldefrag as urldefrag,\n urlencode as urlencode,\n urljoin as urljoin,\n urlparse as urlparse,\n urlsplit as urlsplit,\n urlunparse as urlunparse,\n urlunsplit as urlunsplit,\n uses_fragment as uses_fragment,\n uses_netloc as uses_netloc,\n uses_params as uses_params,\n uses_query as uses_query,\n uses_relative as uses_relative,\n)\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib\parse.pyi | parse.pyi | Other | 981 | 0.95 | 0.033333 | 0.233333 | react-lib | 726 | 2023-09-16T12:01:12.254237 | GPL-3.0 | false | 3009984178e2f09b91aa70d538ff8fc9 |
# Stubs for six.moves.urllib.request\n#\n# Note: Commented out items means they weren't implemented at the time.\n# Uncomment them when the modules have been added to the typeshed.\n# from urllib.request import proxy_bypass as proxy_bypass\nfrom urllib.request import (\n AbstractBasicAuthHandler as AbstractBasicAuthHandler,\n AbstractDigestAuthHandler as AbstractDigestAuthHandler,\n BaseHandler as BaseHandler,\n CacheFTPHandler as CacheFTPHandler,\n FancyURLopener as FancyURLopener,\n FileHandler as FileHandler,\n FTPHandler as FTPHandler,\n HTTPBasicAuthHandler as HTTPBasicAuthHandler,\n HTTPCookieProcessor as HTTPCookieProcessor,\n HTTPDefaultErrorHandler as HTTPDefaultErrorHandler,\n HTTPDigestAuthHandler as HTTPDigestAuthHandler,\n HTTPErrorProcessor as HTTPErrorProcessor,\n HTTPHandler as HTTPHandler,\n HTTPPasswordMgr as HTTPPasswordMgr,\n HTTPPasswordMgrWithDefaultRealm as HTTPPasswordMgrWithDefaultRealm,\n HTTPRedirectHandler as HTTPRedirectHandler,\n HTTPSHandler as HTTPSHandler,\n OpenerDirector as OpenerDirector,\n ProxyBasicAuthHandler as ProxyBasicAuthHandler,\n ProxyDigestAuthHandler as ProxyDigestAuthHandler,\n ProxyHandler as ProxyHandler,\n Request as Request,\n UnknownHandler as UnknownHandler,\n URLopener as URLopener,\n build_opener as build_opener,\n getproxies as getproxies,\n install_opener as install_opener,\n parse_http_list as parse_http_list,\n parse_keqv_list as parse_keqv_list,\n pathname2url as pathname2url,\n url2pathname as url2pathname,\n urlcleanup as urlcleanup,\n urlopen as urlopen,\n urlretrieve as urlretrieve,\n)\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib\request.pyi | request.pyi | Other | 1,639 | 0.95 | 0.02439 | 0.121951 | awesome-app | 33 | 2024-06-18T15:55:33.536067 | MIT | false | 149c8fc6ee5dc1d9f56d69823508f45a |
# Stubs for six.moves.urllib.response\n#\n# Note: Commented out items means they weren't implemented at the time.\n# Uncomment them when the modules have been added to the typeshed.\n# from urllib.response import addbase as addbase\n# from urllib.response import addclosehook as addclosehook\n# from urllib.response import addinfo as addinfo\nfrom urllib.response import addinfourl as addinfourl\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib\response.pyi | response.pyi | Other | 389 | 0.95 | 0.125 | 0.875 | awesome-app | 85 | 2024-09-26T05:19:59.704770 | MIT | false | 1a6452adbee5df1e4737499bd1da903f |
from urllib.robotparser import RobotFileParser as RobotFileParser\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib\robotparser.pyi | robotparser.pyi | Other | 66 | 0.65 | 0 | 0 | awesome-app | 543 | 2024-02-17T03:30:49.842434 | BSD-3-Clause | false | 30f8ef6f9ae42c1573ae6e8ea7e13367 |
import six.moves.urllib.error as error\nimport six.moves.urllib.parse as parse\nimport six.moves.urllib.request as request\nimport six.moves.urllib.response as response\nimport six.moves.urllib.robotparser as robotparser\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\six\moves\urllib\__init__.pyi | __init__.pyi | Other | 217 | 0.85 | 0 | 0 | vue-tools | 814 | 2025-02-28T20:44:08.224879 | BSD-3-Clause | false | f3ae2c07dd91df9d44c138f71bd45f37 |
import typing\nfrom typing import Any, Iterator, Optional, Union\n\nclass NodeVisitor:\n def visit(self, node: AST) -> Any: ...\n def generic_visit(self, node: AST) -> None: ...\n\nclass NodeTransformer(NodeVisitor):\n def generic_visit(self, node: AST) -> None: ...\n\ndef parse(source: Union[str, bytes], filename: Union[str, bytes] = ..., mode: str = ...) -> AST: ...\ndef copy_location(new_node: AST, old_node: AST) -> AST: ...\ndef dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ...\ndef fix_missing_locations(node: AST) -> AST: ...\ndef get_docstring(node: AST, clean: bool = ...) -> Optional[bytes]: ...\ndef increment_lineno(node: AST, n: int = ...) -> AST: ...\ndef iter_child_nodes(node: AST) -> Iterator[AST]: ...\ndef iter_fields(node: AST) -> Iterator[typing.Tuple[str, Any]]: ...\ndef literal_eval(node_or_string: Union[str, AST]) -> Any: ...\ndef walk(node: AST) -> Iterator[AST]: ...\n\nPyCF_ONLY_AST: int\n\n# ast classes\n\nidentifier = str\n\nclass AST:\n _attributes: typing.Tuple[str, ...]\n _fields: typing.Tuple[str, ...]\n def __init__(self, *args: Any, **kwargs: Any) -> None: ...\n\nclass mod(AST): ...\n\nclass Module(mod):\n body: typing.List[stmt]\n type_ignores: typing.List[TypeIgnore]\n\nclass Interactive(mod):\n body: typing.List[stmt]\n\nclass Expression(mod):\n body: expr\n\nclass FunctionType(mod):\n argtypes: typing.List[expr]\n returns: expr\n\nclass Suite(mod):\n body: typing.List[stmt]\n\nclass stmt(AST):\n lineno: int\n col_offset: int\n\nclass FunctionDef(stmt):\n name: identifier\n args: arguments\n body: typing.List[stmt]\n decorator_list: typing.List[expr]\n type_comment: Optional[str]\n\nclass ClassDef(stmt):\n name: identifier\n bases: typing.List[expr]\n body: typing.List[stmt]\n decorator_list: typing.List[expr]\n\nclass Return(stmt):\n value: Optional[expr]\n\nclass Delete(stmt):\n targets: typing.List[expr]\n\nclass Assign(stmt):\n targets: typing.List[expr]\n value: expr\n type_comment: Optional[str]\n\nclass AugAssign(stmt):\n target: expr\n op: operator\n value: expr\n\nclass Print(stmt):\n dest: Optional[expr]\n values: typing.List[expr]\n nl: bool\n\nclass For(stmt):\n target: expr\n iter: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n type_comment: Optional[str]\n\nclass While(stmt):\n test: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n\nclass If(stmt):\n test: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n\nclass With(stmt):\n context_expr: expr\n optional_vars: Optional[expr]\n body: typing.List[stmt]\n type_comment: Optional[str]\n\nclass Raise(stmt):\n type: Optional[expr]\n inst: Optional[expr]\n tback: Optional[expr]\n\nclass TryExcept(stmt):\n body: typing.List[stmt]\n handlers: typing.List[ExceptHandler]\n orelse: typing.List[stmt]\n\nclass TryFinally(stmt):\n body: typing.List[stmt]\n finalbody: typing.List[stmt]\n\nclass Assert(stmt):\n test: expr\n msg: Optional[expr]\n\nclass Import(stmt):\n names: typing.List[alias]\n\nclass ImportFrom(stmt):\n module: Optional[identifier]\n names: typing.List[alias]\n level: Optional[int]\n\nclass Exec(stmt):\n body: expr\n globals: Optional[expr]\n locals: Optional[expr]\n\nclass Global(stmt):\n names: typing.List[identifier]\n\nclass Expr(stmt):\n value: expr\n\nclass Pass(stmt): ...\nclass Break(stmt): ...\nclass Continue(stmt): ...\nclass slice(AST): ...\n\n_slice = slice # this lets us type the variable named 'slice' below\n\nclass Slice(slice):\n lower: Optional[expr]\n upper: Optional[expr]\n step: Optional[expr]\n\nclass ExtSlice(slice):\n dims: typing.List[slice]\n\nclass Index(slice):\n value: expr\n\nclass Ellipsis(slice): ...\n\nclass expr(AST):\n lineno: int\n col_offset: int\n\nclass BoolOp(expr):\n op: boolop\n values: typing.List[expr]\n\nclass BinOp(expr):\n left: expr\n op: operator\n right: expr\n\nclass UnaryOp(expr):\n op: unaryop\n operand: expr\n\nclass Lambda(expr):\n args: arguments\n body: expr\n\nclass IfExp(expr):\n test: expr\n body: expr\n orelse: expr\n\nclass Dict(expr):\n keys: typing.List[expr]\n values: typing.List[expr]\n\nclass Set(expr):\n elts: typing.List[expr]\n\nclass ListComp(expr):\n elt: expr\n generators: typing.List[comprehension]\n\nclass SetComp(expr):\n elt: expr\n generators: typing.List[comprehension]\n\nclass DictComp(expr):\n key: expr\n value: expr\n generators: typing.List[comprehension]\n\nclass GeneratorExp(expr):\n elt: expr\n generators: typing.List[comprehension]\n\nclass Yield(expr):\n value: Optional[expr]\n\nclass Compare(expr):\n left: expr\n ops: typing.List[cmpop]\n comparators: typing.List[expr]\n\nclass Call(expr):\n func: expr\n args: typing.List[expr]\n keywords: typing.List[keyword]\n starargs: Optional[expr]\n kwargs: Optional[expr]\n\nclass Repr(expr):\n value: expr\n\nclass Num(expr):\n n: Union[int, float, complex]\n\nclass Str(expr):\n s: Union[str, bytes]\n kind: str\n\nclass Attribute(expr):\n value: expr\n attr: identifier\n ctx: expr_context\n\nclass Subscript(expr):\n value: expr\n slice: _slice\n ctx: expr_context\n\nclass Name(expr):\n id: identifier\n ctx: expr_context\n\nclass List(expr):\n elts: typing.List[expr]\n ctx: expr_context\n\nclass Tuple(expr):\n elts: typing.List[expr]\n ctx: expr_context\n\nclass expr_context(AST): ...\nclass AugLoad(expr_context): ...\nclass AugStore(expr_context): ...\nclass Del(expr_context): ...\nclass Load(expr_context): ...\nclass Param(expr_context): ...\nclass Store(expr_context): ...\nclass boolop(AST): ...\nclass And(boolop): ...\nclass Or(boolop): ...\nclass operator(AST): ...\nclass Add(operator): ...\nclass BitAnd(operator): ...\nclass BitOr(operator): ...\nclass BitXor(operator): ...\nclass Div(operator): ...\nclass FloorDiv(operator): ...\nclass LShift(operator): ...\nclass Mod(operator): ...\nclass Mult(operator): ...\nclass Pow(operator): ...\nclass RShift(operator): ...\nclass Sub(operator): ...\nclass unaryop(AST): ...\nclass Invert(unaryop): ...\nclass Not(unaryop): ...\nclass UAdd(unaryop): ...\nclass USub(unaryop): ...\nclass cmpop(AST): ...\nclass Eq(cmpop): ...\nclass Gt(cmpop): ...\nclass GtE(cmpop): ...\nclass In(cmpop): ...\nclass Is(cmpop): ...\nclass IsNot(cmpop): ...\nclass Lt(cmpop): ...\nclass LtE(cmpop): ...\nclass NotEq(cmpop): ...\nclass NotIn(cmpop): ...\n\nclass comprehension(AST):\n target: expr\n iter: expr\n ifs: typing.List[expr]\n\nclass ExceptHandler(AST):\n type: Optional[expr]\n name: Optional[expr]\n body: typing.List[stmt]\n lineno: int\n col_offset: int\n\nclass arguments(AST):\n args: typing.List[expr]\n vararg: Optional[identifier]\n kwarg: Optional[identifier]\n defaults: typing.List[expr]\n type_comments: typing.List[Optional[str]]\n\nclass keyword(AST):\n arg: identifier\n value: expr\n\nclass alias(AST):\n name: identifier\n asname: Optional[identifier]\n\nclass TypeIgnore(AST):\n lineno: int\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\typed_ast\ast27.pyi | ast27.pyi | Other | 6,949 | 0.95 | 0.358209 | 0.003774 | vue-tools | 512 | 2024-01-03T01:23:14.470271 | MIT | false | b28c9b3d94ed41f66d75d4b087936688 |
import typing\nfrom typing import Any, Iterator, Optional, Union\n\nclass NodeVisitor:\n def visit(self, node: AST) -> Any: ...\n def generic_visit(self, node: AST) -> None: ...\n\nclass NodeTransformer(NodeVisitor):\n def generic_visit(self, node: AST) -> None: ...\n\ndef parse(source: Union[str, bytes], filename: Union[str, bytes] = ..., mode: str = ..., feature_version: int = ...) -> AST: ...\ndef copy_location(new_node: AST, old_node: AST) -> AST: ...\ndef dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ...\ndef fix_missing_locations(node: AST) -> AST: ...\ndef get_docstring(node: AST, clean: bool = ...) -> Optional[str]: ...\ndef increment_lineno(node: AST, n: int = ...) -> AST: ...\ndef iter_child_nodes(node: AST) -> Iterator[AST]: ...\ndef iter_fields(node: AST) -> Iterator[typing.Tuple[str, Any]]: ...\ndef literal_eval(node_or_string: Union[str, AST]) -> Any: ...\ndef walk(node: AST) -> Iterator[AST]: ...\n\nPyCF_ONLY_AST: int\n\n# ast classes\n\nidentifier = str\n\nclass AST:\n _attributes: typing.Tuple[str, ...]\n _fields: typing.Tuple[str, ...]\n def __init__(self, *args: Any, **kwargs: Any) -> None: ...\n\nclass mod(AST): ...\n\nclass Module(mod):\n body: typing.List[stmt]\n type_ignores: typing.List[TypeIgnore]\n\nclass Interactive(mod):\n body: typing.List[stmt]\n\nclass Expression(mod):\n body: expr\n\nclass FunctionType(mod):\n argtypes: typing.List[expr]\n returns: expr\n\nclass Suite(mod):\n body: typing.List[stmt]\n\nclass stmt(AST):\n lineno: int\n col_offset: int\n\nclass FunctionDef(stmt):\n name: identifier\n args: arguments\n body: typing.List[stmt]\n decorator_list: typing.List[expr]\n returns: Optional[expr]\n type_comment: Optional[str]\n\nclass AsyncFunctionDef(stmt):\n name: identifier\n args: arguments\n body: typing.List[stmt]\n decorator_list: typing.List[expr]\n returns: Optional[expr]\n type_comment: Optional[str]\n\nclass ClassDef(stmt):\n name: identifier\n bases: typing.List[expr]\n keywords: typing.List[keyword]\n body: typing.List[stmt]\n decorator_list: typing.List[expr]\n\nclass Return(stmt):\n value: Optional[expr]\n\nclass Delete(stmt):\n targets: typing.List[expr]\n\nclass Assign(stmt):\n targets: typing.List[expr]\n value: expr\n type_comment: Optional[str]\n\nclass AugAssign(stmt):\n target: expr\n op: operator\n value: expr\n\nclass AnnAssign(stmt):\n target: expr\n annotation: expr\n value: Optional[expr]\n simple: int\n\nclass For(stmt):\n target: expr\n iter: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n type_comment: Optional[str]\n\nclass AsyncFor(stmt):\n target: expr\n iter: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n type_comment: Optional[str]\n\nclass While(stmt):\n test: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n\nclass If(stmt):\n test: expr\n body: typing.List[stmt]\n orelse: typing.List[stmt]\n\nclass With(stmt):\n items: typing.List[withitem]\n body: typing.List[stmt]\n type_comment: Optional[str]\n\nclass AsyncWith(stmt):\n items: typing.List[withitem]\n body: typing.List[stmt]\n type_comment: Optional[str]\n\nclass Raise(stmt):\n exc: Optional[expr]\n cause: Optional[expr]\n\nclass Try(stmt):\n body: typing.List[stmt]\n handlers: typing.List[ExceptHandler]\n orelse: typing.List[stmt]\n finalbody: typing.List[stmt]\n\nclass Assert(stmt):\n test: expr\n msg: Optional[expr]\n\nclass Import(stmt):\n names: typing.List[alias]\n\nclass ImportFrom(stmt):\n module: Optional[identifier]\n names: typing.List[alias]\n level: Optional[int]\n\nclass Global(stmt):\n names: typing.List[identifier]\n\nclass Nonlocal(stmt):\n names: typing.List[identifier]\n\nclass Expr(stmt):\n value: expr\n\nclass Pass(stmt): ...\nclass Break(stmt): ...\nclass Continue(stmt): ...\nclass slice(AST): ...\n\n_slice = slice # this lets us type the variable named 'slice' below\n\nclass Slice(slice):\n lower: Optional[expr]\n upper: Optional[expr]\n step: Optional[expr]\n\nclass ExtSlice(slice):\n dims: typing.List[slice]\n\nclass Index(slice):\n value: expr\n\nclass expr(AST):\n lineno: int\n col_offset: int\n\nclass BoolOp(expr):\n op: boolop\n values: typing.List[expr]\n\nclass BinOp(expr):\n left: expr\n op: operator\n right: expr\n\nclass UnaryOp(expr):\n op: unaryop\n operand: expr\n\nclass Lambda(expr):\n args: arguments\n body: expr\n\nclass IfExp(expr):\n test: expr\n body: expr\n orelse: expr\n\nclass Dict(expr):\n keys: typing.List[expr]\n values: typing.List[expr]\n\nclass Set(expr):\n elts: typing.List[expr]\n\nclass ListComp(expr):\n elt: expr\n generators: typing.List[comprehension]\n\nclass SetComp(expr):\n elt: expr\n generators: typing.List[comprehension]\n\nclass DictComp(expr):\n key: expr\n value: expr\n generators: typing.List[comprehension]\n\nclass GeneratorExp(expr):\n elt: expr\n generators: typing.List[comprehension]\n\nclass Await(expr):\n value: expr\n\nclass Yield(expr):\n value: Optional[expr]\n\nclass YieldFrom(expr):\n value: expr\n\nclass Compare(expr):\n left: expr\n ops: typing.List[cmpop]\n comparators: typing.List[expr]\n\nclass Call(expr):\n func: expr\n args: typing.List[expr]\n keywords: typing.List[keyword]\n\nclass Num(expr):\n n: Union[float, int, complex]\n\nclass Str(expr):\n s: str\n kind: str\n\nclass FormattedValue(expr):\n value: expr\n conversion: typing.Optional[int]\n format_spec: typing.Optional[expr]\n\nclass JoinedStr(expr):\n values: typing.List[expr]\n\nclass Bytes(expr):\n s: bytes\n\nclass NameConstant(expr):\n value: Any\n\nclass Ellipsis(expr): ...\n\nclass Attribute(expr):\n value: expr\n attr: identifier\n ctx: expr_context\n\nclass Subscript(expr):\n value: expr\n slice: _slice\n ctx: expr_context\n\nclass Starred(expr):\n value: expr\n ctx: expr_context\n\nclass Name(expr):\n id: identifier\n ctx: expr_context\n\nclass List(expr):\n elts: typing.List[expr]\n ctx: expr_context\n\nclass Tuple(expr):\n elts: typing.List[expr]\n ctx: expr_context\n\nclass expr_context(AST): ...\nclass AugLoad(expr_context): ...\nclass AugStore(expr_context): ...\nclass Del(expr_context): ...\nclass Load(expr_context): ...\nclass Param(expr_context): ...\nclass Store(expr_context): ...\nclass boolop(AST): ...\nclass And(boolop): ...\nclass Or(boolop): ...\nclass operator(AST): ...\nclass Add(operator): ...\nclass BitAnd(operator): ...\nclass BitOr(operator): ...\nclass BitXor(operator): ...\nclass Div(operator): ...\nclass FloorDiv(operator): ...\nclass LShift(operator): ...\nclass Mod(operator): ...\nclass Mult(operator): ...\nclass MatMult(operator): ...\nclass Pow(operator): ...\nclass RShift(operator): ...\nclass Sub(operator): ...\nclass unaryop(AST): ...\nclass Invert(unaryop): ...\nclass Not(unaryop): ...\nclass UAdd(unaryop): ...\nclass USub(unaryop): ...\nclass cmpop(AST): ...\nclass Eq(cmpop): ...\nclass Gt(cmpop): ...\nclass GtE(cmpop): ...\nclass In(cmpop): ...\nclass Is(cmpop): ...\nclass IsNot(cmpop): ...\nclass Lt(cmpop): ...\nclass LtE(cmpop): ...\nclass NotEq(cmpop): ...\nclass NotIn(cmpop): ...\n\nclass comprehension(AST):\n target: expr\n iter: expr\n ifs: typing.List[expr]\n is_async: int\n\nclass ExceptHandler(AST):\n type: Optional[expr]\n name: Optional[identifier]\n body: typing.List[stmt]\n lineno: int\n col_offset: int\n\nclass arguments(AST):\n args: typing.List[arg]\n vararg: Optional[arg]\n kwonlyargs: typing.List[arg]\n kw_defaults: typing.List[expr]\n kwarg: Optional[arg]\n defaults: typing.List[expr]\n\nclass arg(AST):\n arg: identifier\n annotation: Optional[expr]\n lineno: int\n col_offset: int\n type_comment: typing.Optional[str]\n\nclass keyword(AST):\n arg: Optional[identifier]\n value: expr\n\nclass alias(AST):\n name: identifier\n asname: Optional[identifier]\n\nclass withitem(AST):\n context_expr: expr\n optional_vars: Optional[expr]\n\nclass TypeIgnore(AST):\n lineno: int\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\typed_ast\ast3.pyi | ast3.pyi | Other | 7,946 | 0.95 | 0.341146 | 0.003289 | node-utils | 425 | 2023-12-25T13:21:44.879784 | BSD-3-Clause | false | 074500ab342a8eebc94491b8405293e3 |
from . import ast3, ast27\n\ndef py2to3(ast: ast27.AST) -> ast3.AST: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\typed_ast\conversions.pyi | conversions.pyi | Other | 71 | 0.65 | 0.333333 | 0 | awesome-app | 902 | 2024-10-11T21:50:46.271609 | BSD-3-Clause | false | dcdca3eb3c43600f839bc0db0b486424 |
from socket import SocketType\nfrom typing import Any, Dict, FrozenSet, Iterable, List, Optional, Sequence, Set, Tuple, Union\n\nfrom .compat import HAS_IPV6 as HAS_IPV6, PY2 as PY2, WIN as WIN, string_types as string_types\nfrom .proxy_headers import PROXY_HEADERS as PROXY_HEADERS\n\ntruthy: FrozenSet\nKNOWN_PROXY_HEADERS: FrozenSet\n\ndef asbool(s: Optional[Union[bool, str, int]]) -> bool: ...\ndef asoctal(s: str) -> int: ...\ndef aslist_cronly(value: str) -> List[str]: ...\ndef aslist(value: str) -> List[str]: ...\ndef asset(value: Optional[str]) -> Set[str]: ...\ndef slash_fixed_str(s: Optional[str]) -> str: ...\ndef str_iftruthy(s: Optional[str]) -> Optional[str]: ...\ndef as_socket_list(sockets: Sequence[object]) -> List[SocketType]: ...\n\nclass _str_marker(str): ...\nclass _int_marker(int): ...\nclass _bool_marker: ...\n\nclass Adjustments:\n host: _str_marker = ...\n port: _int_marker = ...\n listen: List[str] = ...\n threads: int = ...\n trusted_proxy: Optional[str] = ...\n trusted_proxy_count: Optional[int] = ...\n trusted_proxy_headers: Set[str] = ...\n log_untrusted_proxy_headers: bool = ...\n clear_untrusted_proxy_headers: Union[_bool_marker, bool] = ...\n url_scheme: str = ...\n url_prefix: str = ...\n ident: str = ...\n backlog: int = ...\n recv_bytes: int = ...\n send_bytes: int = ...\n outbuf_overflow: int = ...\n outbuf_high_watermark: int = ...\n inbuf_overflow: int = ...\n connection_limit: int = ...\n cleanup_interval: int = ...\n channel_timeout: int = ...\n log_socket_errors: bool = ...\n max_request_header_size: int = ...\n max_request_body_size: int = ...\n expose_tracebacks: bool = ...\n unix_socket: Optional[str] = ...\n unix_socket_perms: int = ...\n socket_options: List[Tuple[int, int, int]] = ...\n asyncore_loop_timeout: int = ...\n asyncore_use_poll: bool = ...\n ipv4: bool = ...\n ipv6: bool = ...\n sockets: List[SocketType] = ...\n def __init__(self, **kw: Any) -> None: ...\n @classmethod\n def parse_args(cls, argv: str) -> Tuple[Dict[str, Any], Any]: ...\n @classmethod\n def check_sockets(cls, sockets: Iterable[SocketType]) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\adjustments.pyi | adjustments.pyi | Other | 2,162 | 0.85 | 0.245902 | 0 | vue-tools | 769 | 2025-04-20T16:49:59.847683 | GPL-3.0 | false | cc898d6f992f118d0c18b8be2c0f38b2 |
from io import BufferedIOBase, BufferedRandom, BytesIO\nfrom typing import Any, Callable, Optional\n\nCOPY_BYTES: int\nSTRBUF_LIMIT: int\n\nclass FileBasedBuffer:\n remain: int = ...\n file: BytesIO = ...\n def __init__(self, file: BytesIO, from_buffer: Optional[BytesIO] = ...) -> None: ...\n def __len__(self) -> int: ...\n def __nonzero__(self) -> bool: ...\n __bool__: Callable[[], bool] = ...\n def append(self, s: Any) -> None: ...\n def get(self, numbytes: int = ..., skip: bool = ...) -> bytes: ...\n def skip(self, numbytes: int, allow_prune: int = ...) -> None: ...\n def newfile(self) -> Any: ...\n def prune(self) -> None: ...\n def getfile(self) -> Any: ...\n def close(self) -> None: ...\n\nclass TempfileBasedBuffer(FileBasedBuffer):\n def __init__(self, from_buffer: Optional[BytesIO] = ...) -> None: ...\n def newfile(self) -> BufferedRandom: ...\n\nclass BytesIOBasedBuffer(FileBasedBuffer):\n file: BytesIO = ...\n def __init__(self, from_buffer: Optional[BytesIO] = ...) -> None: ...\n def newfile(self) -> BytesIO: ...\n\nclass ReadOnlyFileBasedBuffer(FileBasedBuffer):\n file: BytesIO = ...\n block_size: int = ...\n def __init__(self, file: BytesIO, block_size: int = ...) -> None: ...\n remain: int = ...\n def prepare(self, size: Optional[int] = ...) -> int: ...\n def get(self, numbytes: int = ..., skip: bool = ...) -> bytes: ...\n def __iter__(self) -> ReadOnlyFileBasedBuffer: ...\n def next(self) -> Optional[bytes]: ...\n __next__: Callable[[], Optional[bytes]] = ...\n def append(self, s: Any) -> None: ...\n\nclass OverflowableBuffer:\n overflowed: bool = ...\n buf: Optional[BufferedIOBase] = ...\n strbuf: bytes = ...\n overflow: int = ...\n def __init__(self, overflow: int) -> None: ...\n def __len__(self) -> int: ...\n def __nonzero__(self) -> bool: ...\n __bool__: Callable[[], bool] = ...\n def append(self, s: bytes) -> None: ...\n def get(self, numbytes: int = ..., skip: bool = ...) -> bytes: ...\n def skip(self, numbytes: int, allow_prune: bool = ...) -> None: ...\n def prune(self) -> None: ...\n def getfile(self) -> BytesIO: ...\n def close(self) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\buffers.pyi | buffers.pyi | Other | 2,179 | 0.85 | 0.596491 | 0 | awesome-app | 538 | 2023-09-05T17:09:07.936957 | GPL-3.0 | false | f2ad5c5e2bb8873b6e388e014d321943 |
from socket import SocketType\nfrom threading import Condition, Lock\nfrom typing import Mapping, Optional, Sequence, Tuple\n\nfrom waitress.adjustments import Adjustments\nfrom waitress.buffers import OverflowableBuffer\nfrom waitress.parser import HTTPRequestParser\nfrom waitress.server import BaseWSGIServer\nfrom waitress.task import ErrorTask, WSGITask\n\nfrom . import wasyncore as wasyncore\n\nclass ClientDisconnected(Exception): ...\n\nclass HTTPChannel(wasyncore.dispatcher):\n task_class: WSGITask = ...\n error_task_class: ErrorTask = ...\n parser_class: HTTPRequestParser = ...\n request: HTTPRequestParser = ...\n last_activity: float = ...\n will_close: bool = ...\n close_when_flushed: bool = ...\n requests: Sequence[HTTPRequestParser] = ...\n sent_continue: bool = ...\n total_outbufs_len: int = ...\n current_outbuf_count: int = ...\n server: BaseWSGIServer = ...\n adj: Adjustments = ...\n outbufs: Sequence[OverflowableBuffer] = ...\n creation_time: float = ...\n sendbuf_len: int = ...\n task_lock: Lock = ...\n outbuf_lock: Condition = ...\n addr: Tuple[str, int] = ...\n def __init__(\n self, server: BaseWSGIServer, sock: SocketType, addr: str, adj: Adjustments, map: Optional[Mapping[int, SocketType]] = ...\n ) -> None: ...\n def writable(self) -> bool: ...\n def handle_write(self) -> None: ...\n def readable(self) -> bool: ...\n def handle_read(self) -> None: ...\n def received(self, data: bytes) -> bool: ...\n connected: bool = ...\n def handle_close(self) -> None: ...\n def add_channel(self, map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n def del_channel(self, map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n def write_soon(self, data: bytes) -> int: ...\n def service(self) -> None: ...\n def cancel(self) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\channel.pyi | channel.pyi | Other | 1,843 | 0.85 | 0.285714 | 0 | vue-tools | 340 | 2024-10-08T03:56:20.720091 | Apache-2.0 | false | 805f7cdf1aca4b8363bbd9e141bc8fcd |
import sys\nfrom io import TextIOWrapper\nfrom typing import Any, Optional, Tuple\n\nPY2: bool\nPY3: bool\nWIN: bool\nstring_types: Tuple[\n str,\n]\ninteger_types: Tuple[\n int,\n]\nclass_types: Tuple[\n type,\n]\ntext_type = str\nbinary_type = bytes\nlong = int\n\ndef unquote_bytes_to_wsgi(bytestring: bytes) -> str: ...\ndef text_(s: str, encoding: str = ..., errors: str = ...) -> str: ...\ndef tostr(s: str) -> str: ...\ndef tobytes(s: str) -> bytes: ...\n\nexec_: Any\n\ndef reraise(tp: Any, value: BaseException, tb: Optional[str] = ...) -> None: ...\n\nMAXINT: int\nHAS_IPV6: bool\nIPPROTO_IPV6: int\nIPV6_V6ONLY: int\n\ndef set_nonblocking(fd: TextIOWrapper) -> None: ...\n\nResourceWarning: Warning\n\ndef qualname(cls: Any) -> str: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\compat.pyi | compat.pyi | Other | 719 | 0.85 | 0.179487 | 0 | awesome-app | 128 | 2024-09-24T01:56:26.150730 | MIT | false | cec6db5247988f4868e791184be879ec |
from io import BytesIO\nfrom typing import Mapping, Optional, Pattern, Sequence, Tuple, Union\n\nfrom waitress.adjustments import Adjustments\nfrom waitress.receiver import ChunkedReceiver, FixedStreamReceiver\nfrom waitress.utilities import Error\n\nfrom .rfc7230 import HEADER_FIELD as HEADER_FIELD\n\nclass ParsingError(Exception): ...\nclass TransferEncodingNotImplemented(Exception): ...\n\nclass HTTPRequestParser:\n completed: bool = ...\n empty: bool = ...\n expect_continue: bool = ...\n headers_finished: bool = ...\n header_plus: bytes = ...\n chunked: bool = ...\n content_length: int = ...\n header_bytes_received: int = ...\n body_bytes_received: int = ...\n body_rcv: Optional[Union[ChunkedReceiver, FixedStreamReceiver]] = ...\n version: str = ...\n error: Optional[Error] = ...\n connection_close: bool = ...\n headers: Mapping[str, str] = ...\n adj: Adjustments = ...\n def __init__(self, adj: Adjustments) -> None: ...\n def received(self, data: bytes) -> int: ...\n first_line: str = ...\n command: bytes = ...\n url_scheme: str = ...\n def parse_header(self, header_plus: bytes) -> None: ...\n def get_body_stream(self) -> BytesIO: ...\n def close(self) -> None: ...\n\ndef split_uri(uri: bytes) -> Tuple[str, str, bytes, str, str]: ...\ndef get_header_lines(header: bytes) -> Sequence[bytes]: ...\n\nfirst_line_re: Pattern\n\ndef crack_first_line(line: str) -> Tuple[bytes, bytes, bytes]: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\parser.pyi | parser.pyi | Other | 1,442 | 0.85 | 0.255814 | 0 | awesome-app | 862 | 2025-06-20T01:29:12.377341 | MIT | false | f97d08c56f30ad5ef94588d8ef27ec99 |
from collections import namedtuple\nfrom logging import Logger\nfrom typing import Any, Callable, Mapping, Optional, Sequence, Set\n\nfrom .utilities import BadRequest as BadRequest\n\nPROXY_HEADERS: frozenset\n\nForwarded = namedtuple("Forwarded", ["by", "for_", "host", "proto"])\n\nclass MalformedProxyHeader(Exception):\n header: str = ...\n reason: str = ...\n value: str = ...\n def __init__(self, header: str, reason: str, value: str) -> None: ...\n\ndef proxy_headers_middleware(\n app: Any,\n trusted_proxy: Optional[str] = ...,\n trusted_proxy_count: int = ...,\n trusted_proxy_headers: Optional[Set[str]] = ...,\n clear_untrusted: bool = ...,\n log_untrusted: bool = ...,\n logger: Logger = ...,\n) -> Callable[..., Any]: ...\ndef parse_proxy_headers(\n environ: Mapping[str, str], trusted_proxy_count: int, trusted_proxy_headers: Set[str], logger: Logger = ...\n) -> Set[str]: ...\ndef strip_brackets(addr: str) -> str: ...\ndef clear_untrusted_headers(\n environ: Mapping[str, str], untrusted_headers: Sequence[str], log_warning: bool = ..., logger: Logger = ...\n) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\proxy_headers.pyi | proxy_headers.pyi | Other | 1,100 | 0.85 | 0.1875 | 0 | awesome-app | 819 | 2024-11-04T03:59:35.933749 | BSD-3-Clause | false | 59b2938aa9039867137debd23378860a |
from io import BytesIO\nfrom typing import Optional\n\nfrom waitress.buffers import OverflowableBuffer\nfrom waitress.utilities import BadRequest\n\nclass FixedStreamReceiver:\n completed: bool = ...\n error: None = ...\n remain: int = ...\n buf: OverflowableBuffer = ...\n def __init__(self, cl: int, buf: OverflowableBuffer) -> None: ...\n def __len__(self) -> int: ...\n def received(self, data: bytes) -> int: ...\n def getfile(self) -> BytesIO: ...\n def getbuf(self) -> OverflowableBuffer: ...\n\nclass ChunkedReceiver:\n chunk_remainder: int = ...\n validate_chunk_end: bool = ...\n control_line: bytes = ...\n chunk_end: bytes = ...\n all_chunks_received: bool = ...\n trailer: bytes = ...\n completed: bool = ...\n error: Optional[BadRequest] = ...\n buf: OverflowableBuffer = ...\n def __init__(self, buf: OverflowableBuffer) -> None: ...\n def __len__(self) -> int: ...\n def received(self, s: bytes) -> int: ...\n def getfile(self) -> BytesIO: ...\n def getbuf(self) -> OverflowableBuffer: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\receiver.pyi | receiver.pyi | Other | 1,044 | 0.85 | 0.375 | 0 | node-utils | 423 | 2024-10-01T01:37:50.168691 | MIT | false | 85df4fbdb1d2467fa8b3386dd2a02153 |
from typing import Pattern\n\nfrom .compat import tobytes as tobytes\n\nWS: str\nOWS: str\nRWS: str\nBWS = str\nTCHAR: str\nOBS_TEXT: str\nTOKEN: str\nVCHAR: str\nFIELD_VCHAR: str\nFIELD_CONTENT: str\nFIELD_VALUE: str\nHEADER_FIELD: Pattern\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\rfc7230.pyi | rfc7230.pyi | Other | 226 | 0.85 | 0 | 0 | vue-tools | 772 | 2024-05-14T21:20:57.650011 | BSD-3-Clause | false | fbb86a9af6393323cf1daceb8f163e42 |
from io import TextIOWrapper\nfrom typing import Any, Callable, Optional, Pattern, Sequence, Tuple\n\nHELP: str\nRUNNER_PATTERN: Pattern\n\ndef match(obj_name: str) -> Tuple[str, str]: ...\ndef resolve(module_name: str, object_name: str) -> Any: ...\ndef show_help(stream: TextIOWrapper, name: str, error: Optional[str] = ...) -> None: ...\ndef show_exception(stream: TextIOWrapper) -> None: ...\ndef run(argv: Sequence[str] = ..., _serve: Callable[..., Any] = ...) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\runner.pyi | runner.pyi | Other | 469 | 0.85 | 0.454545 | 0 | python-kit | 82 | 2025-01-20T10:53:51.312208 | GPL-3.0 | false | 26bf1968d3333b8e11ea04150adce529 |
from socket import SocketType\nfrom typing import Any, Optional, Sequence, Tuple, Union\n\nfrom waitress.adjustments import Adjustments\nfrom waitress.channel import HTTPChannel\nfrom waitress.task import Task, ThreadedTaskDispatcher\n\nfrom . import wasyncore\n\ndef create_server(\n application: Any,\n map: Optional[Any] = ...,\n _start: bool = ...,\n _sock: Optional[SocketType] = ...,\n _dispatcher: Optional[ThreadedTaskDispatcher] = ...,\n **kw: Any,\n) -> Union[MultiSocketServer, BaseWSGIServer]: ...\n\nclass MultiSocketServer:\n asyncore: Any = ...\n adj: Adjustments = ...\n map: Any = ...\n effective_listen: Sequence[Tuple[str, int]] = ...\n task_dispatcher: ThreadedTaskDispatcher = ...\n def __init__(\n self,\n map: Optional[Any] = ...,\n adj: Optional[Adjustments] = ...,\n effective_listen: Optional[Sequence[Tuple[str, int]]] = ...,\n dispatcher: Optional[ThreadedTaskDispatcher] = ...,\n ) -> None: ...\n def print_listen(self, format_str: str) -> None: ...\n def run(self) -> None: ...\n def close(self) -> None: ...\n\nclass BaseWSGIServer(wasyncore.dispatcher):\n channel_class: HTTPChannel = ...\n next_channel_cleanup: int = ...\n socketmod: SocketType = ...\n asyncore: Any = ...\n sockinfo: Tuple[int, int, int, Tuple[str, int]] = ...\n family: int = ...\n socktype: int = ...\n application: Any = ...\n adj: Adjustments = ...\n trigger: int = ...\n task_dispatcher: ThreadedTaskDispatcher = ...\n server_name: str = ...\n active_channels: HTTPChannel = ...\n def __init__(\n self,\n application: Any,\n map: Optional[Any] = ...,\n _start: bool = ...,\n _sock: Optional[Any] = ...,\n dispatcher: Optional[ThreadedTaskDispatcher] = ...,\n adj: Optional[Adjustments] = ...,\n sockinfo: Optional[Any] = ...,\n bind_socket: bool = ...,\n **kw: Any,\n ) -> None: ...\n def bind_server_socket(self) -> None: ...\n def get_server_name(self, ip: str) -> str: ...\n def getsockname(self) -> Any: ...\n accepting: bool = ...\n def accept_connections(self) -> None: ...\n def add_task(self, task: Task) -> None: ...\n def readable(self) -> bool: ...\n def writable(self) -> bool: ...\n def handle_read(self) -> None: ...\n def handle_connect(self) -> None: ...\n def handle_accept(self) -> None: ...\n def run(self) -> None: ...\n def pull_trigger(self) -> None: ...\n def set_socket_options(self, conn: Any) -> None: ...\n def fix_addr(self, addr: Any) -> Any: ...\n def maintenance(self, now: int) -> None: ...\n def print_listen(self, format_str: str) -> None: ...\n def close(self) -> None: ...\n\nclass TcpWSGIServer(BaseWSGIServer):\n def bind_server_socket(self) -> None: ...\n def getsockname(self) -> Tuple[str, Tuple[str, int]]: ...\n def set_socket_options(self, conn: SocketType) -> None: ...\n\nclass UnixWSGIServer(BaseWSGIServer):\n def __init__(\n self,\n application: Any,\n map: Optional[Any] = ...,\n _start: bool = ...,\n _sock: Optional[Any] = ...,\n dispatcher: Optional[Any] = ...,\n adj: Optional[Adjustments] = ...,\n sockinfo: Optional[Any] = ...,\n **kw: Any,\n ) -> None: ...\n def bind_server_socket(self) -> None: ...\n def getsockname(self) -> Tuple[str, Tuple[str, int]]: ...\n def fix_addr(self, addr: Any) -> Tuple[str, None]: ...\n def get_server_name(self, ip: Any) -> str: ...\n\nWSGIServer: TcpWSGIServer\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\server.pyi | server.pyi | Other | 3,500 | 0.85 | 0.339806 | 0.031579 | python-kit | 91 | 2023-11-30T05:35:11.709814 | BSD-3-Clause | false | 737017097869f8e52ca922c078419f4b |
from logging import Logger\nfrom threading import Condition, Lock\nfrom typing import Any, Deque, Mapping, Optional, Sequence, Set, Tuple\n\nfrom .channel import HTTPChannel\nfrom .utilities import Error\n\nrename_headers: Mapping[str, str]\nhop_by_hop: frozenset\n\nclass ThreadedTaskDispatcher:\n stop_count: int = ...\n active_count: int = ...\n logger: Logger = ...\n queue_logger: Logger = ...\n threads: Set = ...\n queue: Deque[Task] = ...\n lock: Lock = ...\n queue_cv: Condition = ...\n thread_exit_cv: Condition = ...\n def __init__(self) -> None: ...\n def start_new_thread(self, target: Any, args: Any) -> None: ...\n def handler_thread(self, thread_no: int) -> None: ...\n def set_thread_count(self, count: int) -> None: ...\n def add_task(self, task: Task) -> None: ...\n def shutdown(self, cancel_pending: bool = ..., timeout: int = ...) -> bool: ...\n\nclass Task:\n close_on_finish: bool = ...\n status: str = ...\n wrote_header: bool = ...\n start_time: int = ...\n content_length: Optional[int] = ...\n content_bytes_written: int = ...\n logged_write_excess: bool = ...\n logged_write_no_body: bool = ...\n complete: bool = ...\n chunked_response: bool = ...\n logger: Logger = ...\n channel: HTTPChannel = ...\n request: Error = ...\n response_headers: Sequence[Tuple[str, str]] = ...\n version: str = ...\n def __init__(self, channel: HTTPChannel, request: Error) -> None: ...\n def service(self) -> None: ...\n @property\n def has_body(self) -> bool: ...\n def build_response_header(self) -> bytes: ...\n def remove_content_length_header(self) -> None: ...\n def start(self) -> None: ...\n def finish(self) -> None: ...\n def write(self, data: bytes) -> None: ...\n\nclass ErrorTask(Task):\n complete: bool = ...\n status: str = ...\n close_on_finish: bool = ...\n content_length: int = ...\n def execute(self) -> None: ...\n\nclass WSGITask(Task):\n environ: Optional[Any] = ...\n response_headers: Sequence[Tuple[str, str]] = ...\n complete: bool = ...\n status: str = ...\n content_length: int = ...\n close_on_finish: bool = ...\n def execute(self) -> None: ...\n def get_environment(self) -> Any: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\task.pyi | task.pyi | Other | 2,216 | 0.85 | 0.304348 | 0 | react-lib | 934 | 2025-03-18T22:35:59.065606 | Apache-2.0 | false | 452677cb2850c0f075c2077db9b27310 |
import sys\nfrom socket import SocketType\nfrom threading import Lock\nfrom typing import Callable, Mapping, Optional\nfrom typing_extensions import Literal\n\nfrom . import wasyncore as wasyncore\n\nclass _triggerbase:\n kind: Optional[str] = ...\n lock: Lock = ...\n thunks: Callable[[None], None] = ...\n def __init__(self) -> None: ...\n def readable(self) -> Literal[True]: ...\n def writable(self) -> Literal[False]: ...\n def handle_connect(self) -> None: ...\n def handle_close(self) -> None: ...\n def close(self) -> None: ...\n def pull_trigger(self, thunk: Optional[Callable[[None], None]] = ...) -> None: ...\n def handle_read(self) -> None: ...\n\nif sys.platform == "linux" or sys.platform == "darwin":\n class trigger(_triggerbase, wasyncore.file_dispatcher):\n kind: str = ...\n def __init__(self, map: Mapping[str, _triggerbase]) -> None: ...\n\nelse:\n class trigger(_triggerbase, wasyncore.dispatcher):\n kind: str = ...\n trigger: SocketType = ...\n def __init__(self, map: Mapping[str, _triggerbase]) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\trigger.pyi | trigger.pyi | Other | 1,079 | 0.85 | 0.451613 | 0 | python-kit | 769 | 2025-02-23T15:40:22.180647 | GPL-3.0 | false | ab57d34399d211bd225cefaeb1cc8508 |
from logging import Logger\nfrom typing import Any, Callable, Mapping, Match, Pattern, Sequence, Tuple\n\nfrom .rfc7230 import OBS_TEXT as OBS_TEXT, VCHAR as VCHAR\n\nlogger: Logger\nqueue_logger: Logger\n\ndef find_double_newline(s: bytes) -> int: ...\ndef concat(*args: Any) -> str: ...\ndef join(seq: Any, field: str = ...) -> str: ...\ndef group(s: Any) -> str: ...\n\nshort_days: Sequence[str]\nlong_days: Sequence[str]\nshort_day_reg: str\nlong_day_reg: str\ndaymap: Mapping[str, int]\nhms_reg: str\nmonths: Sequence[str]\nmonmap: Mapping[str, int]\nmonths_reg: str\nrfc822_date: str\nrfc822_reg: Pattern\n\ndef unpack_rfc822(m: Match) -> Tuple[int, int, int, int, int, int, int, int, int]: ...\n\nrfc850_date: str\nrfc850_reg: Pattern\n\ndef unpack_rfc850(m: Match) -> Tuple[int, int, int, int, int, int, int, int, int]: ...\n\nweekdayname: Sequence[str]\nmonthname: Sequence[str]\n\ndef build_http_date(when: int) -> str: ...\ndef parse_http_date(d: str) -> int: ...\n\nvchar_re: str\nobs_text_re: str\nqdtext_re: str\nquoted_pair_re: str\nquoted_string_re: str\nquoted_string: Pattern\nquoted_pair: Pattern\n\ndef undquote(value: str) -> str: ...\ndef cleanup_unix_socket(path: str) -> None: ...\n\nclass Error:\n code: int = ...\n reason: str = ...\n body: str = ...\n def __init__(self, body: str) -> None: ...\n def to_response(self) -> Tuple[str, Sequence[Tuple[str, str]], str]: ...\n def wsgi_response(self, environ: Any, start_response: Callable[[str, Sequence[Tuple[str, str]]], None]) -> str: ...\n\nclass BadRequest(Error):\n code: int = ...\n reason: str = ...\n\nclass RequestHeaderFieldsTooLarge(BadRequest):\n code: int = ...\n reason: str = ...\n\nclass RequestEntityTooLarge(BadRequest):\n code: int = ...\n reason: str = ...\n\nclass InternalServerError(Error):\n code: int = ...\n reason: str = ...\n\nclass ServerNotImplemented(Error):\n code: int = ...\n reason: str = ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\utilities.pyi | utilities.pyi | Other | 1,875 | 0.85 | 0.25 | 0 | node-utils | 935 | 2024-03-13T23:28:03.711080 | MIT | false | 97105ba4fc60700a30357f7c1a7f5975 |
from io import BytesIO\nfrom logging import Logger\nfrom socket import SocketType\nfrom typing import Any, Callable, Mapping, Optional, Tuple\n\nfrom . import compat as compat, utilities as utilities\n\nsocket_map: Mapping[int, SocketType]\nmap: Mapping[int, SocketType]\n\nclass ExitNow(Exception): ...\n\ndef read(obj: dispatcher) -> None: ...\ndef write(obj: dispatcher) -> None: ...\ndef readwrite(obj: dispatcher, flags: int) -> None: ...\ndef poll(timeout: float = ..., map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\ndef poll2(timeout: float = ..., map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n\npoll3 = poll2\n\ndef loop(\n timeout: float = ..., use_poll: bool = ..., map: Optional[Mapping[int, SocketType]] = ..., count: Optional[int] = ...\n) -> None: ...\ndef compact_traceback() -> Tuple[Tuple[str, str, str], BaseException, BaseException, str]: ...\n\nclass dispatcher:\n debug: bool = ...\n connected: bool = ...\n accepting: bool = ...\n connecting: bool = ...\n closing: bool = ...\n addr: Optional[Tuple[str, int]] = ...\n ignore_log_types: frozenset = ...\n logger: Logger = ...\n compact_traceback: Callable[[], Tuple[Tuple[str, str, str], BaseException, BaseException, str]] = ...\n socket: Optional[SocketType] = ...\n def __init__(self, sock: Optional[SocketType] = ..., map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n def add_channel(self, map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n def del_channel(self, map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n family_and_type: Tuple[int, int] = ...\n def create_socket(self, family: int = ..., type: int = ...) -> None: ...\n def set_socket(self, sock: SocketType, map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n def set_reuse_addr(self) -> None: ...\n def readable(self) -> bool: ...\n def writable(self) -> bool: ...\n def listen(self, num: int) -> None: ...\n def bind(self, addr: Tuple[str, int]) -> None: ...\n def connect(self, address: Tuple[str, int]) -> None: ...\n def accept(self) -> Optional[Tuple[SocketType, Tuple[str, int]]]: ...\n def send(self, data: bytes) -> int: ...\n def recv(self, buffer_size: int) -> bytes: ...\n def close(self) -> None: ...\n def log(self, message: str) -> None: ...\n def log_info(self, message: str, type: str = ...) -> None: ...\n def handle_read_event(self) -> None: ...\n def handle_connect_event(self) -> None: ...\n def handle_write_event(self) -> None: ...\n def handle_expt_event(self) -> None: ...\n def handle_error(self) -> None: ...\n def handle_expt(self) -> None: ...\n def handle_read(self) -> None: ...\n def handle_write(self) -> None: ...\n def handle_connect(self) -> None: ...\n def handle_accept(self) -> None: ...\n def handle_accepted(self, sock: SocketType, addr: Any) -> None: ...\n def handle_close(self) -> None: ...\n\nclass dispatcher_with_send(dispatcher):\n out_buffer: bytes = ...\n def __init__(self, sock: Optional[SocketType] = ..., map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n def initiate_send(self) -> None: ...\n handle_write: Callable[[], None] = ...\n def writable(self) -> bool: ...\n def send(self, data: bytes) -> None: ... # type: ignore\n\ndef close_all(map: Optional[Mapping[int, SocketType]] = ..., ignore_all: bool = ...) -> None: ...\n\nclass file_wrapper:\n fd: BytesIO = ...\n def __init__(self, fd: BytesIO) -> None: ...\n def __del__(self) -> None: ...\n def recv(self, *args: Any) -> bytes: ...\n def send(self, *args: Any) -> bytes: ...\n def getsockopt(self, level: int, optname: int, buflen: Optional[bool] = ...) -> int: ...\n read: Callable[..., bytes] = ...\n write: Callable[..., bytes] = ...\n def close(self) -> None: ...\n def fileno(self) -> BytesIO: ...\n\nclass file_dispatcher(dispatcher):\n connected: bool = ...\n def __init__(self, fd: BytesIO, map: Optional[Mapping[int, SocketType]] = ...) -> None: ...\n socket: SocketType = ...\n def set_file(self, fd: BytesIO) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\wasyncore.pyi | wasyncore.pyi | Other | 4,059 | 0.95 | 0.585106 | 0 | python-kit | 854 | 2024-06-27T14:01:45.845271 | Apache-2.0 | false | 89f93378fcae502aee7a095467556536 |
from typing import Any, Tuple\n\nfrom waitress.server import create_server as create_server\n\ndef serve(app: Any, **kw: Any) -> None: ...\ndef serve_paste(app: Any, global_conf: Any, **kw: Any) -> int: ...\ndef profile(cmd: Any, globals: Any, locals: Any, sort_order: Tuple[str, ...], callers: bool) -> None: ...\n | .venv\Lib\site-packages\jedi\third_party\typeshed\third_party\3\waitress\__init__.pyi | __init__.pyi | Other | 308 | 0.85 | 0.428571 | 0 | vue-tools | 915 | 2025-06-07T19:32:51.892596 | GPL-3.0 | false | c4ff0a586dc09bccc01ba7f02f2c8fb2 |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\cache.cpython-313.pyc | cache.cpython-313.pyc | Other | 5,359 | 0.95 | 0.157895 | 0.019231 | awesome-app | 117 | 2024-09-22T21:13:06.131896 | BSD-3-Clause | false | 69078a646c5fc9e3716a5000244ecb66 |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\common.cpython-313.pyc | common.cpython-313.pyc | Other | 1,341 | 0.95 | 0.076923 | 0 | awesome-app | 259 | 2023-09-05T09:59:28.481891 | GPL-3.0 | false | f8040584a560fe7c4c6f47c92a7ccad8 |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\debug.cpython-313.pyc | debug.cpython-313.pyc | Other | 5,196 | 0.95 | 0.126984 | 0 | node-utils | 179 | 2023-11-14T15:45:00.716111 | MIT | false | cf0a6a77b1bf6a55c68be94b32cdeffa |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\file_io.cpython-313.pyc | file_io.cpython-313.pyc | Other | 5,546 | 0.8 | 0 | 0 | react-lib | 23 | 2024-04-29T02:52:43.509168 | BSD-3-Clause | false | e6bf903d260e0f746cea044e9cde7935 |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\parser_utils.cpython-313.pyc | parser_utils.cpython-313.pyc | Other | 14,481 | 0.95 | 0.107914 | 0.007937 | vue-tools | 520 | 2023-12-24T04:56:44.140917 | BSD-3-Clause | false | 400c7d38fb74b73ce62b81d093ccdf79 |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\settings.cpython-313.pyc | settings.cpython-313.pyc | Other | 2,469 | 0.95 | 0 | 0 | vue-tools | 779 | 2024-11-09T03:01:01.345278 | GPL-3.0 | false | 8524fcde2afab83e9d5807f2ba84a65d |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 5,653 | 0.95 | 0.113636 | 0.025974 | node-utils | 377 | 2025-04-26T17:35:46.594968 | BSD-3-Clause | false | f1d4264de1ca9a37186b5328b2aa1b2c |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\_compatibility.cpython-313.pyc | _compatibility.cpython-313.pyc | Other | 1,873 | 0.8 | 0 | 0 | awesome-app | 47 | 2024-08-05T11:55:54.660093 | GPL-3.0 | false | f72ecd0d98dc5228651239b558e80cb2 |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,799 | 0.95 | 0.054054 | 0 | react-lib | 175 | 2024-04-15T02:50:55.244547 | GPL-3.0 | false | 1db2ca65fb34e8c6ab70853c1b081bcb |
\n\n | .venv\Lib\site-packages\jedi\__pycache__\__main__.cpython-313.pyc | __main__.cpython-313.pyc | Other | 3,342 | 0.95 | 0.03125 | 0 | python-kit | 727 | 2023-08-03T07:36:20.548610 | MIT | false | f46c1b623245b525cd8d9c4d1575b375 |
Main Authors\n------------\n\n- David Halter (@davidhalter) <davidhalter88@gmail.com>\n- Takafumi Arakaki (@tkf) <aka.tkf@gmail.com>\n\nCode Contributors\n-----------------\n\n- Danilo Bargen (@dbrgn) <mail@dbrgn.ch>\n- Laurens Van Houtven (@lvh) <_@lvh.cc>\n- Aldo Stracquadanio (@Astrac) <aldo.strac@gmail.com>\n- Jean-Louis Fuchs (@ganwell) <ganwell@fangorn.ch>\n- tek (@tek)\n- Yasha Borevich (@jjay) <j.borevich@gmail.com>\n- Aaron Griffin <aaronmgriffin@gmail.com>\n- andviro (@andviro)\n- Mike Gilbert (@floppym) <floppym@gentoo.org>\n- Aaron Meurer (@asmeurer) <asmeurer@gmail.com>\n- Lubos Trilety <ltrilety@redhat.com>\n- Akinori Hattori (@hattya) <hattya@gmail.com>\n- srusskih (@srusskih)\n- Steven Silvester (@blink1073)\n- Colin Duquesnoy (@ColinDuquesnoy) <colin.duquesnoy@gmail.com>\n- Jorgen Schaefer (@jorgenschaefer) <contact@jorgenschaefer.de>\n- Fredrik Bergroth (@fbergroth)\n- Mathias Fußenegger (@mfussenegger)\n- Syohei Yoshida (@syohex) <syohex@gmail.com>\n- ppalucky (@ppalucky)\n- immerrr (@immerrr) immerrr@gmail.com\n- Albertas Agejevas (@alga)\n- Savor d'Isavano (@KenetJervet) <newelevenken@163.com>\n- Phillip Berndt (@phillipberndt) <phillip.berndt@gmail.com>\n- Ian Lee (@IanLee1521) <IanLee1521@gmail.com>\n- Farkhad Khatamov (@hatamov) <comsgn@gmail.com>\n- Kevin Kelley (@kelleyk) <kelleyk@kelleyk.net>\n- Sid Shanker (@squidarth) <sid.p.shanker@gmail.com>\n- Reinoud Elhorst (@reinhrst)\n- Guido van Rossum (@gvanrossum) <guido@python.org>\n- Dmytro Sadovnychyi (@sadovnychyi) <jedi@dmit.ro>\n- Cristi Burcă (@scribu)\n- bstaint (@bstaint)\n- Mathias Rav (@Mortal) <rav@cs.au.dk>\n- Daniel Fiterman (@dfit99) <fitermandaniel2@gmail.com>\n- Simon Ruggier (@sruggier)\n- Élie Gouzien (@ElieGouzien)\n- Robin Roth (@robinro)\n- Malte Plath (@langsamer)\n- Anton Zub (@zabulazza)\n- Maksim Novikov (@m-novikov) <mnovikov.work@gmail.com>\n- Tobias Rzepka (@TobiasRzepka)\n- micbou (@micbou)\n- Dima Gerasimov (@karlicoss) <karlicoss@gmail.com>\n- Max Woerner Chase (@mwchase) <max.chase@gmail.com>\n- Johannes Maria Frank (@jmfrank63) <jmfrank63@gmail.com>\n- Shane Steinert-Threlkeld (@shanest) <ssshanest@gmail.com>\n- Tim Gates (@timgates42) <tim.gates@iress.com>\n- Lior Goldberg (@goldberglior)\n- Ryan Clary (@mrclary)\n- Max Mäusezahl (@mmaeusezahl) <maxmaeusezahl@googlemail.com>\n- Vladislav Serebrennikov (@endilll)\n- Andrii Kolomoiets (@muffinmad)\n- Leo Ryu (@Leo-Ryu)\n- Joseph Birkner (@josephbirkner)\n- Márcio Mazza (@marciomazza)\n- Martin Vielsmaier (@moser) <martin@vielsmaier.net>\n- TingJia Wu (@WutingjiaX) <wutingjia@bytedance.com>\n- Nguyễn Hồng Quân <ng.hong.quan@gmail.com>\n\nAnd a few more "anonymous" contributors.\n\nNote: (@user) means a github user name.\n | .venv\Lib\site-packages\jedi-0.19.2.dist-info\AUTHORS.txt | AUTHORS.txt | Other | 2,661 | 0.7 | 0 | 0 | vue-tools | 980 | 2023-10-09T04:03:18.511309 | Apache-2.0 | false | fe12301d76c8902aac9f932de6733393 |
pip\n | .venv\Lib\site-packages\jedi-0.19.2.dist-info\INSTALLER | INSTALLER | Other | 4 | 0.5 | 0 | 0 | react-lib | 354 | 2023-08-12T08:16:25.890715 | MIT | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
All contributions towards Jedi are MIT licensed.\n\n-------------------------------------------------------------------------------\nThe MIT License (MIT)\n\nCopyright (c) <2013> <David Halter and others, see AUTHORS.txt>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n | .venv\Lib\site-packages\jedi-0.19.2.dist-info\LICENSE.txt | LICENSE.txt | Other | 1,241 | 0.7 | 0 | 0 | react-lib | 734 | 2023-09-05T03:47:36.896357 | BSD-3-Clause | false | 5ed06eebfcb244cd66ebf6cef9c23ab4 |
Metadata-Version: 2.1\nName: jedi\nVersion: 0.19.2\nSummary: An autocompletion tool for Python that can be used for text editors.\nHome-page: https://github.com/davidhalter/jedi\nAuthor: David Halter\nAuthor-email: davidhalter88@gmail.com\nMaintainer: David Halter\nMaintainer-email: davidhalter88@gmail.com\nLicense: MIT\nProject-URL: Documentation, https://jedi.readthedocs.io/en/latest/\nKeywords: python completion refactoring vim\nPlatform: any\nClassifier: Development Status :: 4 - Beta\nClassifier: Environment :: Plugins\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Operating System :: OS Independent\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.6\nClassifier: Programming Language :: Python :: 3.7\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nClassifier: Topic :: Software Development :: Libraries :: Python Modules\nClassifier: Topic :: Text Editors :: Integrated Development Environments (IDE)\nClassifier: Topic :: Utilities\nRequires-Python: >=3.6\nRequires-Dist: parso (<0.9.0,>=0.8.4)\nProvides-Extra: docs\nRequires-Dist: Jinja2 (==2.11.3) ; extra == 'docs'\nRequires-Dist: MarkupSafe (==1.1.1) ; extra == 'docs'\nRequires-Dist: Pygments (==2.8.1) ; extra == 'docs'\nRequires-Dist: alabaster (==0.7.12) ; extra == 'docs'\nRequires-Dist: babel (==2.9.1) ; extra == 'docs'\nRequires-Dist: chardet (==4.0.0) ; extra == 'docs'\nRequires-Dist: commonmark (==0.8.1) ; extra == 'docs'\nRequires-Dist: docutils (==0.17.1) ; extra == 'docs'\nRequires-Dist: future (==0.18.2) ; extra == 'docs'\nRequires-Dist: idna (==2.10) ; extra == 'docs'\nRequires-Dist: imagesize (==1.2.0) ; extra == 'docs'\nRequires-Dist: mock (==1.0.1) ; extra == 'docs'\nRequires-Dist: packaging (==20.9) ; extra == 'docs'\nRequires-Dist: pyparsing (==2.4.7) ; extra == 'docs'\nRequires-Dist: pytz (==2021.1) ; extra == 'docs'\nRequires-Dist: readthedocs-sphinx-ext (==2.1.4) ; extra == 'docs'\nRequires-Dist: recommonmark (==0.5.0) ; extra == 'docs'\nRequires-Dist: requests (==2.25.1) ; extra == 'docs'\nRequires-Dist: six (==1.15.0) ; extra == 'docs'\nRequires-Dist: snowballstemmer (==2.1.0) ; extra == 'docs'\nRequires-Dist: sphinx-rtd-theme (==0.4.3) ; extra == 'docs'\nRequires-Dist: sphinx (==1.8.5) ; extra == 'docs'\nRequires-Dist: sphinxcontrib-serializinghtml (==1.1.4) ; extra == 'docs'\nRequires-Dist: sphinxcontrib-websupport (==1.2.4) ; extra == 'docs'\nRequires-Dist: urllib3 (==1.26.4) ; extra == 'docs'\nProvides-Extra: qa\nRequires-Dist: flake8 (==5.0.4) ; extra == 'qa'\nRequires-Dist: mypy (==0.971) ; extra == 'qa'\nRequires-Dist: types-setuptools (==67.2.0.1) ; extra == 'qa'\nProvides-Extra: testing\nRequires-Dist: Django ; extra == 'testing'\nRequires-Dist: attrs ; extra == 'testing'\nRequires-Dist: colorama ; extra == 'testing'\nRequires-Dist: docopt ; extra == 'testing'\nRequires-Dist: pytest (<9.0.0) ; extra == 'testing'\n\n####################################################################################\nJedi - an awesome autocompletion, static analysis and refactoring library for Python\n####################################################################################\n\n.. image:: http://isitmaintained.com/badge/open/davidhalter/jedi.svg\n :target: https://github.com/davidhalter/jedi/issues\n :alt: The percentage of open issues and pull requests\n\n.. image:: http://isitmaintained.com/badge/resolution/davidhalter/jedi.svg\n :target: https://github.com/davidhalter/jedi/issues\n :alt: The resolution time is the median time an issue or pull request stays open.\n\n.. image:: https://github.com/davidhalter/jedi/workflows/ci/badge.svg?branch=master\n :target: https://github.com/davidhalter/jedi/actions\n :alt: Tests\n\n.. image:: https://pepy.tech/badge/jedi\n :target: https://pepy.tech/project/jedi\n :alt: PyPI Downloads\n\n\nJedi is a static analysis tool for Python that is typically used in\nIDEs/editors plugins. Jedi has a focus on autocompletion and goto\nfunctionality. Other features include refactoring, code search and finding\nreferences.\n\nJedi has a simple API to work with. There is a reference implementation as a\n`VIM-Plugin <https://github.com/davidhalter/jedi-vim>`_. Autocompletion in your\nREPL is also possible, IPython uses it natively and for the CPython REPL you\ncan install it. Jedi is well tested and bugs should be rare.\n\nJedi can currently be used with the following editors/projects:\n\n- Vim (jedi-vim_, YouCompleteMe_, deoplete-jedi_, completor.vim_)\n- `Visual Studio Code`_ (via `Python Extension <https://marketplace.visualstudio.com/items?itemName=ms-python.python>`_)\n- Emacs (Jedi.el_, company-mode_, elpy_, anaconda-mode_, ycmd_)\n- Sublime Text (SublimeJEDI_ [ST2 + ST3], anaconda_ [only ST3])\n- TextMate_ (Not sure if it's actually working)\n- Kate_ version 4.13+ supports it natively, you have to enable it, though. [`see\n <https://projects.kde.org/projects/kde/applications/kate/repository/show?rev=KDE%2F4.13>`_]\n- Atom_ (autocomplete-python-jedi_)\n- `GNOME Builder`_ (with support for GObject Introspection)\n- Gedit (gedi_)\n- wdb_ - Web Debugger\n- `Eric IDE`_\n- `IPython 6.0.0+ <https://ipython.readthedocs.io/en/stable/whatsnew/version6.html>`_\n- `xonsh shell <https://xon.sh/contents.html>`_ has `jedi extension <https://xon.sh/xontribs.html#jedi>`_\n\nand many more!\n\nThere are a few language servers that use Jedi:\n\n- `jedi-language-server <https://github.com/pappasam/jedi-language-server>`_\n- `python-language-server <https://github.com/palantir/python-language-server>`_ (currently unmaintained)\n- `python-lsp-server <https://github.com/python-lsp/python-lsp-server>`_ (fork from python-language-server)\n- `anakin-language-server <https://github.com/muffinmad/anakin-language-server>`_\n\nHere are some pictures taken from jedi-vim_:\n\n.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_complete.png\n\nCompletion for almost anything:\n\n.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_function.png\n\nDocumentation:\n\n.. image:: https://github.com/davidhalter/jedi/raw/master/docs/_screenshots/screenshot_pydoc.png\n\n\nGet the latest version from `github <https://github.com/davidhalter/jedi>`_\n(master branch should always be kind of stable/working).\n\nDocs are available at `https://jedi.readthedocs.org/en/latest/\n<https://jedi.readthedocs.org/en/latest/>`_. Pull requests with enhancements\nand/or fixes are awesome and most welcome. Jedi uses `semantic versioning\n<https://semver.org/>`_.\n\nIf you want to stay **up-to-date** with releases, please **subscribe** to this\nmailing list: https://groups.google.com/g/jedi-announce. To subscribe you can\nsimply send an empty email to ``jedi-announce+subscribe@googlegroups.com``.\n\nIssues & Questions\n==================\n\nYou can file issues and questions in the `issue tracker\n<https://github.com/davidhalter/jedi/>`. Alternatively you can also ask on\n`Stack Overflow <https://stackoverflow.com/questions/tagged/python-jedi>`_ with\nthe label ``python-jedi``.\n\nInstallation\n============\n\n`Check out the docs <https://jedi.readthedocs.org/en/latest/docs/installation.html>`_.\n\nFeatures and Limitations\n========================\n\nJedi's features are listed here:\n`Features <https://jedi.readthedocs.org/en/latest/docs/features.html>`_.\n\nYou can run Jedi on Python 3.6+ but it should also\nunderstand code that is older than those versions. Additionally you should be\nable to use `Virtualenvs <https://jedi.readthedocs.org/en/latest/docs/api.html#environments>`_\nvery well.\n\nTips on how to use Jedi efficiently can be found `here\n<https://jedi.readthedocs.org/en/latest/docs/features.html#recipes>`_.\n\nAPI\n---\n\nYou can find a comprehensive documentation for the\n`API here <https://jedi.readthedocs.org/en/latest/docs/api.html>`_.\n\nAutocompletion / Goto / Documentation\n-------------------------------------\n\nThere are the following commands:\n\n- ``jedi.Script.goto``\n- ``jedi.Script.infer``\n- ``jedi.Script.help``\n- ``jedi.Script.complete``\n- ``jedi.Script.get_references``\n- ``jedi.Script.get_signatures``\n- ``jedi.Script.get_context``\n\nThe returned objects are very powerful and are really all you might need.\n\nAutocompletion in your REPL (IPython, etc.)\n-------------------------------------------\n\nJedi is a dependency of IPython. Autocompletion in IPython with Jedi is\ntherefore possible without additional configuration.\n\nHere is an `example video <https://vimeo.com/122332037>`_ how REPL completion\ncan look like.\nFor the ``python`` shell you can enable tab completion in a `REPL\n<https://jedi.readthedocs.org/en/latest/docs/usage.html#tab-completion-in-the-python-shell>`_.\n\nStatic Analysis\n---------------\n\nFor a lot of forms of static analysis, you can try to use\n``jedi.Script(...).get_names``. It will return a list of names that you can\nthen filter and work with. There is also a way to list the syntax errors in a\nfile: ``jedi.Script.get_syntax_errors``.\n\n\nRefactoring\n-----------\n\nJedi supports the following refactorings:\n\n- ``jedi.Script.inline``\n- ``jedi.Script.rename``\n- ``jedi.Script.extract_function``\n- ``jedi.Script.extract_variable``\n\nCode Search\n-----------\n\nThere is support for module search with ``jedi.Script.search``, and project\nsearch for ``jedi.Project.search``. The way to search is either by providing a\nname like ``foo`` or by using dotted syntax like ``foo.bar``. Additionally you\ncan provide the API type like ``class foo.bar.Bar``. There are also the\nfunctions ``jedi.Script.complete_search`` and ``jedi.Project.complete_search``.\n\nDevelopment\n===========\n\nThere's a pretty good and extensive `development documentation\n<https://jedi.readthedocs.org/en/latest/docs/development.html>`_.\n\nTesting\n=======\n\nThe test suite uses ``pytest``::\n\n pip install pytest\n\nIf you want to test only a specific Python version (e.g. Python 3.8), it is as\neasy as::\n\n python3.8 -m pytest\n\nFor more detailed information visit the `testing documentation\n<https://jedi.readthedocs.org/en/latest/docs/testing.html>`_.\n\nAcknowledgements\n================\n\nThanks a lot to all the\n`contributors <https://jedi.readthedocs.org/en/latest/docs/acknowledgements.html>`_!\n\n\n.. _jedi-vim: https://github.com/davidhalter/jedi-vim\n.. _youcompleteme: https://github.com/ycm-core/YouCompleteMe\n.. _deoplete-jedi: https://github.com/zchee/deoplete-jedi\n.. _completor.vim: https://github.com/maralla/completor.vim\n.. _Jedi.el: https://github.com/tkf/emacs-jedi\n.. _company-mode: https://github.com/syohex/emacs-company-jedi\n.. _elpy: https://github.com/jorgenschaefer/elpy\n.. _anaconda-mode: https://github.com/proofit404/anaconda-mode\n.. _ycmd: https://github.com/abingham/emacs-ycmd\n.. _sublimejedi: https://github.com/srusskih/SublimeJEDI\n.. _anaconda: https://github.com/DamnWidget/anaconda\n.. _wdb: https://github.com/Kozea/wdb\n.. _TextMate: https://github.com/lawrenceakka/python-jedi.tmbundle\n.. _Kate: https://kate-editor.org\n.. _Atom: https://atom.io/\n.. _autocomplete-python-jedi: https://atom.io/packages/autocomplete-python-jedi\n.. _GNOME Builder: https://wiki.gnome.org/Apps/Builder\n.. _Visual Studio Code: https://code.visualstudio.com/\n.. _gedi: https://github.com/isamert/gedi\n.. _Eric IDE: https://eric-ide.python-projects.org\n\n\n.. :changelog:\n\nChangelog\n---------\n\nUnreleased\n++++++++++\n\n0.19.2 (2024-11-10)\n+++++++++++++++++++\n\n- Python 3.13 support\n\n0.19.1 (2023-10-02)\n+++++++++++++++++++\n\n- Python 3.12 support (Thanks Peter!)\n\n0.19.0 (2023-07-29)\n+++++++++++++++++++\n\n- Python 3.11 support\n- Massive improvements in performance for ``Interpreter`` (e.g. IPython) users.\n This especially affects ``pandas`` users with large datasets.\n- Add ``jedi.settings.allow_unsafe_interpreter_executions`` to make it easier\n for IPython users to avoid unsafe executions.\n\n0.18.2 (2022-11-21)\n+++++++++++++++++++\n\n- Added dataclass-equivalent for attrs.define\n- Find fixtures from Pytest entrypoints; Examples of pytest plugins installed\n like this are pytest-django, pytest-sugar and Faker.\n- Fixed Project.search, when a venv was involved, which is why for example\n `:Pyimport django.db` did not work in some cases in jedi-vim.\n- And many smaller bugfixes\n\n0.18.1 (2021-11-17)\n+++++++++++++++++++\n\n- Implict namespaces are now a separate types in ``Name().type``\n- Python 3.10 support\n- Mostly bugfixes\n\n0.18.0 (2020-12-25)\n+++++++++++++++++++\n\n- Dropped Python 2 and Python 3.5\n- Using ``pathlib.Path()`` as an output instead of ``str`` in most places:\n - ``Project.path``\n - ``Script.path``\n - ``Definition.module_path``\n - ``Refactoring.get_renames``\n - ``Refactoring.get_changed_files``\n- Functions with ``@property`` now return ``property`` instead of ``function``\n in ``Name().type``\n- Started using annotations\n- Better support for the walrus operator\n- Project attributes are now read accessible\n- Removed all deprecations\n\nThis is likely going to be the last minor release before 1.0.\n\n0.17.2 (2020-07-17)\n+++++++++++++++++++\n\n- Added an option to pass environment variables to ``Environment``\n- ``Project(...).path`` exists now\n- Support for Python 3.9\n- A few bugfixes\n\nThis will be the last release that supports Python 2 and Python 3.5.\n``0.18.0`` will be Python 3.6+.\n\n0.17.1 (2020-06-20)\n+++++++++++++++++++\n\n- Django ``Model`` meta class support\n- Django Manager support (completion on Managers/QuerySets)\n- Added Django Stubs to Jedi, thanks to all contributors of the\n `Django Stubs <https://github.com/typeddjango/django-stubs>`_ project\n- Added ``SyntaxError.get_message``\n- Python 3.9 support\n- Bugfixes (mostly towards Generics)\n\n0.17.0 (2020-04-14)\n+++++++++++++++++++\n\n- Added ``Project`` support. This allows a user to specify which folders Jedi\n should work with.\n- Added support for Refactoring. The following refactorings have been\n implemented: ``Script.rename``, ``Script.inline``,\n ``Script.extract_variable`` and ``Script.extract_function``.\n- Added ``Script.get_syntax_errors`` to display syntax errors in the current\n script.\n- Added code search capabilities both for individual files and projects. The\n new functions are ``Project.search``, ``Project.complete_search``,\n ``Script.search`` and ``Script.complete_search``.\n- Added ``Script.help`` to make it easier to display a help window to people.\n Now returns pydoc information as well for Python keywords/operators. This\n means that on the class keyword it will now return the docstring of Python's\n builtin function ``help('class')``.\n- The API documentation is now way more readable and complete. Check it out\n under https://jedi.readthedocs.io. A lot of it has been rewritten.\n- Removed Python 3.4 support\n- Many bugfixes\n\nThis is likely going to be the last minor version that supports Python 2 and\nPython3.5. Bugfixes will be provided in 0.17.1+. The next minor/major version\nwill probably be Jedi 1.0.0.\n\n0.16.0 (2020-01-26)\n+++++++++++++++++++\n\n- **Added** ``Script.get_context`` to get information where you currently are.\n- Completions/type inference of **Pytest fixtures**.\n- Tensorflow, Numpy and Pandas completions should now be about **4-10x faster**\n after the first time they are used.\n- Dict key completions are working now. e.g. ``d = {1000: 3}; d[10`` will\n expand to ``1000``.\n- Completion for "proxies" works now. These are classes that have a\n ``__getattr__(self, name)`` method that does a ``return getattr(x, name)``.\n after loading them initially.\n- Goto on a function/attribute in a class now goes to the definition in its\n super class.\n- Big **Script API Changes**:\n - The line and column parameters of ``jedi.Script`` are now deprecated\n - ``completions`` deprecated, use ``complete`` instead\n - ``goto_assignments`` deprecated, use ``goto`` instead\n - ``goto_definitions`` deprecated, use ``infer`` instead\n - ``call_signatures`` deprecated, use ``get_signatures`` instead\n - ``usages`` deprecated, use ``get_references`` instead\n - ``jedi.names`` deprecated, use ``jedi.Script(...).get_names()``\n- ``BaseName.goto_assignments`` renamed to ``BaseName.goto``\n- Add follow_imports to ``Name.goto``. Now its signature matches\n ``Script.goto``.\n- **Python 2 support deprecated**. For this release it is best effort. Python 2\n has reached the end of its life and now it's just about a smooth transition.\n Bugs for Python 2 will not be fixed anymore and a third of the tests are\n already skipped.\n- Removed ``settings.no_completion_duplicates``. It wasn't tested and nobody\n was probably using it anyway.\n- Removed ``settings.use_filesystem_cache`` and\n ``settings.additional_dynamic_modules``, they have no usage anymore. Pretty\n much nobody was probably using them.\n\n0.15.2 (2019-12-20)\n+++++++++++++++++++\n\n- Signatures are now detected a lot better\n- Add fuzzy completions with ``Script(...).completions(fuzzy=True)``\n- Files bigger than one MB (about 20kLOC) get cropped to avoid getting\n stuck completely.\n- Many small Bugfixes\n- A big refactoring around contexts/values\n\n0.15.1 (2019-08-13)\n+++++++++++++++++++\n\n- Small bugfix and removal of a print statement\n\n0.15.0 (2019-08-11)\n+++++++++++++++++++\n\n- Added file path completions, there's a **new** ``Completion.type`` now:\n ``path``. Example: ``'/ho`` -> ``'/home/``\n- ``*args``/``**kwargs`` resolving. If possible Jedi replaces the parameters\n with the actual alternatives.\n- Better support for enums/dataclasses\n- When using Interpreter, properties are now executed, since a lot of people\n have complained about this. Discussion in #1299, #1347.\n\nNew APIs:\n\n- ``Name.get_signatures() -> List[Signature]``. Signatures are similar to\n ``CallSignature``. ``Name.params`` is therefore deprecated.\n- ``Signature.to_string()`` to format signatures.\n- ``Signature.params -> List[ParamName]``, ParamName has the\n following additional attributes ``infer_default()``, ``infer_annotation()``,\n ``to_string()``, and ``kind``.\n- ``Name.execute() -> List[Name]``, makes it possible to infer\n return values of functions.\n\n\n0.14.1 (2019-07-13)\n+++++++++++++++++++\n\n- CallSignature.index should now be working a lot better\n- A couple of smaller bugfixes\n\n0.14.0 (2019-06-20)\n+++++++++++++++++++\n\n- Added ``goto_*(prefer_stubs=True)`` as well as ``goto_*(prefer_stubs=True)``\n- Stubs are used now for type inference\n- Typeshed is used for better type inference\n- Reworked Name.full_name, should have more correct return values\n\n0.13.3 (2019-02-24)\n+++++++++++++++++++\n\n- Fixed an issue with embedded Python, see https://github.com/davidhalter/jedi-vim/issues/870\n\n0.13.2 (2018-12-15)\n+++++++++++++++++++\n\n- Fixed a bug that led to Jedi spawning a lot of subprocesses.\n\n0.13.1 (2018-10-02)\n+++++++++++++++++++\n\n- Bugfixes, because tensorflow completions were still slow.\n\n0.13.0 (2018-10-02)\n+++++++++++++++++++\n\n- A small release. Some bug fixes.\n- Remove Python 3.3 support. Python 3.3 support has been dropped by the Python\n foundation.\n- Default environments are now using the same Python version as the Python\n process. In 0.12.x, we used to load the latest Python version on the system.\n- Added ``include_builtins`` as a parameter to usages.\n- ``goto_assignments`` has a new ``follow_builtin_imports`` parameter that\n changes the previous behavior slightly.\n\n0.12.1 (2018-06-30)\n+++++++++++++++++++\n\n- This release forces you to upgrade parso. If you don't, nothing will work\n anymore. Otherwise changes should be limited to bug fixes. Unfortunately Jedi\n still uses a few internals of parso that make it hard to keep compatibility\n over multiple releases. Parso >=0.3.0 is going to be needed.\n\n0.12.0 (2018-04-15)\n+++++++++++++++++++\n\n- Virtualenv/Environment support\n- F-String Completion/Goto Support\n- Cannot crash with segfaults anymore\n- Cleaned up import logic\n- Understand async/await and autocomplete it (including async generators)\n- Better namespace completions\n- Passing tests for Windows (including CI for Windows)\n- Remove Python 2.6 support\n\n0.11.1 (2017-12-14)\n+++++++++++++++++++\n\n- Parso update - the caching layer was broken\n- Better usages - a lot of internal code was ripped out and improved.\n\n0.11.0 (2017-09-20)\n+++++++++++++++++++\n\n- Split Jedi's parser into a separate project called ``parso``.\n- Avoiding side effects in REPL completion.\n- Numpy docstring support should be much better.\n- Moved the `settings.*recursion*` away, they are no longer usable.\n\n0.10.2 (2017-04-05)\n+++++++++++++++++++\n\n- Python Packaging sucks. Some files were not included in 0.10.1.\n\n0.10.1 (2017-04-05)\n+++++++++++++++++++\n\n- Fixed a few very annoying bugs.\n- Prepared the parser to be factored out of Jedi.\n\n0.10.0 (2017-02-03)\n+++++++++++++++++++\n\n- Actual semantic completions for the complete Python syntax.\n- Basic type inference for ``yield from`` PEP 380.\n- PEP 484 support (most of the important features of it). Thanks Claude! (@reinhrst)\n- Added ``get_line_code`` to ``Name`` and ``Completion`` objects.\n- Completely rewritten the type inference engine.\n- A new and better parser for (fast) parsing diffs of Python code.\n\n0.9.0 (2015-04-10)\n++++++++++++++++++\n\n- The import logic has been rewritten to look more like Python's. There is now\n an ``InferState.modules`` import cache, which resembles ``sys.modules``.\n- Integrated the parser of 2to3. This will make refactoring possible. It will\n also be possible to check for error messages (like compiling an AST would give)\n in the future.\n- With the new parser, the type inference also completely changed. It's now\n simpler and more readable.\n- Completely rewritten REPL completion.\n- Added ``jedi.names``, a command to do static analysis. Thanks to that\n sourcegraph guys for sponsoring this!\n- Alpha version of the linter.\n\n\n0.8.1 (2014-07-23)\n+++++++++++++++++++\n\n- Bugfix release, the last release forgot to include files that improve\n autocompletion for builtin libraries. Fixed.\n\n0.8.0 (2014-05-05)\n+++++++++++++++++++\n\n- Memory Consumption for compiled modules (e.g. builtins, sys) has been reduced\n drastically. Loading times are down as well (it takes basically as long as an\n import).\n- REPL completion is starting to become usable.\n- Various small API changes. Generally this release focuses on stability and\n refactoring of internal APIs.\n- Introducing operator precedence, which makes calculating correct Array\n indices and ``__getattr__`` strings possible.\n\n0.7.0 (2013-08-09)\n++++++++++++++++++\n\n- Switched from LGPL to MIT license.\n- Added an Interpreter class to the API to make autocompletion in REPL\n possible.\n- Added autocompletion support for namespace packages.\n- Add sith.py, a new random testing method.\n\n0.6.0 (2013-05-14)\n++++++++++++++++++\n\n- Much faster parser with builtin part caching.\n- A test suite, thanks @tkf.\n\n0.5 versions (2012)\n+++++++++++++++++++\n\n- Initial development.\n\n\n | .venv\Lib\site-packages\jedi-0.19.2.dist-info\METADATA | METADATA | Other | 22,937 | 0.95 | 0.073836 | 0.004115 | awesome-app | 838 | 2025-06-27T00:22:49.327327 | GPL-3.0 | false | 4cd21001f3be2950f22b6897d053e088 |
jedi\n | .venv\Lib\site-packages\jedi-0.19.2.dist-info\top_level.txt | top_level.txt | Other | 5 | 0.5 | 0 | 0 | vue-tools | 767 | 2024-04-03T14:17:44.656626 | BSD-3-Clause | false | cda103fead1a3557f41eded906e38df2 |
Wheel-Version: 1.0\nGenerator: bdist_wheel (0.34.2)\nRoot-Is-Purelib: true\nTag: py2-none-any\nTag: py3-none-any\n\n | .venv\Lib\site-packages\jedi-0.19.2.dist-info\WHEEL | WHEEL | Other | 110 | 0.7 | 0 | 0 | vue-tools | 243 | 2025-03-12T11:40:26.536729 | Apache-2.0 | false | d2a91f104288b412dbc67b54de94e3ac |
import inspect\nimport typing as t\nfrom functools import WRAPPER_ASSIGNMENTS\nfrom functools import wraps\n\nfrom .utils import _PassArg\nfrom .utils import pass_eval_context\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n\nV = t.TypeVar("V")\n\n\ndef async_variant(normal_func): # type: ignore\n def decorator(async_func): # type: ignore\n pass_arg = _PassArg.from_obj(normal_func)\n need_eval_context = pass_arg is None\n\n if pass_arg is _PassArg.environment:\n\n def is_async(args: t.Any) -> bool:\n return t.cast(bool, args[0].is_async)\n\n else:\n\n def is_async(args: t.Any) -> bool:\n return t.cast(bool, args[0].environment.is_async)\n\n # Take the doc and annotations from the sync function, but the\n # name from the async function. Pallets-Sphinx-Themes\n # build_function_directive expects __wrapped__ to point to the\n # sync function.\n async_func_attrs = ("__module__", "__name__", "__qualname__")\n normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs))\n\n @wraps(normal_func, assigned=normal_func_attrs)\n @wraps(async_func, assigned=async_func_attrs, updated=())\n def wrapper(*args, **kwargs): # type: ignore\n b = is_async(args)\n\n if need_eval_context:\n args = args[1:]\n\n if b:\n return async_func(*args, **kwargs)\n\n return normal_func(*args, **kwargs)\n\n if need_eval_context:\n wrapper = pass_eval_context(wrapper)\n\n wrapper.jinja_async_variant = True # type: ignore[attr-defined]\n return wrapper\n\n return decorator\n\n\n_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)}\n\n\nasync def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":\n # Avoid a costly call to isawaitable\n if type(value) in _common_primitives:\n return t.cast("V", value)\n\n if inspect.isawaitable(value):\n return await t.cast("t.Awaitable[V]", value)\n\n return value\n\n\nclass _IteratorToAsyncIterator(t.Generic[V]):\n def __init__(self, iterator: "t.Iterator[V]"):\n self._iterator = iterator\n\n def __aiter__(self) -> "te.Self":\n return self\n\n async def __anext__(self) -> V:\n try:\n return next(self._iterator)\n except StopIteration as e:\n raise StopAsyncIteration(e.value) from e\n\n\ndef auto_aiter(\n iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",\n) -> "t.AsyncIterator[V]":\n if hasattr(iterable, "__aiter__"):\n return iterable.__aiter__()\n else:\n return _IteratorToAsyncIterator(iter(iterable))\n\n\nasync def auto_to_list(\n value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",\n) -> t.List["V"]:\n return [x async for x in auto_aiter(value)]\n | .venv\Lib\site-packages\jinja2\async_utils.py | async_utils.py | Python | 2,834 | 0.95 | 0.252525 | 0.073529 | react-lib | 608 | 2025-04-23T00:52:27.160366 | GPL-3.0 | false | cef0370ac6003913b74d9513d9f8d99e |
"""Compiles nodes from the parser into Python code."""\n\nimport typing as t\nfrom contextlib import contextmanager\nfrom functools import update_wrapper\nfrom io import StringIO\nfrom itertools import chain\nfrom keyword import iskeyword as is_python_keyword\n\nfrom markupsafe import escape\nfrom markupsafe import Markup\n\nfrom . import nodes\nfrom .exceptions import TemplateAssertionError\nfrom .idtracking import Symbols\nfrom .idtracking import VAR_LOAD_ALIAS\nfrom .idtracking import VAR_LOAD_PARAMETER\nfrom .idtracking import VAR_LOAD_RESOLVE\nfrom .idtracking import VAR_LOAD_UNDEFINED\nfrom .nodes import EvalContext\nfrom .optimizer import Optimizer\nfrom .utils import _PassArg\nfrom .utils import concat\nfrom .visitor import NodeVisitor\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n\n from .environment import Environment\n\nF = t.TypeVar("F", bound=t.Callable[..., t.Any])\n\noperators = {\n "eq": "==",\n "ne": "!=",\n "gt": ">",\n "gteq": ">=",\n "lt": "<",\n "lteq": "<=",\n "in": "in",\n "notin": "not in",\n}\n\n\ndef optimizeconst(f: F) -> F:\n def new_func(\n self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any\n ) -> t.Any:\n # Only optimize if the frame is not volatile\n if self.optimizer is not None and not frame.eval_ctx.volatile:\n new_node = self.optimizer.visit(node, frame.eval_ctx)\n\n if new_node != node:\n return self.visit(new_node, frame)\n\n return f(self, node, frame, **kwargs)\n\n return update_wrapper(new_func, f) # type: ignore[return-value]\n\n\ndef _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:\n @optimizeconst\n def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:\n if (\n self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore\n ):\n self.write(f"environment.call_binop(context, {op!r}, ")\n self.visit(node.left, frame)\n self.write(", ")\n self.visit(node.right, frame)\n else:\n self.write("(")\n self.visit(node.left, frame)\n self.write(f" {op} ")\n self.visit(node.right, frame)\n\n self.write(")")\n\n return visitor\n\n\ndef _make_unop(\n op: str,\n) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:\n @optimizeconst\n def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:\n if (\n self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore\n ):\n self.write(f"environment.call_unop(context, {op!r}, ")\n self.visit(node.node, frame)\n else:\n self.write("(" + op)\n self.visit(node.node, frame)\n\n self.write(")")\n\n return visitor\n\n\ndef generate(\n node: nodes.Template,\n environment: "Environment",\n name: t.Optional[str],\n filename: t.Optional[str],\n stream: t.Optional[t.TextIO] = None,\n defer_init: bool = False,\n optimized: bool = True,\n) -> t.Optional[str]:\n """Generate the python source for a node tree."""\n if not isinstance(node, nodes.Template):\n raise TypeError("Can't compile non template nodes")\n\n generator = environment.code_generator_class(\n environment, name, filename, stream, defer_init, optimized\n )\n generator.visit(node)\n\n if stream is None:\n return generator.stream.getvalue() # type: ignore\n\n return None\n\n\ndef has_safe_repr(value: t.Any) -> bool:\n """Does the node have a safe representation?"""\n if value is None or value is NotImplemented or value is Ellipsis:\n return True\n\n if type(value) in {bool, int, float, complex, range, str, Markup}:\n return True\n\n if type(value) in {tuple, list, set, frozenset}:\n return all(has_safe_repr(v) for v in value)\n\n if type(value) is dict: # noqa E721\n return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())\n\n return False\n\n\ndef find_undeclared(\n nodes: t.Iterable[nodes.Node], names: t.Iterable[str]\n) -> t.Set[str]:\n """Check if the names passed are accessed undeclared. The return value\n is a set of all the undeclared names from the sequence of names found.\n """\n visitor = UndeclaredNameVisitor(names)\n try:\n for node in nodes:\n visitor.visit(node)\n except VisitorExit:\n pass\n return visitor.undeclared\n\n\nclass MacroRef:\n def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None:\n self.node = node\n self.accesses_caller = False\n self.accesses_kwargs = False\n self.accesses_varargs = False\n\n\nclass Frame:\n """Holds compile time information for us."""\n\n def __init__(\n self,\n eval_ctx: EvalContext,\n parent: t.Optional["Frame"] = None,\n level: t.Optional[int] = None,\n ) -> None:\n self.eval_ctx = eval_ctx\n\n # the parent of this frame\n self.parent = parent\n\n if parent is None:\n self.symbols = Symbols(level=level)\n\n # in some dynamic inheritance situations the compiler needs to add\n # write tests around output statements.\n self.require_output_check = False\n\n # inside some tags we are using a buffer rather than yield statements.\n # this for example affects {% filter %} or {% macro %}. If a frame\n # is buffered this variable points to the name of the list used as\n # buffer.\n self.buffer: t.Optional[str] = None\n\n # the name of the block we're in, otherwise None.\n self.block: t.Optional[str] = None\n\n else:\n self.symbols = Symbols(parent.symbols, level=level)\n self.require_output_check = parent.require_output_check\n self.buffer = parent.buffer\n self.block = parent.block\n\n # a toplevel frame is the root + soft frames such as if conditions.\n self.toplevel = False\n\n # the root frame is basically just the outermost frame, so no if\n # conditions. This information is used to optimize inheritance\n # situations.\n self.rootlevel = False\n\n # variables set inside of loops and blocks should not affect outer frames,\n # but they still needs to be kept track of as part of the active context.\n self.loop_frame = False\n self.block_frame = False\n\n # track whether the frame is being used in an if-statement or conditional\n # expression as it determines which errors should be raised during runtime\n # or compile time.\n self.soft_frame = False\n\n def copy(self) -> "te.Self":\n """Create a copy of the current one."""\n rv = object.__new__(self.__class__)\n rv.__dict__.update(self.__dict__)\n rv.symbols = self.symbols.copy()\n return rv\n\n def inner(self, isolated: bool = False) -> "Frame":\n """Return an inner frame."""\n if isolated:\n return Frame(self.eval_ctx, level=self.symbols.level + 1)\n return Frame(self.eval_ctx, self)\n\n def soft(self) -> "te.Self":\n """Return a soft frame. A soft frame may not be modified as\n standalone thing as it shares the resources with the frame it\n was created of, but it's not a rootlevel frame any longer.\n\n This is only used to implement if-statements and conditional\n expressions.\n """\n rv = self.copy()\n rv.rootlevel = False\n rv.soft_frame = True\n return rv\n\n __copy__ = copy\n\n\nclass VisitorExit(RuntimeError):\n """Exception used by the `UndeclaredNameVisitor` to signal a stop."""\n\n\nclass DependencyFinderVisitor(NodeVisitor):\n """A visitor that collects filter and test calls."""\n\n def __init__(self) -> None:\n self.filters: t.Set[str] = set()\n self.tests: t.Set[str] = set()\n\n def visit_Filter(self, node: nodes.Filter) -> None:\n self.generic_visit(node)\n self.filters.add(node.name)\n\n def visit_Test(self, node: nodes.Test) -> None:\n self.generic_visit(node)\n self.tests.add(node.name)\n\n def visit_Block(self, node: nodes.Block) -> None:\n """Stop visiting at blocks."""\n\n\nclass UndeclaredNameVisitor(NodeVisitor):\n """A visitor that checks if a name is accessed without being\n declared. This is different from the frame visitor as it will\n not stop at closure frames.\n """\n\n def __init__(self, names: t.Iterable[str]) -> None:\n self.names = set(names)\n self.undeclared: t.Set[str] = set()\n\n def visit_Name(self, node: nodes.Name) -> None:\n if node.ctx == "load" and node.name in self.names:\n self.undeclared.add(node.name)\n if self.undeclared == self.names:\n raise VisitorExit()\n else:\n self.names.discard(node.name)\n\n def visit_Block(self, node: nodes.Block) -> None:\n """Stop visiting a blocks."""\n\n\nclass CompilerExit(Exception):\n """Raised if the compiler encountered a situation where it just\n doesn't make sense to further process the code. Any block that\n raises such an exception is not further processed.\n """\n\n\nclass CodeGenerator(NodeVisitor):\n def __init__(\n self,\n environment: "Environment",\n name: t.Optional[str],\n filename: t.Optional[str],\n stream: t.Optional[t.TextIO] = None,\n defer_init: bool = False,\n optimized: bool = True,\n ) -> None:\n if stream is None:\n stream = StringIO()\n self.environment = environment\n self.name = name\n self.filename = filename\n self.stream = stream\n self.created_block_context = False\n self.defer_init = defer_init\n self.optimizer: t.Optional[Optimizer] = None\n\n if optimized:\n self.optimizer = Optimizer(environment)\n\n # aliases for imports\n self.import_aliases: t.Dict[str, str] = {}\n\n # a registry for all blocks. Because blocks are moved out\n # into the global python scope they are registered here\n self.blocks: t.Dict[str, nodes.Block] = {}\n\n # the number of extends statements so far\n self.extends_so_far = 0\n\n # some templates have a rootlevel extends. In this case we\n # can safely assume that we're a child template and do some\n # more optimizations.\n self.has_known_extends = False\n\n # the current line number\n self.code_lineno = 1\n\n # registry of all filters and tests (global, not block local)\n self.tests: t.Dict[str, str] = {}\n self.filters: t.Dict[str, str] = {}\n\n # the debug information\n self.debug_info: t.List[t.Tuple[int, int]] = []\n self._write_debug_info: t.Optional[int] = None\n\n # the number of new lines before the next write()\n self._new_lines = 0\n\n # the line number of the last written statement\n self._last_line = 0\n\n # true if nothing was written so far.\n self._first_write = True\n\n # used by the `temporary_identifier` method to get new\n # unique, temporary identifier\n self._last_identifier = 0\n\n # the current indentation\n self._indentation = 0\n\n # Tracks toplevel assignments\n self._assign_stack: t.List[t.Set[str]] = []\n\n # Tracks parameter definition blocks\n self._param_def_block: t.List[t.Set[str]] = []\n\n # Tracks the current context.\n self._context_reference_stack = ["context"]\n\n @property\n def optimized(self) -> bool:\n return self.optimizer is not None\n\n # -- Various compilation helpers\n\n def fail(self, msg: str, lineno: int) -> "te.NoReturn":\n """Fail with a :exc:`TemplateAssertionError`."""\n raise TemplateAssertionError(msg, lineno, self.name, self.filename)\n\n def temporary_identifier(self) -> str:\n """Get a new unique identifier."""\n self._last_identifier += 1\n return f"t_{self._last_identifier}"\n\n def buffer(self, frame: Frame) -> None:\n """Enable buffering for the frame from that point onwards."""\n frame.buffer = self.temporary_identifier()\n self.writeline(f"{frame.buffer} = []")\n\n def return_buffer_contents(\n self, frame: Frame, force_unescaped: bool = False\n ) -> None:\n """Return the buffer contents of the frame."""\n if not force_unescaped:\n if frame.eval_ctx.volatile:\n self.writeline("if context.eval_ctx.autoescape:")\n self.indent()\n self.writeline(f"return Markup(concat({frame.buffer}))")\n self.outdent()\n self.writeline("else:")\n self.indent()\n self.writeline(f"return concat({frame.buffer})")\n self.outdent()\n return\n elif frame.eval_ctx.autoescape:\n self.writeline(f"return Markup(concat({frame.buffer}))")\n return\n self.writeline(f"return concat({frame.buffer})")\n\n def indent(self) -> None:\n """Indent by one."""\n self._indentation += 1\n\n def outdent(self, step: int = 1) -> None:\n """Outdent by step."""\n self._indentation -= step\n\n def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None:\n """Yield or write into the frame buffer."""\n if frame.buffer is None:\n self.writeline("yield ", node)\n else:\n self.writeline(f"{frame.buffer}.append(", node)\n\n def end_write(self, frame: Frame) -> None:\n """End the writing process started by `start_write`."""\n if frame.buffer is not None:\n self.write(")")\n\n def simple_write(\n self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None\n ) -> None:\n """Simple shortcut for start_write + write + end_write."""\n self.start_write(frame, node)\n self.write(s)\n self.end_write(frame)\n\n def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None:\n """Visit a list of nodes as block in a frame. If the current frame\n is no buffer a dummy ``if 0: yield None`` is written automatically.\n """\n try:\n self.writeline("pass")\n for node in nodes:\n self.visit(node, frame)\n except CompilerExit:\n pass\n\n def write(self, x: str) -> None:\n """Write a string into the output stream."""\n if self._new_lines:\n if not self._first_write:\n self.stream.write("\n" * self._new_lines)\n self.code_lineno += self._new_lines\n if self._write_debug_info is not None:\n self.debug_info.append((self._write_debug_info, self.code_lineno))\n self._write_debug_info = None\n self._first_write = False\n self.stream.write(" " * self._indentation)\n self._new_lines = 0\n self.stream.write(x)\n\n def writeline(\n self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0\n ) -> None:\n """Combination of newline and write."""\n self.newline(node, extra)\n self.write(x)\n\n def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None:\n """Add one or more newlines before the next write."""\n self._new_lines = max(self._new_lines, 1 + extra)\n if node is not None and node.lineno != self._last_line:\n self._write_debug_info = node.lineno\n self._last_line = node.lineno\n\n def signature(\n self,\n node: t.Union[nodes.Call, nodes.Filter, nodes.Test],\n frame: Frame,\n extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None,\n ) -> None:\n """Writes a function call to the stream for the current node.\n A leading comma is added automatically. The extra keyword\n arguments may not include python keywords otherwise a syntax\n error could occur. The extra keyword arguments should be given\n as python dict.\n """\n # if any of the given keyword arguments is a python keyword\n # we have to make sure that no invalid call is created.\n kwarg_workaround = any(\n is_python_keyword(t.cast(str, k))\n for k in chain((x.key for x in node.kwargs), extra_kwargs or ())\n )\n\n for arg in node.args:\n self.write(", ")\n self.visit(arg, frame)\n\n if not kwarg_workaround:\n for kwarg in node.kwargs:\n self.write(", ")\n self.visit(kwarg, frame)\n if extra_kwargs is not None:\n for key, value in extra_kwargs.items():\n self.write(f", {key}={value}")\n if node.dyn_args:\n self.write(", *")\n self.visit(node.dyn_args, frame)\n\n if kwarg_workaround:\n if node.dyn_kwargs is not None:\n self.write(", **dict({")\n else:\n self.write(", **{")\n for kwarg in node.kwargs:\n self.write(f"{kwarg.key!r}: ")\n self.visit(kwarg.value, frame)\n self.write(", ")\n if extra_kwargs is not None:\n for key, value in extra_kwargs.items():\n self.write(f"{key!r}: {value}, ")\n if node.dyn_kwargs is not None:\n self.write("}, **")\n self.visit(node.dyn_kwargs, frame)\n self.write(")")\n else:\n self.write("}")\n\n elif node.dyn_kwargs is not None:\n self.write(", **")\n self.visit(node.dyn_kwargs, frame)\n\n def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None:\n """Find all filter and test names used in the template and\n assign them to variables in the compiled namespace. Checking\n that the names are registered with the environment is done when\n compiling the Filter and Test nodes. If the node is in an If or\n CondExpr node, the check is done at runtime instead.\n\n .. versionchanged:: 3.0\n Filters and tests in If and CondExpr nodes are checked at\n runtime instead of compile time.\n """\n visitor = DependencyFinderVisitor()\n\n for node in nodes:\n visitor.visit(node)\n\n for id_map, names, dependency in (\n (self.filters, visitor.filters, "filters"),\n (\n self.tests,\n visitor.tests,\n "tests",\n ),\n ):\n for name in sorted(names):\n if name not in id_map:\n id_map[name] = self.temporary_identifier()\n\n # add check during runtime that dependencies used inside of executed\n # blocks are defined, as this step may be skipped during compile time\n self.writeline("try:")\n self.indent()\n self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]")\n self.outdent()\n self.writeline("except KeyError:")\n self.indent()\n self.writeline("@internalcode")\n self.writeline(f"def {id_map[name]}(*unused):")\n self.indent()\n self.writeline(\n f'raise TemplateRuntimeError("No {dependency[:-1]}'\n f' named {name!r} found.")'\n )\n self.outdent()\n self.outdent()\n\n def enter_frame(self, frame: Frame) -> None:\n undefs = []\n for target, (action, param) in frame.symbols.loads.items():\n if action == VAR_LOAD_PARAMETER:\n pass\n elif action == VAR_LOAD_RESOLVE:\n self.writeline(f"{target} = {self.get_resolve_func()}({param!r})")\n elif action == VAR_LOAD_ALIAS:\n self.writeline(f"{target} = {param}")\n elif action == VAR_LOAD_UNDEFINED:\n undefs.append(target)\n else:\n raise NotImplementedError("unknown load instruction")\n if undefs:\n self.writeline(f"{' = '.join(undefs)} = missing")\n\n def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None:\n if not with_python_scope:\n undefs = []\n for target in frame.symbols.loads:\n undefs.append(target)\n if undefs:\n self.writeline(f"{' = '.join(undefs)} = missing")\n\n def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str:\n return async_value if self.environment.is_async else sync_value\n\n def func(self, name: str) -> str:\n return f"{self.choose_async()}def {name}"\n\n def macro_body(\n self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame\n ) -> t.Tuple[Frame, MacroRef]:\n """Dump the function def of a macro or call block."""\n frame = frame.inner()\n frame.symbols.analyze_node(node)\n macro_ref = MacroRef(node)\n\n explicit_caller = None\n skip_special_params = set()\n args = []\n\n for idx, arg in enumerate(node.args):\n if arg.name == "caller":\n explicit_caller = idx\n if arg.name in ("kwargs", "varargs"):\n skip_special_params.add(arg.name)\n args.append(frame.symbols.ref(arg.name))\n\n undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))\n\n if "caller" in undeclared:\n # In older Jinja versions there was a bug that allowed caller\n # to retain the special behavior even if it was mentioned in\n # the argument list. However thankfully this was only really\n # working if it was the last argument. So we are explicitly\n # checking this now and error out if it is anywhere else in\n # the argument list.\n if explicit_caller is not None:\n try:\n node.defaults[explicit_caller - len(node.args)]\n except IndexError:\n self.fail(\n "When defining macros or call blocks the "\n 'special "caller" argument must be omitted '\n "or be given a default.",\n node.lineno,\n )\n else:\n args.append(frame.symbols.declare_parameter("caller"))\n macro_ref.accesses_caller = True\n if "kwargs" in undeclared and "kwargs" not in skip_special_params:\n args.append(frame.symbols.declare_parameter("kwargs"))\n macro_ref.accesses_kwargs = True\n if "varargs" in undeclared and "varargs" not in skip_special_params:\n args.append(frame.symbols.declare_parameter("varargs"))\n macro_ref.accesses_varargs = True\n\n # macros are delayed, they never require output checks\n frame.require_output_check = False\n frame.symbols.analyze_node(node)\n self.writeline(f"{self.func('macro')}({', '.join(args)}):", node)\n self.indent()\n\n self.buffer(frame)\n self.enter_frame(frame)\n\n self.push_parameter_definitions(frame)\n for idx, arg in enumerate(node.args):\n ref = frame.symbols.ref(arg.name)\n self.writeline(f"if {ref} is missing:")\n self.indent()\n try:\n default = node.defaults[idx - len(node.args)]\n except IndexError:\n self.writeline(\n f'{ref} = undefined("parameter {arg.name!r} was not provided",'\n f" name={arg.name!r})"\n )\n else:\n self.writeline(f"{ref} = ")\n self.visit(default, frame)\n self.mark_parameter_stored(ref)\n self.outdent()\n self.pop_parameter_definitions()\n\n self.blockvisit(node.body, frame)\n self.return_buffer_contents(frame, force_unescaped=True)\n self.leave_frame(frame, with_python_scope=True)\n self.outdent()\n\n return frame, macro_ref\n\n def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None:\n """Dump the macro definition for the def created by macro_body."""\n arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)\n name = getattr(macro_ref.node, "name", None)\n if len(macro_ref.node.args) == 1:\n arg_tuple += ","\n self.write(\n f"Macro(environment, macro, {name!r}, ({arg_tuple}),"\n f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"\n f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"\n )\n\n def position(self, node: nodes.Node) -> str:\n """Return a human readable position for the node."""\n rv = f"line {node.lineno}"\n if self.name is not None:\n rv = f"{rv} in {self.name!r}"\n return rv\n\n def dump_local_context(self, frame: Frame) -> str:\n items_kv = ", ".join(\n f"{name!r}: {target}"\n for name, target in frame.symbols.dump_stores().items()\n )\n return f"{{{items_kv}}}"\n\n def write_commons(self) -> None:\n """Writes a common preamble that is used by root and block functions.\n Primarily this sets up common local helpers and enforces a generator\n through a dead branch.\n """\n self.writeline("resolve = context.resolve_or_missing")\n self.writeline("undefined = environment.undefined")\n self.writeline("concat = environment.concat")\n # always use the standard Undefined class for the implicit else of\n # conditional expressions\n self.writeline("cond_expr_undefined = Undefined")\n self.writeline("if 0: yield None")\n\n def push_parameter_definitions(self, frame: Frame) -> None:\n """Pushes all parameter targets from the given frame into a local\n stack that permits tracking of yet to be assigned parameters. In\n particular this enables the optimization from `visit_Name` to skip\n undefined expressions for parameters in macros as macros can reference\n otherwise unbound parameters.\n """\n self._param_def_block.append(frame.symbols.dump_param_targets())\n\n def pop_parameter_definitions(self) -> None:\n """Pops the current parameter definitions set."""\n self._param_def_block.pop()\n\n def mark_parameter_stored(self, target: str) -> None:\n """Marks a parameter in the current parameter definitions as stored.\n This will skip the enforced undefined checks.\n """\n if self._param_def_block:\n self._param_def_block[-1].discard(target)\n\n def push_context_reference(self, target: str) -> None:\n self._context_reference_stack.append(target)\n\n def pop_context_reference(self) -> None:\n self._context_reference_stack.pop()\n\n def get_context_ref(self) -> str:\n return self._context_reference_stack[-1]\n\n def get_resolve_func(self) -> str:\n target = self._context_reference_stack[-1]\n if target == "context":\n return "resolve"\n return f"{target}.resolve"\n\n def derive_context(self, frame: Frame) -> str:\n return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"\n\n def parameter_is_undeclared(self, target: str) -> bool:\n """Checks if a given target is an undeclared parameter."""\n if not self._param_def_block:\n return False\n return target in self._param_def_block[-1]\n\n def push_assign_tracking(self) -> None:\n """Pushes a new layer for assignment tracking."""\n self._assign_stack.append(set())\n\n def pop_assign_tracking(self, frame: Frame) -> None:\n """Pops the topmost level for assignment tracking and updates the\n context variables if necessary.\n """\n vars = self._assign_stack.pop()\n if (\n not frame.block_frame\n and not frame.loop_frame\n and not frame.toplevel\n or not vars\n ):\n return\n public_names = [x for x in vars if x[:1] != "_"]\n if len(vars) == 1:\n name = next(iter(vars))\n ref = frame.symbols.ref(name)\n if frame.loop_frame:\n self.writeline(f"_loop_vars[{name!r}] = {ref}")\n return\n if frame.block_frame:\n self.writeline(f"_block_vars[{name!r}] = {ref}")\n return\n self.writeline(f"context.vars[{name!r}] = {ref}")\n else:\n if frame.loop_frame:\n self.writeline("_loop_vars.update({")\n elif frame.block_frame:\n self.writeline("_block_vars.update({")\n else:\n self.writeline("context.vars.update({")\n for idx, name in enumerate(sorted(vars)):\n if idx:\n self.write(", ")\n ref = frame.symbols.ref(name)\n self.write(f"{name!r}: {ref}")\n self.write("})")\n if not frame.block_frame and not frame.loop_frame and public_names:\n if len(public_names) == 1:\n self.writeline(f"context.exported_vars.add({public_names[0]!r})")\n else:\n names_str = ", ".join(map(repr, sorted(public_names)))\n self.writeline(f"context.exported_vars.update(({names_str}))")\n\n # -- Statement Visitors\n\n def visit_Template(\n self, node: nodes.Template, frame: t.Optional[Frame] = None\n ) -> None:\n assert frame is None, "no root frame allowed"\n eval_ctx = EvalContext(self.environment, self.name)\n\n from .runtime import async_exported\n from .runtime import exported\n\n if self.environment.is_async:\n exported_names = sorted(exported + async_exported)\n else:\n exported_names = sorted(exported)\n\n self.writeline("from jinja2.runtime import " + ", ".join(exported_names))\n\n # if we want a deferred initialization we cannot move the\n # environment into a local name\n envenv = "" if self.defer_init else ", environment=environment"\n\n # do we have an extends tag at all? If not, we can save some\n # overhead by just not processing any inheritance code.\n have_extends = node.find(nodes.Extends) is not None\n\n # find all blocks\n for block in node.find_all(nodes.Block):\n if block.name in self.blocks:\n self.fail(f"block {block.name!r} defined twice", block.lineno)\n self.blocks[block.name] = block\n\n # find all imports and import them\n for import_ in node.find_all(nodes.ImportedName):\n if import_.importname not in self.import_aliases:\n imp = import_.importname\n self.import_aliases[imp] = alias = self.temporary_identifier()\n if "." in imp:\n module, obj = imp.rsplit(".", 1)\n self.writeline(f"from {module} import {obj} as {alias}")\n else:\n self.writeline(f"import {imp} as {alias}")\n\n # add the load name\n self.writeline(f"name = {self.name!r}")\n\n # generate the root render function.\n self.writeline(\n f"{self.func('root')}(context, missing=missing{envenv}):", extra=1\n )\n self.indent()\n self.write_commons()\n\n # process the root\n frame = Frame(eval_ctx)\n if "self" in find_undeclared(node.body, ("self",)):\n ref = frame.symbols.declare_parameter("self")\n self.writeline(f"{ref} = TemplateReference(context)")\n frame.symbols.analyze_node(node)\n frame.toplevel = frame.rootlevel = True\n frame.require_output_check = have_extends and not self.has_known_extends\n if have_extends:\n self.writeline("parent_template = None")\n self.enter_frame(frame)\n self.pull_dependencies(node.body)\n self.blockvisit(node.body, frame)\n self.leave_frame(frame, with_python_scope=True)\n self.outdent()\n\n # make sure that the parent root is called.\n if have_extends:\n if not self.has_known_extends:\n self.indent()\n self.writeline("if parent_template is not None:")\n self.indent()\n if not self.environment.is_async:\n self.writeline("yield from parent_template.root_render_func(context)")\n else:\n self.writeline("agen = parent_template.root_render_func(context)")\n self.writeline("try:")\n self.indent()\n self.writeline("async for event in agen:")\n self.indent()\n self.writeline("yield event")\n self.outdent()\n self.outdent()\n self.writeline("finally: await agen.aclose()")\n self.outdent(1 + (not self.has_known_extends))\n\n # at this point we now have the blocks collected and can visit them too.\n for name, block in self.blocks.items():\n self.writeline(\n f"{self.func('block_' + name)}(context, missing=missing{envenv}):",\n block,\n 1,\n )\n self.indent()\n self.write_commons()\n # It's important that we do not make this frame a child of the\n # toplevel template. This would cause a variety of\n # interesting issues with identifier tracking.\n block_frame = Frame(eval_ctx)\n block_frame.block_frame = True\n undeclared = find_undeclared(block.body, ("self", "super"))\n if "self" in undeclared:\n ref = block_frame.symbols.declare_parameter("self")\n self.writeline(f"{ref} = TemplateReference(context)")\n if "super" in undeclared:\n ref = block_frame.symbols.declare_parameter("super")\n self.writeline(f"{ref} = context.super({name!r}, block_{name})")\n block_frame.symbols.analyze_node(block)\n block_frame.block = name\n self.writeline("_block_vars = {}")\n self.enter_frame(block_frame)\n self.pull_dependencies(block.body)\n self.blockvisit(block.body, block_frame)\n self.leave_frame(block_frame, with_python_scope=True)\n self.outdent()\n\n blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks)\n self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)\n debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)\n self.writeline(f"debug_info = {debug_kv_str!r}")\n\n def visit_Block(self, node: nodes.Block, frame: Frame) -> None:\n """Call a block and register it for the template."""\n level = 0\n if frame.toplevel:\n # if we know that we are a child template, there is no need to\n # check if we are one\n if self.has_known_extends:\n return\n if self.extends_so_far > 0:\n self.writeline("if parent_template is None:")\n self.indent()\n level += 1\n\n if node.scoped:\n context = self.derive_context(frame)\n else:\n context = self.get_context_ref()\n\n if node.required:\n self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node)\n self.indent()\n self.writeline(\n f'raise TemplateRuntimeError("Required block {node.name!r} not found")',\n node,\n )\n self.outdent()\n\n if not self.environment.is_async and frame.buffer is None:\n self.writeline(\n f"yield from context.blocks[{node.name!r}][0]({context})", node\n )\n else:\n self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})")\n self.writeline("try:")\n self.indent()\n self.writeline(\n f"{self.choose_async()}for event in gen:",\n node,\n )\n self.indent()\n self.simple_write("event", frame)\n self.outdent()\n self.outdent()\n self.writeline(\n f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}"\n )\n\n self.outdent(level)\n\n def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:\n """Calls the extender."""\n if not frame.toplevel:\n self.fail("cannot use extend from a non top-level scope", node.lineno)\n\n # if the number of extends statements in general is zero so\n # far, we don't have to add a check if something extended\n # the template before this one.\n if self.extends_so_far > 0:\n # if we have a known extends we just add a template runtime\n # error into the generated code. We could catch that at compile\n # time too, but i welcome it not to confuse users by throwing the\n # same error at different times just "because we can".\n if not self.has_known_extends:\n self.writeline("if parent_template is not None:")\n self.indent()\n self.writeline('raise TemplateRuntimeError("extended multiple times")')\n\n # if we have a known extends already we don't need that code here\n # as we know that the template execution will end here.\n if self.has_known_extends:\n raise CompilerExit()\n else:\n self.outdent()\n\n self.writeline("parent_template = environment.get_template(", node)\n self.visit(node.template, frame)\n self.write(f", {self.name!r})")\n self.writeline("for name, parent_block in parent_template.blocks.items():")\n self.indent()\n self.writeline("context.blocks.setdefault(name, []).append(parent_block)")\n self.outdent()\n\n # if this extends statement was in the root level we can take\n # advantage of that information and simplify the generated code\n # in the top level from this point onwards\n if frame.rootlevel:\n self.has_known_extends = True\n\n # and now we have one more\n self.extends_so_far += 1\n\n def visit_Include(self, node: nodes.Include, frame: Frame) -> None:\n """Handles includes."""\n if node.ignore_missing:\n self.writeline("try:")\n self.indent()\n\n func_name = "get_or_select_template"\n if isinstance(node.template, nodes.Const):\n if isinstance(node.template.value, str):\n func_name = "get_template"\n elif isinstance(node.template.value, (tuple, list)):\n func_name = "select_template"\n elif isinstance(node.template, (nodes.Tuple, nodes.List)):\n func_name = "select_template"\n\n self.writeline(f"template = environment.{func_name}(", node)\n self.visit(node.template, frame)\n self.write(f", {self.name!r})")\n if node.ignore_missing:\n self.outdent()\n self.writeline("except TemplateNotFound:")\n self.indent()\n self.writeline("pass")\n self.outdent()\n self.writeline("else:")\n self.indent()\n\n def loop_body() -> None:\n self.indent()\n self.simple_write("event", frame)\n self.outdent()\n\n if node.with_context:\n self.writeline(\n f"gen = template.root_render_func("\n "template.new_context(context.get_all(), True,"\n f" {self.dump_local_context(frame)}))"\n )\n self.writeline("try:")\n self.indent()\n self.writeline(f"{self.choose_async()}for event in gen:")\n loop_body()\n self.outdent()\n self.writeline(\n f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}"\n )\n elif self.environment.is_async:\n self.writeline(\n "for event in (await template._get_default_module_async())"\n "._body_stream:"\n )\n loop_body()\n else:\n self.writeline("yield from template._get_default_module()._body_stream")\n\n if node.ignore_missing:\n self.outdent()\n\n def _import_common(\n self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame\n ) -> None:\n self.write(f"{self.choose_async('await ')}environment.get_template(")\n self.visit(node.template, frame)\n self.write(f", {self.name!r}).")\n\n if node.with_context:\n f_name = f"make_module{self.choose_async('_async')}"\n self.write(\n f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})"\n )\n else:\n self.write(f"_get_default_module{self.choose_async('_async')}(context)")\n\n def visit_Import(self, node: nodes.Import, frame: Frame) -> None:\n """Visit regular imports."""\n self.writeline(f"{frame.symbols.ref(node.target)} = ", node)\n if frame.toplevel:\n self.write(f"context.vars[{node.target!r}] = ")\n\n self._import_common(node, frame)\n\n if frame.toplevel and not node.target.startswith("_"):\n self.writeline(f"context.exported_vars.discard({node.target!r})")\n\n def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None:\n """Visit named imports."""\n self.newline(node)\n self.write("included_template = ")\n self._import_common(node, frame)\n var_names = []\n discarded_names = []\n for name in node.names:\n if isinstance(name, tuple):\n name, alias = name\n else:\n alias = name\n self.writeline(\n f"{frame.symbols.ref(alias)} ="\n f" getattr(included_template, {name!r}, missing)"\n )\n self.writeline(f"if {frame.symbols.ref(alias)} is missing:")\n self.indent()\n # The position will contain the template name, and will be formatted\n # into a string that will be compiled into an f-string. Curly braces\n # in the name must be replaced with escapes so that they will not be\n # executed as part of the f-string.\n position = self.position(node).replace("{", "{{").replace("}", "}}")\n message = (\n "the template {included_template.__name__!r}"\n f" (imported on {position})"\n f" does not export the requested name {name!r}"\n )\n self.writeline(\n f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"\n )\n self.outdent()\n if frame.toplevel:\n var_names.append(alias)\n if not alias.startswith("_"):\n discarded_names.append(alias)\n\n if var_names:\n if len(var_names) == 1:\n name = var_names[0]\n self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")\n else:\n names_kv = ", ".join(\n f"{name!r}: {frame.symbols.ref(name)}" for name in var_names\n )\n self.writeline(f"context.vars.update({{{names_kv}}})")\n if discarded_names:\n if len(discarded_names) == 1:\n self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})")\n else:\n names_str = ", ".join(map(repr, discarded_names))\n self.writeline(\n f"context.exported_vars.difference_update(({names_str}))"\n )\n\n def visit_For(self, node: nodes.For, frame: Frame) -> None:\n loop_frame = frame.inner()\n loop_frame.loop_frame = True\n test_frame = frame.inner()\n else_frame = frame.inner()\n\n # try to figure out if we have an extended loop. An extended loop\n # is necessary if the loop is in recursive mode if the special loop\n # variable is accessed in the body if the body is a scoped block.\n extended_loop = (\n node.recursive\n or "loop"\n in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",))\n or any(block.scoped for block in node.find_all(nodes.Block))\n )\n\n loop_ref = None\n if extended_loop:\n loop_ref = loop_frame.symbols.declare_parameter("loop")\n\n loop_frame.symbols.analyze_node(node, for_branch="body")\n if node.else_:\n else_frame.symbols.analyze_node(node, for_branch="else")\n\n if node.test:\n loop_filter_func = self.temporary_identifier()\n test_frame.symbols.analyze_node(node, for_branch="test")\n self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test)\n self.indent()\n self.enter_frame(test_frame)\n self.writeline(self.choose_async("async for ", "for "))\n self.visit(node.target, loop_frame)\n self.write(" in ")\n self.write(self.choose_async("auto_aiter(fiter)", "fiter"))\n self.write(":")\n self.indent()\n self.writeline("if ", node.test)\n self.visit(node.test, test_frame)\n self.write(":")\n self.indent()\n self.writeline("yield ")\n self.visit(node.target, loop_frame)\n self.outdent(3)\n self.leave_frame(test_frame, with_python_scope=True)\n\n # if we don't have an recursive loop we have to find the shadowed\n # variables at that point. Because loops can be nested but the loop\n # variable is a special one we have to enforce aliasing for it.\n if node.recursive:\n self.writeline(\n f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node\n )\n self.indent()\n self.buffer(loop_frame)\n\n # Use the same buffer for the else frame\n else_frame.buffer = loop_frame.buffer\n\n # make sure the loop variable is a special one and raise a template\n # assertion error if a loop tries to write to loop\n if extended_loop:\n self.writeline(f"{loop_ref} = missing")\n\n for name in node.find_all(nodes.Name):\n if name.ctx == "store" and name.name == "loop":\n self.fail(\n "Can't assign to special loop variable in for-loop target",\n name.lineno,\n )\n\n if node.else_:\n iteration_indicator = self.temporary_identifier()\n self.writeline(f"{iteration_indicator} = 1")\n\n self.writeline(self.choose_async("async for ", "for "), node)\n self.visit(node.target, loop_frame)\n if extended_loop:\n self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(")\n else:\n self.write(" in ")\n\n if node.test:\n self.write(f"{loop_filter_func}(")\n if node.recursive:\n self.write("reciter")\n else:\n if self.environment.is_async and not extended_loop:\n self.write("auto_aiter(")\n self.visit(node.iter, frame)\n if self.environment.is_async and not extended_loop:\n self.write(")")\n if node.test:\n self.write(")")\n\n if node.recursive:\n self.write(", undefined, loop_render_func, depth):")\n else:\n self.write(", undefined):" if extended_loop else ":")\n\n self.indent()\n self.enter_frame(loop_frame)\n\n self.writeline("_loop_vars = {}")\n self.blockvisit(node.body, loop_frame)\n if node.else_:\n self.writeline(f"{iteration_indicator} = 0")\n self.outdent()\n self.leave_frame(\n loop_frame, with_python_scope=node.recursive and not node.else_\n )\n\n if node.else_:\n self.writeline(f"if {iteration_indicator}:")\n self.indent()\n self.enter_frame(else_frame)\n self.blockvisit(node.else_, else_frame)\n self.leave_frame(else_frame)\n self.outdent()\n\n # if the node was recursive we have to return the buffer contents\n # and start the iteration code\n if node.recursive:\n self.return_buffer_contents(loop_frame)\n self.outdent()\n self.start_write(frame, node)\n self.write(f"{self.choose_async('await ')}loop(")\n if self.environment.is_async:\n self.write("auto_aiter(")\n self.visit(node.iter, frame)\n if self.environment.is_async:\n self.write(")")\n self.write(", loop)")\n self.end_write(frame)\n\n # at the end of the iteration, clear any assignments made in the\n # loop from the top level\n if self._assign_stack:\n self._assign_stack[-1].difference_update(loop_frame.symbols.stores)\n\n def visit_If(self, node: nodes.If, frame: Frame) -> None:\n if_frame = frame.soft()\n self.writeline("if ", node)\n self.visit(node.test, if_frame)\n self.write(":")\n self.indent()\n self.blockvisit(node.body, if_frame)\n self.outdent()\n for elif_ in node.elif_:\n self.writeline("elif ", elif_)\n self.visit(elif_.test, if_frame)\n self.write(":")\n self.indent()\n self.blockvisit(elif_.body, if_frame)\n self.outdent()\n if node.else_:\n self.writeline("else:")\n self.indent()\n self.blockvisit(node.else_, if_frame)\n self.outdent()\n\n def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None:\n macro_frame, macro_ref = self.macro_body(node, frame)\n self.newline()\n if frame.toplevel:\n if not node.name.startswith("_"):\n self.write(f"context.exported_vars.add({node.name!r})")\n self.writeline(f"context.vars[{node.name!r}] = ")\n self.write(f"{frame.symbols.ref(node.name)} = ")\n self.macro_def(macro_ref, macro_frame)\n\n def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None:\n call_frame, macro_ref = self.macro_body(node, frame)\n self.writeline("caller = ")\n self.macro_def(macro_ref, call_frame)\n self.start_write(frame, node)\n self.visit_Call(node.call, frame, forward_caller=True)\n self.end_write(frame)\n\n def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None:\n filter_frame = frame.inner()\n filter_frame.symbols.analyze_node(node)\n self.enter_frame(filter_frame)\n self.buffer(filter_frame)\n self.blockvisit(node.body, filter_frame)\n self.start_write(frame, node)\n self.visit_Filter(node.filter, filter_frame)\n self.end_write(frame)\n self.leave_frame(filter_frame)\n\n def visit_With(self, node: nodes.With, frame: Frame) -> None:\n with_frame = frame.inner()\n with_frame.symbols.analyze_node(node)\n self.enter_frame(with_frame)\n for target, expr in zip(node.targets, node.values):\n self.newline()\n self.visit(target, with_frame)\n self.write(" = ")\n self.visit(expr, frame)\n self.blockvisit(node.body, with_frame)\n self.leave_frame(with_frame)\n\n def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None:\n self.newline(node)\n self.visit(node.node, frame)\n\n class _FinalizeInfo(t.NamedTuple):\n const: t.Optional[t.Callable[..., str]]\n src: t.Optional[str]\n\n @staticmethod\n def _default_finalize(value: t.Any) -> t.Any:\n """The default finalize function if the environment isn't\n configured with one. Or, if the environment has one, this is\n called on that function's output for constants.\n """\n return str(value)\n\n _finalize: t.Optional[_FinalizeInfo] = None\n\n def _make_finalize(self) -> _FinalizeInfo:\n """Build the finalize function to be used on constants and at\n runtime. Cached so it's only created once for all output nodes.\n\n Returns a ``namedtuple`` with the following attributes:\n\n ``const``\n A function to finalize constant data at compile time.\n\n ``src``\n Source code to output around nodes to be evaluated at\n runtime.\n """\n if self._finalize is not None:\n return self._finalize\n\n finalize: t.Optional[t.Callable[..., t.Any]]\n finalize = default = self._default_finalize\n src = None\n\n if self.environment.finalize:\n src = "environment.finalize("\n env_finalize = self.environment.finalize\n pass_arg = {\n _PassArg.context: "context",\n _PassArg.eval_context: "context.eval_ctx",\n _PassArg.environment: "environment",\n }.get(\n _PassArg.from_obj(env_finalize) # type: ignore\n )\n finalize = None\n\n if pass_arg is None:\n\n def finalize(value: t.Any) -> t.Any: # noqa: F811\n return default(env_finalize(value))\n\n else:\n src = f"{src}{pass_arg}, "\n\n if pass_arg == "environment":\n\n def finalize(value: t.Any) -> t.Any: # noqa: F811\n return default(env_finalize(self.environment, value))\n\n self._finalize = self._FinalizeInfo(finalize, src)\n return self._finalize\n\n def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:\n """Given a group of constant values converted from ``Output``\n child nodes, produce a string to write to the template module\n source.\n """\n return repr(concat(group))\n\n def _output_child_to_const(\n self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo\n ) -> str:\n """Try to optimize a child of an ``Output`` node by trying to\n convert it to constant, finalized data at compile time.\n\n If :exc:`Impossible` is raised, the node is not constant and\n will be evaluated at runtime. Any other exception will also be\n evaluated at runtime for easier debugging.\n """\n const = node.as_const(frame.eval_ctx)\n\n if frame.eval_ctx.autoescape:\n const = escape(const)\n\n # Template data doesn't go through finalize.\n if isinstance(node, nodes.TemplateData):\n return str(const)\n\n return finalize.const(const) # type: ignore\n\n def _output_child_pre(\n self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo\n ) -> None:\n """Output extra source code before visiting a child of an\n ``Output`` node.\n """\n if frame.eval_ctx.volatile:\n self.write("(escape if context.eval_ctx.autoescape else str)(")\n elif frame.eval_ctx.autoescape:\n self.write("escape(")\n else:\n self.write("str(")\n\n if finalize.src is not None:\n self.write(finalize.src)\n\n def _output_child_post(\n self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo\n ) -> None:\n """Output extra source code after visiting a child of an\n ``Output`` node.\n """\n self.write(")")\n\n if finalize.src is not None:\n self.write(")")\n\n def visit_Output(self, node: nodes.Output, frame: Frame) -> None:\n # If an extends is active, don't render outside a block.\n if frame.require_output_check:\n # A top-level extends is known to exist at compile time.\n if self.has_known_extends:\n return\n\n self.writeline("if parent_template is None:")\n self.indent()\n\n finalize = self._make_finalize()\n body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = []\n\n # Evaluate constants at compile time if possible. Each item in\n # body will be either a list of static data or a node to be\n # evaluated at runtime.\n for child in node.nodes:\n try:\n if not (\n # If the finalize function requires runtime context,\n # constants can't be evaluated at compile time.\n finalize.const\n # Unless it's basic template data that won't be\n # finalized anyway.\n or isinstance(child, nodes.TemplateData)\n ):\n raise nodes.Impossible()\n\n const = self._output_child_to_const(child, frame, finalize)\n except (nodes.Impossible, Exception):\n # The node was not constant and needs to be evaluated at\n # runtime. Or another error was raised, which is easier\n # to debug at runtime.\n body.append(child)\n continue\n\n if body and isinstance(body[-1], list):\n body[-1].append(const)\n else:\n body.append([const])\n\n if frame.buffer is not None:\n if len(body) == 1:\n self.writeline(f"{frame.buffer}.append(")\n else:\n self.writeline(f"{frame.buffer}.extend((")\n\n self.indent()\n\n for item in body:\n if isinstance(item, list):\n # A group of constant data to join and output.\n val = self._output_const_repr(item)\n\n if frame.buffer is None:\n self.writeline("yield " + val)\n else:\n self.writeline(val + ",")\n else:\n if frame.buffer is None:\n self.writeline("yield ", item)\n else:\n self.newline(item)\n\n # A node to be evaluated at runtime.\n self._output_child_pre(item, frame, finalize)\n self.visit(item, frame)\n self._output_child_post(item, frame, finalize)\n\n if frame.buffer is not None:\n self.write(",")\n\n if frame.buffer is not None:\n self.outdent()\n self.writeline(")" if len(body) == 1 else "))")\n\n if frame.require_output_check:\n self.outdent()\n\n def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:\n self.push_assign_tracking()\n\n # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However,\n # it is only valid if it references a Namespace object. Emit a check for\n # that for each ref here, before assignment code is emitted. This can't\n # be done in visit_NSRef as the ref could be in the middle of a tuple.\n seen_refs: t.Set[str] = set()\n\n for nsref in node.find_all(nodes.NSRef):\n if nsref.name in seen_refs:\n # Only emit the check for each reference once, in case the same\n # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`.\n continue\n\n seen_refs.add(nsref.name)\n ref = frame.symbols.ref(nsref.name)\n self.writeline(f"if not isinstance({ref}, Namespace):")\n self.indent()\n self.writeline(\n "raise TemplateRuntimeError"\n '("cannot assign attribute on non-namespace object")'\n )\n self.outdent()\n\n self.newline(node)\n self.visit(node.target, frame)\n self.write(" = ")\n self.visit(node.node, frame)\n self.pop_assign_tracking(frame)\n\n def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None:\n self.push_assign_tracking()\n block_frame = frame.inner()\n # This is a special case. Since a set block always captures we\n # will disable output checks. This way one can use set blocks\n # toplevel even in extended templates.\n block_frame.require_output_check = False\n block_frame.symbols.analyze_node(node)\n self.enter_frame(block_frame)\n self.buffer(block_frame)\n self.blockvisit(node.body, block_frame)\n self.newline(node)\n self.visit(node.target, frame)\n self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")\n if node.filter is not None:\n self.visit_Filter(node.filter, block_frame)\n else:\n self.write(f"concat({block_frame.buffer})")\n self.write(")")\n self.pop_assign_tracking(frame)\n self.leave_frame(block_frame)\n\n # -- Expression Visitors\n\n def visit_Name(self, node: nodes.Name, frame: Frame) -> None:\n if node.ctx == "store" and (\n frame.toplevel or frame.loop_frame or frame.block_frame\n ):\n if self._assign_stack:\n self._assign_stack[-1].add(node.name)\n ref = frame.symbols.ref(node.name)\n\n # If we are looking up a variable we might have to deal with the\n # case where it's undefined. We can skip that case if the load\n # instruction indicates a parameter which are always defined.\n if node.ctx == "load":\n load = frame.symbols.find_load(ref)\n if not (\n load is not None\n and load[0] == VAR_LOAD_PARAMETER\n and not self.parameter_is_undeclared(ref)\n ):\n self.write(\n f"(undefined(name={node.name!r}) if {ref} is missing else {ref})"\n )\n return\n\n self.write(ref)\n\n def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:\n # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally.\n # visit_Assign emits code to validate that each ref is to a Namespace\n # object only. That can't be emitted here as the ref could be in the\n # middle of a tuple assignment.\n ref = frame.symbols.ref(node.name)\n self.writeline(f"{ref}[{node.attr!r}]")\n\n def visit_Const(self, node: nodes.Const, frame: Frame) -> None:\n val = node.as_const(frame.eval_ctx)\n if isinstance(val, float):\n self.write(str(val))\n else:\n self.write(repr(val))\n\n def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None:\n try:\n self.write(repr(node.as_const(frame.eval_ctx)))\n except nodes.Impossible:\n self.write(\n f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"\n )\n\n def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None:\n self.write("(")\n idx = -1\n for idx, item in enumerate(node.items):\n if idx:\n self.write(", ")\n self.visit(item, frame)\n self.write(",)" if idx == 0 else ")")\n\n def visit_List(self, node: nodes.List, frame: Frame) -> None:\n self.write("[")\n for idx, item in enumerate(node.items):\n if idx:\n self.write(", ")\n self.visit(item, frame)\n self.write("]")\n\n def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None:\n self.write("{")\n for idx, item in enumerate(node.items):\n if idx:\n self.write(", ")\n self.visit(item.key, frame)\n self.write(": ")\n self.visit(item.value, frame)\n self.write("}")\n\n visit_Add = _make_binop("+")\n visit_Sub = _make_binop("-")\n visit_Mul = _make_binop("*")\n visit_Div = _make_binop("/")\n visit_FloorDiv = _make_binop("//")\n visit_Pow = _make_binop("**")\n visit_Mod = _make_binop("%")\n visit_And = _make_binop("and")\n visit_Or = _make_binop("or")\n visit_Pos = _make_unop("+")\n visit_Neg = _make_unop("-")\n visit_Not = _make_unop("not ")\n\n @optimizeconst\n def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None:\n if frame.eval_ctx.volatile:\n func_name = "(markup_join if context.eval_ctx.volatile else str_join)"\n elif frame.eval_ctx.autoescape:\n func_name = "markup_join"\n else:\n func_name = "str_join"\n self.write(f"{func_name}((")\n for arg in node.nodes:\n self.visit(arg, frame)\n self.write(", ")\n self.write("))")\n\n @optimizeconst\n def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None:\n self.write("(")\n self.visit(node.expr, frame)\n for op in node.ops:\n self.visit(op, frame)\n self.write(")")\n\n def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None:\n self.write(f" {operators[node.op]} ")\n self.visit(node.expr, frame)\n\n @optimizeconst\n def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None:\n if self.environment.is_async:\n self.write("(await auto_await(")\n\n self.write("environment.getattr(")\n self.visit(node.node, frame)\n self.write(f", {node.attr!r})")\n\n if self.environment.is_async:\n self.write("))")\n\n @optimizeconst\n def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None:\n # slices bypass the environment getitem method.\n if isinstance(node.arg, nodes.Slice):\n self.visit(node.node, frame)\n self.write("[")\n self.visit(node.arg, frame)\n self.write("]")\n else:\n if self.environment.is_async:\n self.write("(await auto_await(")\n\n self.write("environment.getitem(")\n self.visit(node.node, frame)\n self.write(", ")\n self.visit(node.arg, frame)\n self.write(")")\n\n if self.environment.is_async:\n self.write("))")\n\n def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None:\n if node.start is not None:\n self.visit(node.start, frame)\n self.write(":")\n if node.stop is not None:\n self.visit(node.stop, frame)\n if node.step is not None:\n self.write(":")\n self.visit(node.step, frame)\n\n @contextmanager\n def _filter_test_common(\n self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool\n ) -> t.Iterator[None]:\n if self.environment.is_async:\n self.write("(await auto_await(")\n\n if is_filter:\n self.write(f"{self.filters[node.name]}(")\n func = self.environment.filters.get(node.name)\n else:\n self.write(f"{self.tests[node.name]}(")\n func = self.environment.tests.get(node.name)\n\n # When inside an If or CondExpr frame, allow the filter to be\n # undefined at compile time and only raise an error if it's\n # actually called at runtime. See pull_dependencies.\n if func is None and not frame.soft_frame:\n type_name = "filter" if is_filter else "test"\n self.fail(f"No {type_name} named {node.name!r}.", node.lineno)\n\n pass_arg = {\n _PassArg.context: "context",\n _PassArg.eval_context: "context.eval_ctx",\n _PassArg.environment: "environment",\n }.get(\n _PassArg.from_obj(func) # type: ignore\n )\n\n if pass_arg is not None:\n self.write(f"{pass_arg}, ")\n\n # Back to the visitor function to handle visiting the target of\n # the filter or test.\n yield\n\n self.signature(node, frame)\n self.write(")")\n\n if self.environment.is_async:\n self.write("))")\n\n @optimizeconst\n def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None:\n with self._filter_test_common(node, frame, True):\n # if the filter node is None we are inside a filter block\n # and want to write to the current buffer\n if node.node is not None:\n self.visit(node.node, frame)\n elif frame.eval_ctx.volatile:\n self.write(\n f"(Markup(concat({frame.buffer}))"\n f" if context.eval_ctx.autoescape else concat({frame.buffer}))"\n )\n elif frame.eval_ctx.autoescape:\n self.write(f"Markup(concat({frame.buffer}))")\n else:\n self.write(f"concat({frame.buffer})")\n\n @optimizeconst\n def visit_Test(self, node: nodes.Test, frame: Frame) -> None:\n with self._filter_test_common(node, frame, False):\n self.visit(node.node, frame)\n\n @optimizeconst\n def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None:\n frame = frame.soft()\n\n def write_expr2() -> None:\n if node.expr2 is not None:\n self.visit(node.expr2, frame)\n return\n\n self.write(\n f'cond_expr_undefined("the inline if-expression on'\n f" {self.position(node)} evaluated to false and no else"\n f' section was defined.")'\n )\n\n self.write("(")\n self.visit(node.expr1, frame)\n self.write(" if ")\n self.visit(node.test, frame)\n self.write(" else ")\n write_expr2()\n self.write(")")\n\n @optimizeconst\n def visit_Call(\n self, node: nodes.Call, frame: Frame, forward_caller: bool = False\n ) -> None:\n if self.environment.is_async:\n self.write("(await auto_await(")\n if self.environment.sandboxed:\n self.write("environment.call(context, ")\n else:\n self.write("context.call(")\n self.visit(node.node, frame)\n extra_kwargs = {"caller": "caller"} if forward_caller else None\n loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {}\n block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {}\n if extra_kwargs:\n extra_kwargs.update(loop_kwargs, **block_kwargs)\n elif loop_kwargs or block_kwargs:\n extra_kwargs = dict(loop_kwargs, **block_kwargs)\n self.signature(node, frame, extra_kwargs)\n self.write(")")\n if self.environment.is_async:\n self.write("))")\n\n def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None:\n self.write(node.key + "=")\n self.visit(node.value, frame)\n\n # -- Unused nodes for extensions\n\n def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None:\n self.write("Markup(")\n self.visit(node.expr, frame)\n self.write(")")\n\n def visit_MarkSafeIfAutoescape(\n self, node: nodes.MarkSafeIfAutoescape, frame: Frame\n ) -> None:\n self.write("(Markup if context.eval_ctx.autoescape else identity)(")\n self.visit(node.expr, frame)\n self.write(")")\n\n def visit_EnvironmentAttribute(\n self, node: nodes.EnvironmentAttribute, frame: Frame\n ) -> None:\n self.write("environment." + node.name)\n\n def visit_ExtensionAttribute(\n self, node: nodes.ExtensionAttribute, frame: Frame\n ) -> None:\n self.write(f"environment.extensions[{node.identifier!r}].{node.name}")\n\n def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None:\n self.write(self.import_aliases[node.importname])\n\n def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None:\n self.write(node.name)\n\n def visit_ContextReference(\n self, node: nodes.ContextReference, frame: Frame\n ) -> None:\n self.write("context")\n\n def visit_DerivedContextReference(\n self, node: nodes.DerivedContextReference, frame: Frame\n ) -> None:\n self.write(self.derive_context(frame))\n\n def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:\n self.writeline("continue", node)\n\n def visit_Break(self, node: nodes.Break, frame: Frame) -> None:\n self.writeline("break", node)\n\n def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None:\n scope_frame = frame.inner()\n scope_frame.symbols.analyze_node(node)\n self.enter_frame(scope_frame)\n self.blockvisit(node.body, scope_frame)\n self.leave_frame(scope_frame)\n\n def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None:\n ctx = self.temporary_identifier()\n self.writeline(f"{ctx} = {self.derive_context(frame)}")\n self.writeline(f"{ctx}.vars = ")\n self.visit(node.context, frame)\n self.push_context_reference(ctx)\n\n scope_frame = frame.inner(isolated=True)\n scope_frame.symbols.analyze_node(node)\n self.enter_frame(scope_frame)\n self.blockvisit(node.body, scope_frame)\n self.leave_frame(scope_frame)\n self.pop_context_reference()\n\n def visit_EvalContextModifier(\n self, node: nodes.EvalContextModifier, frame: Frame\n ) -> None:\n for keyword in node.options:\n self.writeline(f"context.eval_ctx.{keyword.key} = ")\n self.visit(keyword.value, frame)\n try:\n val = keyword.value.as_const(frame.eval_ctx)\n except nodes.Impossible:\n frame.eval_ctx.volatile = True\n else:\n setattr(frame.eval_ctx, keyword.key, val)\n\n def visit_ScopedEvalContextModifier(\n self, node: nodes.ScopedEvalContextModifier, frame: Frame\n ) -> None:\n old_ctx_name = self.temporary_identifier()\n saved_ctx = frame.eval_ctx.save()\n self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")\n self.visit_EvalContextModifier(node, frame)\n for child in node.body:\n self.visit(child, frame)\n frame.eval_ctx.revert(saved_ctx)\n self.writeline(f"context.eval_ctx.revert({old_ctx_name})")\n | .venv\Lib\site-packages\jinja2\compiler.py | compiler.py | Python | 74,131 | 0.75 | 0.235235 | 0.081909 | react-lib | 492 | 2024-07-08T19:44:10.592665 | BSD-3-Clause | false | eb0ea06048a3a00da84ffd56a6fa8019 |
#: list of lorem ipsum words used by the lipsum() helper function\nLOREM_IPSUM_WORDS = """\\na ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at\nauctor augue bibendum blandit class commodo condimentum congue consectetuer\nconsequat conubia convallis cras cubilia cum curabitur curae cursus dapibus\ndiam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend\nelementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames\nfaucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac\nhendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum\njusto lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem\nluctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie\nmollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non\nnonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque\npenatibus per pharetra phasellus placerat platea porta porttitor posuere\npotenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus\nridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit\nsociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor\ntempus tincidunt torquent tortor tristique turpis ullamcorper ultrices\nultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus\nviverra volutpat vulputate"""\n | .venv\Lib\site-packages\jinja2\constants.py | constants.py | Python | 1,433 | 0.95 | 0.1 | 0.05 | react-lib | 50 | 2025-02-15T07:38:20.378002 | BSD-3-Clause | false | 3fc9eeacad854b6a1aa52af53f109409 |
import typing as t\n\nfrom .filters import FILTERS as DEFAULT_FILTERS # noqa: F401\nfrom .tests import TESTS as DEFAULT_TESTS # noqa: F401\nfrom .utils import Cycler\nfrom .utils import generate_lorem_ipsum\nfrom .utils import Joiner\nfrom .utils import Namespace\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n\n# defaults for the parser / lexer\nBLOCK_START_STRING = "{%"\nBLOCK_END_STRING = "%}"\nVARIABLE_START_STRING = "{{"\nVARIABLE_END_STRING = "}}"\nCOMMENT_START_STRING = "{#"\nCOMMENT_END_STRING = "#}"\nLINE_STATEMENT_PREFIX: t.Optional[str] = None\nLINE_COMMENT_PREFIX: t.Optional[str] = None\nTRIM_BLOCKS = False\nLSTRIP_BLOCKS = False\nNEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n"\nKEEP_TRAILING_NEWLINE = False\n\n# default filters, tests and namespace\n\nDEFAULT_NAMESPACE = {\n "range": range,\n "dict": dict,\n "lipsum": generate_lorem_ipsum,\n "cycler": Cycler,\n "joiner": Joiner,\n "namespace": Namespace,\n}\n\n# default policies\nDEFAULT_POLICIES: t.Dict[str, t.Any] = {\n "compiler.ascii_str": True,\n "urlize.rel": "noopener",\n "urlize.target": None,\n "urlize.extra_schemes": None,\n "truncate.leeway": 5,\n "json.dumps_function": None,\n "json.dumps_kwargs": {"sort_keys": True},\n "ext.i18n.trimmed": False,\n}\n | .venv\Lib\site-packages\jinja2\defaults.py | defaults.py | Python | 1,267 | 0.95 | 0.041667 | 0.071429 | react-lib | 748 | 2025-06-10T20:07:27.627594 | Apache-2.0 | false | d2ecb9e8536a202b3514f96573a6675f |
import typing as t\n\nif t.TYPE_CHECKING:\n from .runtime import Undefined\n\n\nclass TemplateError(Exception):\n """Baseclass for all template errors."""\n\n def __init__(self, message: t.Optional[str] = None) -> None:\n super().__init__(message)\n\n @property\n def message(self) -> t.Optional[str]:\n return self.args[0] if self.args else None\n\n\nclass TemplateNotFound(IOError, LookupError, TemplateError):\n """Raised if a template does not exist.\n\n .. versionchanged:: 2.11\n If the given name is :class:`Undefined` and no message was\n provided, an :exc:`UndefinedError` is raised.\n """\n\n # Silence the Python warning about message being deprecated since\n # it's not valid here.\n message: t.Optional[str] = None\n\n def __init__(\n self,\n name: t.Optional[t.Union[str, "Undefined"]],\n message: t.Optional[str] = None,\n ) -> None:\n IOError.__init__(self, name)\n\n if message is None:\n from .runtime import Undefined\n\n if isinstance(name, Undefined):\n name._fail_with_undefined_error()\n\n message = name\n\n self.message = message\n self.name = name\n self.templates = [name]\n\n def __str__(self) -> str:\n return str(self.message)\n\n\nclass TemplatesNotFound(TemplateNotFound):\n """Like :class:`TemplateNotFound` but raised if multiple templates\n are selected. This is a subclass of :class:`TemplateNotFound`\n exception, so just catching the base exception will catch both.\n\n .. versionchanged:: 2.11\n If a name in the list of names is :class:`Undefined`, a message\n about it being undefined is shown rather than the empty string.\n\n .. versionadded:: 2.2\n """\n\n def __init__(\n self,\n names: t.Sequence[t.Union[str, "Undefined"]] = (),\n message: t.Optional[str] = None,\n ) -> None:\n if message is None:\n from .runtime import Undefined\n\n parts = []\n\n for name in names:\n if isinstance(name, Undefined):\n parts.append(name._undefined_message)\n else:\n parts.append(name)\n\n parts_str = ", ".join(map(str, parts))\n message = f"none of the templates given were found: {parts_str}"\n\n super().__init__(names[-1] if names else None, message)\n self.templates = list(names)\n\n\nclass TemplateSyntaxError(TemplateError):\n """Raised to tell the user that there is a problem with the template."""\n\n def __init__(\n self,\n message: str,\n lineno: int,\n name: t.Optional[str] = None,\n filename: t.Optional[str] = None,\n ) -> None:\n super().__init__(message)\n self.lineno = lineno\n self.name = name\n self.filename = filename\n self.source: t.Optional[str] = None\n\n # this is set to True if the debug.translate_syntax_error\n # function translated the syntax error into a new traceback\n self.translated = False\n\n def __str__(self) -> str:\n # for translated errors we only return the message\n if self.translated:\n return t.cast(str, self.message)\n\n # otherwise attach some stuff\n location = f"line {self.lineno}"\n name = self.filename or self.name\n if name:\n location = f'File "{name}", {location}'\n lines = [t.cast(str, self.message), " " + location]\n\n # if the source is set, add the line to the output\n if self.source is not None:\n try:\n line = self.source.splitlines()[self.lineno - 1]\n except IndexError:\n pass\n else:\n lines.append(" " + line.strip())\n\n return "\n".join(lines)\n\n def __reduce__(self): # type: ignore\n # https://bugs.python.org/issue1692335 Exceptions that take\n # multiple required arguments have problems with pickling.\n # Without this, raises TypeError: __init__() missing 1 required\n # positional argument: 'lineno'\n return self.__class__, (self.message, self.lineno, self.name, self.filename)\n\n\nclass TemplateAssertionError(TemplateSyntaxError):\n """Like a template syntax error, but covers cases where something in the\n template caused an error at compile time that wasn't necessarily caused\n by a syntax error. However it's a direct subclass of\n :exc:`TemplateSyntaxError` and has the same attributes.\n """\n\n\nclass TemplateRuntimeError(TemplateError):\n """A generic runtime error in the template engine. Under some situations\n Jinja may raise this exception.\n """\n\n\nclass UndefinedError(TemplateRuntimeError):\n """Raised if a template tries to operate on :class:`Undefined`."""\n\n\nclass SecurityError(TemplateRuntimeError):\n """Raised if a template tries to do something insecure if the\n sandbox is enabled.\n """\n\n\nclass FilterArgumentError(TemplateRuntimeError):\n """This error is raised if a filter was called with inappropriate\n arguments\n """\n | .venv\Lib\site-packages\jinja2\exceptions.py | exceptions.py | Python | 5,071 | 0.95 | 0.277108 | 0.089431 | react-lib | 806 | 2025-03-20T05:33:37.020687 | GPL-3.0 | false | d11bd5c21dc4cd1a7e9f8244cdce3db1 |
"""Extension API for adding custom tags and behavior."""\n\nimport pprint\nimport re\nimport typing as t\n\nfrom markupsafe import Markup\n\nfrom . import defaults\nfrom . import nodes\nfrom .environment import Environment\nfrom .exceptions import TemplateAssertionError\nfrom .exceptions import TemplateSyntaxError\nfrom .runtime import concat # type: ignore\nfrom .runtime import Context\nfrom .runtime import Undefined\nfrom .utils import import_string\nfrom .utils import pass_context\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n\n from .lexer import Token\n from .lexer import TokenStream\n from .parser import Parser\n\n class _TranslationsBasic(te.Protocol):\n def gettext(self, message: str) -> str: ...\n\n def ngettext(self, singular: str, plural: str, n: int) -> str:\n pass\n\n class _TranslationsContext(_TranslationsBasic):\n def pgettext(self, context: str, message: str) -> str: ...\n\n def npgettext(\n self, context: str, singular: str, plural: str, n: int\n ) -> str: ...\n\n _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]\n\n\n# I18N functions available in Jinja templates. If the I18N library\n# provides ugettext, it will be assigned to gettext.\nGETTEXT_FUNCTIONS: t.Tuple[str, ...] = (\n "_",\n "gettext",\n "ngettext",\n "pgettext",\n "npgettext",\n)\n_ws_re = re.compile(r"\s*\n\s*")\n\n\nclass Extension:\n """Extensions can be used to add extra functionality to the Jinja template\n system at the parser level. Custom extensions are bound to an environment\n but may not store environment specific data on `self`. The reason for\n this is that an extension can be bound to another environment (for\n overlays) by creating a copy and reassigning the `environment` attribute.\n\n As extensions are created by the environment they cannot accept any\n arguments for configuration. One may want to work around that by using\n a factory function, but that is not possible as extensions are identified\n by their import name. The correct way to configure the extension is\n storing the configuration values on the environment. Because this way the\n environment ends up acting as central configuration storage the\n attributes may clash which is why extensions have to ensure that the names\n they choose for configuration are not too generic. ``prefix`` for example\n is a terrible name, ``fragment_cache_prefix`` on the other hand is a good\n name as includes the name of the extension (fragment cache).\n """\n\n identifier: t.ClassVar[str]\n\n def __init_subclass__(cls) -> None:\n cls.identifier = f"{cls.__module__}.{cls.__name__}"\n\n #: if this extension parses this is the list of tags it's listening to.\n tags: t.Set[str] = set()\n\n #: the priority of that extension. This is especially useful for\n #: extensions that preprocess values. A lower value means higher\n #: priority.\n #:\n #: .. versionadded:: 2.4\n priority = 100\n\n def __init__(self, environment: Environment) -> None:\n self.environment = environment\n\n def bind(self, environment: Environment) -> "te.Self":\n """Create a copy of this extension bound to another environment."""\n rv = object.__new__(self.__class__)\n rv.__dict__.update(self.__dict__)\n rv.environment = environment\n return rv\n\n def preprocess(\n self, source: str, name: t.Optional[str], filename: t.Optional[str] = None\n ) -> str:\n """This method is called before the actual lexing and can be used to\n preprocess the source. The `filename` is optional. The return value\n must be the preprocessed source.\n """\n return source\n\n def filter_stream(\n self, stream: "TokenStream"\n ) -> t.Union["TokenStream", t.Iterable["Token"]]:\n """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used\n to filter tokens returned. This method has to return an iterable of\n :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a\n :class:`~jinja2.lexer.TokenStream`.\n """\n return stream\n\n def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:\n """If any of the :attr:`tags` matched this method is called with the\n parser as first argument. The token the parser stream is pointing at\n is the name token that matched. This method has to return one or a\n list of multiple nodes.\n """\n raise NotImplementedError()\n\n def attr(\n self, name: str, lineno: t.Optional[int] = None\n ) -> nodes.ExtensionAttribute:\n """Return an attribute node for the current extension. This is useful\n to pass constants on extensions to generated template code.\n\n ::\n\n self.attr('_my_attribute', lineno=lineno)\n """\n return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)\n\n def call_method(\n self,\n name: str,\n args: t.Optional[t.List[nodes.Expr]] = None,\n kwargs: t.Optional[t.List[nodes.Keyword]] = None,\n dyn_args: t.Optional[nodes.Expr] = None,\n dyn_kwargs: t.Optional[nodes.Expr] = None,\n lineno: t.Optional[int] = None,\n ) -> nodes.Call:\n """Call a method of the extension. This is a shortcut for\n :meth:`attr` + :class:`jinja2.nodes.Call`.\n """\n if args is None:\n args = []\n if kwargs is None:\n kwargs = []\n return nodes.Call(\n self.attr(name, lineno=lineno),\n args,\n kwargs,\n dyn_args,\n dyn_kwargs,\n lineno=lineno,\n )\n\n\n@pass_context\ndef _gettext_alias(\n __context: Context, *args: t.Any, **kwargs: t.Any\n) -> t.Union[t.Any, Undefined]:\n return __context.call(__context.resolve("gettext"), *args, **kwargs)\n\n\ndef _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:\n @pass_context\n def gettext(__context: Context, __string: str, **variables: t.Any) -> str:\n rv = __context.call(func, __string)\n if __context.eval_ctx.autoescape:\n rv = Markup(rv)\n # Always treat as a format string, even if there are no\n # variables. This makes translation strings more consistent\n # and predictable. This requires escaping\n return rv % variables # type: ignore\n\n return gettext\n\n\ndef _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:\n @pass_context\n def ngettext(\n __context: Context,\n __singular: str,\n __plural: str,\n __num: int,\n **variables: t.Any,\n ) -> str:\n variables.setdefault("num", __num)\n rv = __context.call(func, __singular, __plural, __num)\n if __context.eval_ctx.autoescape:\n rv = Markup(rv)\n # Always treat as a format string, see gettext comment above.\n return rv % variables # type: ignore\n\n return ngettext\n\n\ndef _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:\n @pass_context\n def pgettext(\n __context: Context, __string_ctx: str, __string: str, **variables: t.Any\n ) -> str:\n variables.setdefault("context", __string_ctx)\n rv = __context.call(func, __string_ctx, __string)\n\n if __context.eval_ctx.autoescape:\n rv = Markup(rv)\n\n # Always treat as a format string, see gettext comment above.\n return rv % variables # type: ignore\n\n return pgettext\n\n\ndef _make_new_npgettext(\n func: t.Callable[[str, str, str, int], str],\n) -> t.Callable[..., str]:\n @pass_context\n def npgettext(\n __context: Context,\n __string_ctx: str,\n __singular: str,\n __plural: str,\n __num: int,\n **variables: t.Any,\n ) -> str:\n variables.setdefault("context", __string_ctx)\n variables.setdefault("num", __num)\n rv = __context.call(func, __string_ctx, __singular, __plural, __num)\n\n if __context.eval_ctx.autoescape:\n rv = Markup(rv)\n\n # Always treat as a format string, see gettext comment above.\n return rv % variables # type: ignore\n\n return npgettext\n\n\nclass InternationalizationExtension(Extension):\n """This extension adds gettext support to Jinja."""\n\n tags = {"trans"}\n\n # TODO: the i18n extension is currently reevaluating values in a few\n # situations. Take this example:\n # {% trans count=something() %}{{ count }} foo{% pluralize\n # %}{{ count }} fooss{% endtrans %}\n # something is called twice here. One time for the gettext value and\n # the other time for the n-parameter of the ngettext function.\n\n def __init__(self, environment: Environment) -> None:\n super().__init__(environment)\n environment.globals["_"] = _gettext_alias\n environment.extend(\n install_gettext_translations=self._install,\n install_null_translations=self._install_null,\n install_gettext_callables=self._install_callables,\n uninstall_gettext_translations=self._uninstall,\n extract_translations=self._extract,\n newstyle_gettext=False,\n )\n\n def _install(\n self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None\n ) -> None:\n # ugettext and ungettext are preferred in case the I18N library\n # is providing compatibility with older Python versions.\n gettext = getattr(translations, "ugettext", None)\n if gettext is None:\n gettext = translations.gettext\n ngettext = getattr(translations, "ungettext", None)\n if ngettext is None:\n ngettext = translations.ngettext\n\n pgettext = getattr(translations, "pgettext", None)\n npgettext = getattr(translations, "npgettext", None)\n self._install_callables(\n gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext\n )\n\n def _install_null(self, newstyle: t.Optional[bool] = None) -> None:\n import gettext\n\n translations = gettext.NullTranslations()\n\n if hasattr(translations, "pgettext"):\n # Python < 3.8\n pgettext = translations.pgettext\n else:\n\n def pgettext(c: str, s: str) -> str: # type: ignore[misc]\n return s\n\n if hasattr(translations, "npgettext"):\n npgettext = translations.npgettext\n else:\n\n def npgettext(c: str, s: str, p: str, n: int) -> str: # type: ignore[misc]\n return s if n == 1 else p\n\n self._install_callables(\n gettext=translations.gettext,\n ngettext=translations.ngettext,\n newstyle=newstyle,\n pgettext=pgettext,\n npgettext=npgettext,\n )\n\n def _install_callables(\n self,\n gettext: t.Callable[[str], str],\n ngettext: t.Callable[[str, str, int], str],\n newstyle: t.Optional[bool] = None,\n pgettext: t.Optional[t.Callable[[str, str], str]] = None,\n npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,\n ) -> None:\n if newstyle is not None:\n self.environment.newstyle_gettext = newstyle # type: ignore\n if self.environment.newstyle_gettext: # type: ignore\n gettext = _make_new_gettext(gettext)\n ngettext = _make_new_ngettext(ngettext)\n\n if pgettext is not None:\n pgettext = _make_new_pgettext(pgettext)\n\n if npgettext is not None:\n npgettext = _make_new_npgettext(npgettext)\n\n self.environment.globals.update(\n gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext\n )\n\n def _uninstall(self, translations: "_SupportedTranslations") -> None:\n for key in ("gettext", "ngettext", "pgettext", "npgettext"):\n self.environment.globals.pop(key, None)\n\n def _extract(\n self,\n source: t.Union[str, nodes.Template],\n gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,\n ) -> t.Iterator[\n t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]\n ]:\n if isinstance(source, str):\n source = self.environment.parse(source)\n return extract_from_ast(source, gettext_functions)\n\n def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:\n """Parse a translatable tag."""\n lineno = next(parser.stream).lineno\n\n context = None\n context_token = parser.stream.next_if("string")\n\n if context_token is not None:\n context = context_token.value\n\n # find all the variables referenced. Additionally a variable can be\n # defined in the body of the trans block too, but this is checked at\n # a later state.\n plural_expr: t.Optional[nodes.Expr] = None\n plural_expr_assignment: t.Optional[nodes.Assign] = None\n num_called_num = False\n variables: t.Dict[str, nodes.Expr] = {}\n trimmed = None\n while parser.stream.current.type != "block_end":\n if variables:\n parser.stream.expect("comma")\n\n # skip colon for python compatibility\n if parser.stream.skip_if("colon"):\n break\n\n token = parser.stream.expect("name")\n if token.value in variables:\n parser.fail(\n f"translatable variable {token.value!r} defined twice.",\n token.lineno,\n exc=TemplateAssertionError,\n )\n\n # expressions\n if parser.stream.current.type == "assign":\n next(parser.stream)\n variables[token.value] = var = parser.parse_expression()\n elif trimmed is None and token.value in ("trimmed", "notrimmed"):\n trimmed = token.value == "trimmed"\n continue\n else:\n variables[token.value] = var = nodes.Name(token.value, "load")\n\n if plural_expr is None:\n if isinstance(var, nodes.Call):\n plural_expr = nodes.Name("_trans", "load")\n variables[token.value] = plural_expr\n plural_expr_assignment = nodes.Assign(\n nodes.Name("_trans", "store"), var\n )\n else:\n plural_expr = var\n num_called_num = token.value == "num"\n\n parser.stream.expect("block_end")\n\n plural = None\n have_plural = False\n referenced = set()\n\n # now parse until endtrans or pluralize\n singular_names, singular = self._parse_block(parser, True)\n if singular_names:\n referenced.update(singular_names)\n if plural_expr is None:\n plural_expr = nodes.Name(singular_names[0], "load")\n num_called_num = singular_names[0] == "num"\n\n # if we have a pluralize block, we parse that too\n if parser.stream.current.test("name:pluralize"):\n have_plural = True\n next(parser.stream)\n if parser.stream.current.type != "block_end":\n token = parser.stream.expect("name")\n if token.value not in variables:\n parser.fail(\n f"unknown variable {token.value!r} for pluralization",\n token.lineno,\n exc=TemplateAssertionError,\n )\n plural_expr = variables[token.value]\n num_called_num = token.value == "num"\n parser.stream.expect("block_end")\n plural_names, plural = self._parse_block(parser, False)\n next(parser.stream)\n referenced.update(plural_names)\n else:\n next(parser.stream)\n\n # register free names as simple name expressions\n for name in referenced:\n if name not in variables:\n variables[name] = nodes.Name(name, "load")\n\n if not have_plural:\n plural_expr = None\n elif plural_expr is None:\n parser.fail("pluralize without variables", lineno)\n\n if trimmed is None:\n trimmed = self.environment.policies["ext.i18n.trimmed"]\n if trimmed:\n singular = self._trim_whitespace(singular)\n if plural:\n plural = self._trim_whitespace(plural)\n\n node = self._make_node(\n singular,\n plural,\n context,\n variables,\n plural_expr,\n bool(referenced),\n num_called_num and have_plural,\n )\n node.set_lineno(lineno)\n if plural_expr_assignment is not None:\n return [plural_expr_assignment, node]\n else:\n return node\n\n def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:\n return _ws_re.sub(" ", string.strip())\n\n def _parse_block(\n self, parser: "Parser", allow_pluralize: bool\n ) -> t.Tuple[t.List[str], str]:\n """Parse until the next block tag with a given name."""\n referenced = []\n buf = []\n\n while True:\n if parser.stream.current.type == "data":\n buf.append(parser.stream.current.value.replace("%", "%%"))\n next(parser.stream)\n elif parser.stream.current.type == "variable_begin":\n next(parser.stream)\n name = parser.stream.expect("name").value\n referenced.append(name)\n buf.append(f"%({name})s")\n parser.stream.expect("variable_end")\n elif parser.stream.current.type == "block_begin":\n next(parser.stream)\n block_name = (\n parser.stream.current.value\n if parser.stream.current.type == "name"\n else None\n )\n if block_name == "endtrans":\n break\n elif block_name == "pluralize":\n if allow_pluralize:\n break\n parser.fail(\n "a translatable section can have only one pluralize section"\n )\n elif block_name == "trans":\n parser.fail(\n "trans blocks can't be nested; did you mean `endtrans`?"\n )\n parser.fail(\n f"control structures in translatable sections are not allowed; "\n f"saw `{block_name}`"\n )\n elif parser.stream.eos:\n parser.fail("unclosed translation block")\n else:\n raise RuntimeError("internal parser error")\n\n return referenced, concat(buf)\n\n def _make_node(\n self,\n singular: str,\n plural: t.Optional[str],\n context: t.Optional[str],\n variables: t.Dict[str, nodes.Expr],\n plural_expr: t.Optional[nodes.Expr],\n vars_referenced: bool,\n num_called_num: bool,\n ) -> nodes.Output:\n """Generates a useful node from the data provided."""\n newstyle = self.environment.newstyle_gettext # type: ignore\n node: nodes.Expr\n\n # no variables referenced? no need to escape for old style\n # gettext invocations only if there are vars.\n if not vars_referenced and not newstyle:\n singular = singular.replace("%%", "%")\n if plural:\n plural = plural.replace("%%", "%")\n\n func_name = "gettext"\n func_args: t.List[nodes.Expr] = [nodes.Const(singular)]\n\n if context is not None:\n func_args.insert(0, nodes.Const(context))\n func_name = f"p{func_name}"\n\n if plural_expr is not None:\n func_name = f"n{func_name}"\n func_args.extend((nodes.Const(plural), plural_expr))\n\n node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)\n\n # in case newstyle gettext is used, the method is powerful\n # enough to handle the variable expansion and autoescape\n # handling itself\n if newstyle:\n for key, value in variables.items():\n # the function adds that later anyways in case num was\n # called num, so just skip it.\n if num_called_num and key == "num":\n continue\n node.kwargs.append(nodes.Keyword(key, value))\n\n # otherwise do that here\n else:\n # mark the return value as safe if we are in an\n # environment with autoescaping turned on\n node = nodes.MarkSafeIfAutoescape(node)\n if variables:\n node = nodes.Mod(\n node,\n nodes.Dict(\n [\n nodes.Pair(nodes.Const(key), value)\n for key, value in variables.items()\n ]\n ),\n )\n return nodes.Output([node])\n\n\nclass ExprStmtExtension(Extension):\n """Adds a `do` tag to Jinja that works like the print statement just\n that it doesn't print the return value.\n """\n\n tags = {"do"}\n\n def parse(self, parser: "Parser") -> nodes.ExprStmt:\n node = nodes.ExprStmt(lineno=next(parser.stream).lineno)\n node.node = parser.parse_tuple()\n return node\n\n\nclass LoopControlExtension(Extension):\n """Adds break and continue to the template engine."""\n\n tags = {"break", "continue"}\n\n def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:\n token = next(parser.stream)\n if token.value == "break":\n return nodes.Break(lineno=token.lineno)\n return nodes.Continue(lineno=token.lineno)\n\n\nclass DebugExtension(Extension):\n """A ``{% debug %}`` tag that dumps the available variables,\n filters, and tests.\n\n .. code-block:: html+jinja\n\n <pre>{% debug %}</pre>\n\n .. code-block:: text\n\n {'context': {'cycler': <class 'jinja2.utils.Cycler'>,\n ...,\n 'namespace': <class 'jinja2.utils.Namespace'>},\n 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',\n ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],\n 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',\n ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}\n\n .. versionadded:: 2.11.0\n """\n\n tags = {"debug"}\n\n def parse(self, parser: "Parser") -> nodes.Output:\n lineno = parser.stream.expect("name:debug").lineno\n context = nodes.ContextReference()\n result = self.call_method("_render", [context], lineno=lineno)\n return nodes.Output([result], lineno=lineno)\n\n def _render(self, context: Context) -> str:\n result = {\n "context": context.get_all(),\n "filters": sorted(self.environment.filters.keys()),\n "tests": sorted(self.environment.tests.keys()),\n }\n\n # Set the depth since the intent is to show the top few names.\n return pprint.pformat(result, depth=3, compact=True)\n\n\ndef extract_from_ast(\n ast: nodes.Template,\n gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,\n babel_style: bool = True,\n) -> t.Iterator[\n t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]\n]:\n """Extract localizable strings from the given template node. Per\n default this function returns matches in babel style that means non string\n parameters as well as keyword arguments are returned as `None`. This\n allows Babel to figure out what you really meant if you are using\n gettext functions that allow keyword arguments for placeholder expansion.\n If you don't want that behavior set the `babel_style` parameter to `False`\n which causes only strings to be returned and parameters are always stored\n in tuples. As a consequence invalid gettext calls (calls without a single\n string parameter or string parameters after non-string parameters) are\n skipped.\n\n This example explains the behavior:\n\n >>> from jinja2 import Environment\n >>> env = Environment()\n >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')\n >>> list(extract_from_ast(node))\n [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]\n >>> list(extract_from_ast(node, babel_style=False))\n [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]\n\n For every string found this function yields a ``(lineno, function,\n message)`` tuple, where:\n\n * ``lineno`` is the number of the line on which the string was found,\n * ``function`` is the name of the ``gettext`` function used (if the\n string was extracted from embedded Python code), and\n * ``message`` is the string, or a tuple of strings for functions\n with multiple string arguments.\n\n This extraction function operates on the AST and is because of that unable\n to extract any comments. For comment support you have to use the babel\n extraction interface or extract comments yourself.\n """\n out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]\n\n for node in ast.find_all(nodes.Call):\n if (\n not isinstance(node.node, nodes.Name)\n or node.node.name not in gettext_functions\n ):\n continue\n\n strings: t.List[t.Optional[str]] = []\n\n for arg in node.args:\n if isinstance(arg, nodes.Const) and isinstance(arg.value, str):\n strings.append(arg.value)\n else:\n strings.append(None)\n\n for _ in node.kwargs:\n strings.append(None)\n if node.dyn_args is not None:\n strings.append(None)\n if node.dyn_kwargs is not None:\n strings.append(None)\n\n if not babel_style:\n out = tuple(x for x in strings if x is not None)\n\n if not out:\n continue\n else:\n if len(strings) == 1:\n out = strings[0]\n else:\n out = tuple(strings)\n\n yield node.lineno, node.node.name, out\n\n\nclass _CommentFinder:\n """Helper class to find comments in a token stream. Can only\n find comments for gettext calls forwards. Once the comment\n from line 4 is found, a comment for line 1 will not return a\n usable value.\n """\n\n def __init__(\n self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]\n ) -> None:\n self.tokens = tokens\n self.comment_tags = comment_tags\n self.offset = 0\n self.last_lineno = 0\n\n def find_backwards(self, offset: int) -> t.List[str]:\n try:\n for _, token_type, token_value in reversed(\n self.tokens[self.offset : offset]\n ):\n if token_type in ("comment", "linecomment"):\n try:\n prefix, comment = token_value.split(None, 1)\n except ValueError:\n continue\n if prefix in self.comment_tags:\n return [comment.rstrip()]\n return []\n finally:\n self.offset = offset\n\n def find_comments(self, lineno: int) -> t.List[str]:\n if not self.comment_tags or self.last_lineno > lineno:\n return []\n for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):\n if token_lineno > lineno:\n return self.find_backwards(self.offset + idx)\n return self.find_backwards(len(self.tokens))\n\n\ndef babel_extract(\n fileobj: t.BinaryIO,\n keywords: t.Sequence[str],\n comment_tags: t.Sequence[str],\n options: t.Dict[str, t.Any],\n) -> t.Iterator[\n t.Tuple[\n int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]\n ]\n]:\n """Babel extraction method for Jinja templates.\n\n .. versionchanged:: 2.3\n Basic support for translation comments was added. If `comment_tags`\n is now set to a list of keywords for extraction, the extractor will\n try to find the best preceding comment that begins with one of the\n keywords. For best results, make sure to not have more than one\n gettext call in one line of code and the matching comment in the\n same line or the line before.\n\n .. versionchanged:: 2.5.1\n The `newstyle_gettext` flag can be set to `True` to enable newstyle\n gettext calls.\n\n .. versionchanged:: 2.7\n A `silent` option can now be provided. If set to `False` template\n syntax errors are propagated instead of being ignored.\n\n :param fileobj: the file-like object the messages should be extracted from\n :param keywords: a list of keywords (i.e. function names) that should be\n recognized as translation functions\n :param comment_tags: a list of translator tags to search for and include\n in the results.\n :param options: a dictionary of additional options (optional)\n :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.\n (comments will be empty currently)\n """\n extensions: t.Dict[t.Type[Extension], None] = {}\n\n for extension_name in options.get("extensions", "").split(","):\n extension_name = extension_name.strip()\n\n if not extension_name:\n continue\n\n extensions[import_string(extension_name)] = None\n\n if InternationalizationExtension not in extensions:\n extensions[InternationalizationExtension] = None\n\n def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:\n return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}\n\n silent = getbool(options, "silent", True)\n environment = Environment(\n options.get("block_start_string", defaults.BLOCK_START_STRING),\n options.get("block_end_string", defaults.BLOCK_END_STRING),\n options.get("variable_start_string", defaults.VARIABLE_START_STRING),\n options.get("variable_end_string", defaults.VARIABLE_END_STRING),\n options.get("comment_start_string", defaults.COMMENT_START_STRING),\n options.get("comment_end_string", defaults.COMMENT_END_STRING),\n options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,\n options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,\n getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),\n getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),\n defaults.NEWLINE_SEQUENCE,\n getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),\n tuple(extensions),\n cache_size=0,\n auto_reload=False,\n )\n\n if getbool(options, "trimmed"):\n environment.policies["ext.i18n.trimmed"] = True\n if getbool(options, "newstyle_gettext"):\n environment.newstyle_gettext = True # type: ignore\n\n source = fileobj.read().decode(options.get("encoding", "utf-8"))\n try:\n node = environment.parse(source)\n tokens = list(environment.lex(environment.preprocess(source)))\n except TemplateSyntaxError:\n if not silent:\n raise\n # skip templates with syntax errors\n return\n\n finder = _CommentFinder(tokens, comment_tags)\n for lineno, func, message in extract_from_ast(node, keywords):\n yield lineno, func, message, finder.find_comments(lineno)\n\n\n#: nicer import names\ni18n = InternationalizationExtension\ndo = ExprStmtExtension\nloopcontrols = LoopControlExtension\ndebug = DebugExtension\n | .venv\Lib\site-packages\jinja2\ext.py | ext.py | Python | 31,875 | 0.95 | 0.205747 | 0.067961 | vue-tools | 258 | 2024-11-16T01:04:01.767669 | GPL-3.0 | false | a1a1b549337b40a82f706cbdd6e3dece |
import typing as t\n\nfrom . import nodes\nfrom .visitor import NodeVisitor\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n\nVAR_LOAD_PARAMETER = "param"\nVAR_LOAD_RESOLVE = "resolve"\nVAR_LOAD_ALIAS = "alias"\nVAR_LOAD_UNDEFINED = "undefined"\n\n\ndef find_symbols(\n nodes: t.Iterable[nodes.Node], parent_symbols: t.Optional["Symbols"] = None\n) -> "Symbols":\n sym = Symbols(parent=parent_symbols)\n visitor = FrameSymbolVisitor(sym)\n for node in nodes:\n visitor.visit(node)\n return sym\n\n\ndef symbols_for_node(\n node: nodes.Node, parent_symbols: t.Optional["Symbols"] = None\n) -> "Symbols":\n sym = Symbols(parent=parent_symbols)\n sym.analyze_node(node)\n return sym\n\n\nclass Symbols:\n def __init__(\n self, parent: t.Optional["Symbols"] = None, level: t.Optional[int] = None\n ) -> None:\n if level is None:\n if parent is None:\n level = 0\n else:\n level = parent.level + 1\n\n self.level: int = level\n self.parent = parent\n self.refs: t.Dict[str, str] = {}\n self.loads: t.Dict[str, t.Any] = {}\n self.stores: t.Set[str] = set()\n\n def analyze_node(self, node: nodes.Node, **kwargs: t.Any) -> None:\n visitor = RootVisitor(self)\n visitor.visit(node, **kwargs)\n\n def _define_ref(\n self, name: str, load: t.Optional[t.Tuple[str, t.Optional[str]]] = None\n ) -> str:\n ident = f"l_{self.level}_{name}"\n self.refs[name] = ident\n if load is not None:\n self.loads[ident] = load\n return ident\n\n def find_load(self, target: str) -> t.Optional[t.Any]:\n if target in self.loads:\n return self.loads[target]\n\n if self.parent is not None:\n return self.parent.find_load(target)\n\n return None\n\n def find_ref(self, name: str) -> t.Optional[str]:\n if name in self.refs:\n return self.refs[name]\n\n if self.parent is not None:\n return self.parent.find_ref(name)\n\n return None\n\n def ref(self, name: str) -> str:\n rv = self.find_ref(name)\n if rv is None:\n raise AssertionError(\n "Tried to resolve a name to a reference that was"\n f" unknown to the frame ({name!r})"\n )\n return rv\n\n def copy(self) -> "te.Self":\n rv = object.__new__(self.__class__)\n rv.__dict__.update(self.__dict__)\n rv.refs = self.refs.copy()\n rv.loads = self.loads.copy()\n rv.stores = self.stores.copy()\n return rv\n\n def store(self, name: str) -> None:\n self.stores.add(name)\n\n # If we have not see the name referenced yet, we need to figure\n # out what to set it to.\n if name not in self.refs:\n # If there is a parent scope we check if the name has a\n # reference there. If it does it means we might have to alias\n # to a variable there.\n if self.parent is not None:\n outer_ref = self.parent.find_ref(name)\n if outer_ref is not None:\n self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))\n return\n\n # Otherwise we can just set it to undefined.\n self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))\n\n def declare_parameter(self, name: str) -> str:\n self.stores.add(name)\n return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))\n\n def load(self, name: str) -> None:\n if self.find_ref(name) is None:\n self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))\n\n def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:\n stores: t.Set[str] = set()\n\n for branch in branch_symbols:\n stores.update(branch.stores)\n\n stores.difference_update(self.stores)\n\n for sym in branch_symbols:\n self.refs.update(sym.refs)\n self.loads.update(sym.loads)\n self.stores.update(sym.stores)\n\n for name in stores:\n target = self.find_ref(name)\n assert target is not None, "should not happen"\n\n if self.parent is not None:\n outer_target = self.parent.find_ref(name)\n if outer_target is not None:\n self.loads[target] = (VAR_LOAD_ALIAS, outer_target)\n continue\n self.loads[target] = (VAR_LOAD_RESOLVE, name)\n\n def dump_stores(self) -> t.Dict[str, str]:\n rv: t.Dict[str, str] = {}\n node: t.Optional[Symbols] = self\n\n while node is not None:\n for name in sorted(node.stores):\n if name not in rv:\n rv[name] = self.find_ref(name) # type: ignore\n\n node = node.parent\n\n return rv\n\n def dump_param_targets(self) -> t.Set[str]:\n rv = set()\n node: t.Optional[Symbols] = self\n\n while node is not None:\n for target, (instr, _) in self.loads.items():\n if instr == VAR_LOAD_PARAMETER:\n rv.add(target)\n\n node = node.parent\n\n return rv\n\n\nclass RootVisitor(NodeVisitor):\n def __init__(self, symbols: "Symbols") -> None:\n self.sym_visitor = FrameSymbolVisitor(symbols)\n\n def _simple_visit(self, node: nodes.Node, **kwargs: t.Any) -> None:\n for child in node.iter_child_nodes():\n self.sym_visitor.visit(child)\n\n visit_Template = _simple_visit\n visit_Block = _simple_visit\n visit_Macro = _simple_visit\n visit_FilterBlock = _simple_visit\n visit_Scope = _simple_visit\n visit_If = _simple_visit\n visit_ScopedEvalContextModifier = _simple_visit\n\n def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:\n for child in node.body:\n self.sym_visitor.visit(child)\n\n def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:\n for child in node.iter_child_nodes(exclude=("call",)):\n self.sym_visitor.visit(child)\n\n def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:\n for child in node.body:\n self.sym_visitor.visit(child)\n\n def visit_For(\n self, node: nodes.For, for_branch: str = "body", **kwargs: t.Any\n ) -> None:\n if for_branch == "body":\n self.sym_visitor.visit(node.target, store_as_param=True)\n branch = node.body\n elif for_branch == "else":\n branch = node.else_\n elif for_branch == "test":\n self.sym_visitor.visit(node.target, store_as_param=True)\n if node.test is not None:\n self.sym_visitor.visit(node.test)\n return\n else:\n raise RuntimeError("Unknown for branch")\n\n if branch:\n for item in branch:\n self.sym_visitor.visit(item)\n\n def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:\n for target in node.targets:\n self.sym_visitor.visit(target)\n for child in node.body:\n self.sym_visitor.visit(child)\n\n def generic_visit(self, node: nodes.Node, *args: t.Any, **kwargs: t.Any) -> None:\n raise NotImplementedError(f"Cannot find symbols for {type(node).__name__!r}")\n\n\nclass FrameSymbolVisitor(NodeVisitor):\n """A visitor for `Frame.inspect`."""\n\n def __init__(self, symbols: "Symbols") -> None:\n self.symbols = symbols\n\n def visit_Name(\n self, node: nodes.Name, store_as_param: bool = False, **kwargs: t.Any\n ) -> None:\n """All assignments to names go through this function."""\n if store_as_param or node.ctx == "param":\n self.symbols.declare_parameter(node.name)\n elif node.ctx == "store":\n self.symbols.store(node.name)\n elif node.ctx == "load":\n self.symbols.load(node.name)\n\n def visit_NSRef(self, node: nodes.NSRef, **kwargs: t.Any) -> None:\n self.symbols.load(node.name)\n\n def visit_If(self, node: nodes.If, **kwargs: t.Any) -> None:\n self.visit(node.test, **kwargs)\n original_symbols = self.symbols\n\n def inner_visit(nodes: t.Iterable[nodes.Node]) -> "Symbols":\n self.symbols = rv = original_symbols.copy()\n\n for subnode in nodes:\n self.visit(subnode, **kwargs)\n\n self.symbols = original_symbols\n return rv\n\n body_symbols = inner_visit(node.body)\n elif_symbols = inner_visit(node.elif_)\n else_symbols = inner_visit(node.else_ or ())\n self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])\n\n def visit_Macro(self, node: nodes.Macro, **kwargs: t.Any) -> None:\n self.symbols.store(node.name)\n\n def visit_Import(self, node: nodes.Import, **kwargs: t.Any) -> None:\n self.generic_visit(node, **kwargs)\n self.symbols.store(node.target)\n\n def visit_FromImport(self, node: nodes.FromImport, **kwargs: t.Any) -> None:\n self.generic_visit(node, **kwargs)\n\n for name in node.names:\n if isinstance(name, tuple):\n self.symbols.store(name[1])\n else:\n self.symbols.store(name)\n\n def visit_Assign(self, node: nodes.Assign, **kwargs: t.Any) -> None:\n """Visit assignments in the correct order."""\n self.visit(node.node, **kwargs)\n self.visit(node.target, **kwargs)\n\n def visit_For(self, node: nodes.For, **kwargs: t.Any) -> None:\n """Visiting stops at for blocks. However the block sequence\n is visited as part of the outer scope.\n """\n self.visit(node.iter, **kwargs)\n\n def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:\n self.visit(node.call, **kwargs)\n\n def visit_FilterBlock(self, node: nodes.FilterBlock, **kwargs: t.Any) -> None:\n self.visit(node.filter, **kwargs)\n\n def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:\n for target in node.values:\n self.visit(target)\n\n def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:\n """Stop visiting at block assigns."""\n self.visit(node.target, **kwargs)\n\n def visit_Scope(self, node: nodes.Scope, **kwargs: t.Any) -> None:\n """Stop visiting at scopes."""\n\n def visit_Block(self, node: nodes.Block, **kwargs: t.Any) -> None:\n """Stop visiting at blocks."""\n\n def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:\n """Do not visit into overlay scopes."""\n | .venv\Lib\site-packages\jinja2\idtracking.py | idtracking.py | Python | 10,555 | 0.95 | 0.279874 | 0.02449 | vue-tools | 877 | 2025-06-20T17:29:42.400112 | MIT | false | 97bdf4bbfb95cd012521721dfe20aac8 |
"""Functions that expose information about templates that might be\ninteresting for introspection.\n"""\n\nimport typing as t\n\nfrom . import nodes\nfrom .compiler import CodeGenerator\nfrom .compiler import Frame\n\nif t.TYPE_CHECKING:\n from .environment import Environment\n\n\nclass TrackingCodeGenerator(CodeGenerator):\n """We abuse the code generator for introspection."""\n\n def __init__(self, environment: "Environment") -> None:\n super().__init__(environment, "<introspection>", "<introspection>")\n self.undeclared_identifiers: t.Set[str] = set()\n\n def write(self, x: str) -> None:\n """Don't write."""\n\n def enter_frame(self, frame: Frame) -> None:\n """Remember all undeclared identifiers."""\n super().enter_frame(frame)\n\n for _, (action, param) in frame.symbols.loads.items():\n if action == "resolve" and param not in self.environment.globals:\n self.undeclared_identifiers.add(param)\n\n\ndef find_undeclared_variables(ast: nodes.Template) -> t.Set[str]:\n """Returns a set of all variables in the AST that will be looked up from\n the context at runtime. Because at compile time it's not known which\n variables will be used depending on the path the execution takes at\n runtime, all variables are returned.\n\n >>> from jinja2 import Environment, meta\n >>> env = Environment()\n >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')\n >>> meta.find_undeclared_variables(ast) == {'bar'}\n True\n\n .. admonition:: Implementation\n\n Internally the code generator is used for finding undeclared variables.\n This is good to know because the code generator might raise a\n :exc:`TemplateAssertionError` during compilation and as a matter of\n fact this function can currently raise that exception as well.\n """\n codegen = TrackingCodeGenerator(ast.environment) # type: ignore\n codegen.visit(ast)\n return codegen.undeclared_identifiers\n\n\n_ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)\n_RefType = t.Union[nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include]\n\n\ndef find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]:\n """Finds all the referenced templates from the AST. This will return an\n iterator over all the hardcoded template extensions, inclusions and\n imports. If dynamic inheritance or inclusion is used, `None` will be\n yielded.\n\n >>> from jinja2 import Environment, meta\n >>> env = Environment()\n >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')\n >>> list(meta.find_referenced_templates(ast))\n ['layout.html', None]\n\n This function is useful for dependency tracking. For example if you want\n to rebuild parts of the website after a layout template has changed.\n """\n template_name: t.Any\n\n for node in ast.find_all(_ref_types):\n template: nodes.Expr = node.template # type: ignore\n\n if not isinstance(template, nodes.Const):\n # a tuple with some non consts in there\n if isinstance(template, (nodes.Tuple, nodes.List)):\n for template_name in template.items:\n # something const, only yield the strings and ignore\n # non-string consts that really just make no sense\n if isinstance(template_name, nodes.Const):\n if isinstance(template_name.value, str):\n yield template_name.value\n # something dynamic in there\n else:\n yield None\n # something dynamic we don't know about here\n else:\n yield None\n continue\n # constant is a basestring, direct template name\n if isinstance(template.value, str):\n yield template.value\n # a tuple or list (latter *should* not happen) made of consts,\n # yield the consts that are strings. We could warn here for\n # non string values\n elif isinstance(node, nodes.Include) and isinstance(\n template.value, (tuple, list)\n ):\n for template_name in template.value:\n if isinstance(template_name, str):\n yield template_name\n # something else we don't care about, we could warn here\n else:\n yield None\n | .venv\Lib\site-packages\jinja2\meta.py | meta.py | Python | 4,397 | 0.95 | 0.232143 | 0.111111 | python-kit | 437 | 2025-04-19T11:26:14.728550 | BSD-3-Clause | false | b457c1e1135cda85b0f92ea410c197d8 |
"""The optimizer tries to constant fold expressions and modify the AST\nin place so that it should be faster to evaluate.\n\nBecause the AST does not contain all the scoping information and the\ncompiler has to find that out, we cannot do all the optimizations we\nwant. For example, loop unrolling doesn't work because unrolled loops\nwould have a different scope. The solution would be a second syntax tree\nthat stored the scoping rules.\n"""\n\nimport typing as t\n\nfrom . import nodes\nfrom .visitor import NodeTransformer\n\nif t.TYPE_CHECKING:\n from .environment import Environment\n\n\ndef optimize(node: nodes.Node, environment: "Environment") -> nodes.Node:\n """The context hint can be used to perform an static optimization\n based on the context given."""\n optimizer = Optimizer(environment)\n return t.cast(nodes.Node, optimizer.visit(node))\n\n\nclass Optimizer(NodeTransformer):\n def __init__(self, environment: "t.Optional[Environment]") -> None:\n self.environment = environment\n\n def generic_visit(\n self, node: nodes.Node, *args: t.Any, **kwargs: t.Any\n ) -> nodes.Node:\n node = super().generic_visit(node, *args, **kwargs)\n\n # Do constant folding. Some other nodes besides Expr have\n # as_const, but folding them causes errors later on.\n if isinstance(node, nodes.Expr):\n try:\n return nodes.Const.from_untrusted(\n node.as_const(args[0] if args else None),\n lineno=node.lineno,\n environment=self.environment,\n )\n except nodes.Impossible:\n pass\n\n return node\n | .venv\Lib\site-packages\jinja2\optimizer.py | optimizer.py | Python | 1,651 | 0.95 | 0.166667 | 0.054054 | python-kit | 858 | 2025-04-05T03:53:24.471417 | Apache-2.0 | false | 4c2db0cf008a77243634ef76b52a536b |
"""Parse tokens from the lexer into nodes for the compiler."""\n\nimport typing\nimport typing as t\n\nfrom . import nodes\nfrom .exceptions import TemplateAssertionError\nfrom .exceptions import TemplateSyntaxError\nfrom .lexer import describe_token\nfrom .lexer import describe_token_expr\n\nif t.TYPE_CHECKING:\n import typing_extensions as te\n\n from .environment import Environment\n\n_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)\n_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)\n\n_statement_keywords = frozenset(\n [\n "for",\n "if",\n "block",\n "extends",\n "print",\n "macro",\n "include",\n "from",\n "import",\n "set",\n "with",\n "autoescape",\n ]\n)\n_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])\n\n_math_nodes: t.Dict[str, t.Type[nodes.Expr]] = {\n "add": nodes.Add,\n "sub": nodes.Sub,\n "mul": nodes.Mul,\n "div": nodes.Div,\n "floordiv": nodes.FloorDiv,\n "mod": nodes.Mod,\n}\n\n\nclass Parser:\n """This is the central parsing class Jinja uses. It's passed to\n extensions and can be used to parse expressions or statements.\n """\n\n def __init__(\n self,\n environment: "Environment",\n source: str,\n name: t.Optional[str] = None,\n filename: t.Optional[str] = None,\n state: t.Optional[str] = None,\n ) -> None:\n self.environment = environment\n self.stream = environment._tokenize(source, name, filename, state)\n self.name = name\n self.filename = filename\n self.closed = False\n self.extensions: t.Dict[\n str, t.Callable[[Parser], t.Union[nodes.Node, t.List[nodes.Node]]]\n ] = {}\n for extension in environment.iter_extensions():\n for tag in extension.tags:\n self.extensions[tag] = extension.parse\n self._last_identifier = 0\n self._tag_stack: t.List[str] = []\n self._end_token_stack: t.List[t.Tuple[str, ...]] = []\n\n def fail(\n self,\n msg: str,\n lineno: t.Optional[int] = None,\n exc: t.Type[TemplateSyntaxError] = TemplateSyntaxError,\n ) -> "te.NoReturn":\n """Convenience method that raises `exc` with the message, passed\n line number or last line number as well as the current name and\n filename.\n """\n if lineno is None:\n lineno = self.stream.current.lineno\n raise exc(msg, lineno, self.name, self.filename)\n\n def _fail_ut_eof(\n self,\n name: t.Optional[str],\n end_token_stack: t.List[t.Tuple[str, ...]],\n lineno: t.Optional[int],\n ) -> "te.NoReturn":\n expected: t.Set[str] = set()\n for exprs in end_token_stack:\n expected.update(map(describe_token_expr, exprs))\n if end_token_stack:\n currently_looking: t.Optional[str] = " or ".join(\n map(repr, map(describe_token_expr, end_token_stack[-1]))\n )\n else:\n currently_looking = None\n\n if name is None:\n message = ["Unexpected end of template."]\n else:\n message = [f"Encountered unknown tag {name!r}."]\n\n if currently_looking:\n if name is not None and name in expected:\n message.append(\n "You probably made a nesting mistake. Jinja is expecting this tag,"\n f" but currently looking for {currently_looking}."\n )\n else:\n message.append(\n f"Jinja was looking for the following tags: {currently_looking}."\n )\n\n if self._tag_stack:\n message.append(\n "The innermost block that needs to be closed is"\n f" {self._tag_stack[-1]!r}."\n )\n\n self.fail(" ".join(message), lineno)\n\n def fail_unknown_tag(\n self, name: str, lineno: t.Optional[int] = None\n ) -> "te.NoReturn":\n """Called if the parser encounters an unknown tag. Tries to fail\n with a human readable error message that could help to identify\n the problem.\n """\n self._fail_ut_eof(name, self._end_token_stack, lineno)\n\n def fail_eof(\n self,\n end_tokens: t.Optional[t.Tuple[str, ...]] = None,\n lineno: t.Optional[int] = None,\n ) -> "te.NoReturn":\n """Like fail_unknown_tag but for end of template situations."""\n stack = list(self._end_token_stack)\n if end_tokens is not None:\n stack.append(end_tokens)\n self._fail_ut_eof(None, stack, lineno)\n\n def is_tuple_end(\n self, extra_end_rules: t.Optional[t.Tuple[str, ...]] = None\n ) -> bool:\n """Are we at the end of a tuple?"""\n if self.stream.current.type in ("variable_end", "block_end", "rparen"):\n return True\n elif extra_end_rules is not None:\n return self.stream.current.test_any(extra_end_rules) # type: ignore\n return False\n\n def free_identifier(self, lineno: t.Optional[int] = None) -> nodes.InternalName:\n """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""\n self._last_identifier += 1\n rv = object.__new__(nodes.InternalName)\n nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)\n return rv\n\n def parse_statement(self) -> t.Union[nodes.Node, t.List[nodes.Node]]:\n """Parse a single statement."""\n token = self.stream.current\n if token.type != "name":\n self.fail("tag name expected", token.lineno)\n self._tag_stack.append(token.value)\n pop_tag = True\n try:\n if token.value in _statement_keywords:\n f = getattr(self, f"parse_{self.stream.current.value}")\n return f() # type: ignore\n if token.value == "call":\n return self.parse_call_block()\n if token.value == "filter":\n return self.parse_filter_block()\n ext = self.extensions.get(token.value)\n if ext is not None:\n return ext(self)\n\n # did not work out, remove the token we pushed by accident\n # from the stack so that the unknown tag fail function can\n # produce a proper error message.\n self._tag_stack.pop()\n pop_tag = False\n self.fail_unknown_tag(token.value, token.lineno)\n finally:\n if pop_tag:\n self._tag_stack.pop()\n\n def parse_statements(\n self, end_tokens: t.Tuple[str, ...], drop_needle: bool = False\n ) -> t.List[nodes.Node]:\n """Parse multiple statements into a list until one of the end tokens\n is reached. This is used to parse the body of statements as it also\n parses template data if appropriate. The parser checks first if the\n current token is a colon and skips it if there is one. Then it checks\n for the block end and parses until if one of the `end_tokens` is\n reached. Per default the active token in the stream at the end of\n the call is the matched end token. If this is not wanted `drop_needle`\n can be set to `True` and the end token is removed.\n """\n # the first token may be a colon for python compatibility\n self.stream.skip_if("colon")\n\n # in the future it would be possible to add whole code sections\n # by adding some sort of end of statement token and parsing those here.\n self.stream.expect("block_end")\n result = self.subparse(end_tokens)\n\n # we reached the end of the template too early, the subparser\n # does not check for this, so we do that now\n if self.stream.current.type == "eof":\n self.fail_eof(end_tokens)\n\n if drop_needle:\n next(self.stream)\n return result\n\n def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:\n """Parse an assign statement."""\n lineno = next(self.stream).lineno\n target = self.parse_assign_target(with_namespace=True)\n if self.stream.skip_if("assign"):\n expr = self.parse_tuple()\n return nodes.Assign(target, expr, lineno=lineno)\n filter_node = self.parse_filter(None)\n body = self.parse_statements(("name:endset",), drop_needle=True)\n return nodes.AssignBlock(target, filter_node, body, lineno=lineno)\n\n def parse_for(self) -> nodes.For:\n """Parse a for loop."""\n lineno = self.stream.expect("name:for").lineno\n target = self.parse_assign_target(extra_end_rules=("name:in",))\n self.stream.expect("name:in")\n iter = self.parse_tuple(\n with_condexpr=False, extra_end_rules=("name:recursive",)\n )\n test = None\n if self.stream.skip_if("name:if"):\n test = self.parse_expression()\n recursive = self.stream.skip_if("name:recursive")\n body = self.parse_statements(("name:endfor", "name:else"))\n if next(self.stream).value == "endfor":\n else_ = []\n else:\n else_ = self.parse_statements(("name:endfor",), drop_needle=True)\n return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)\n\n def parse_if(self) -> nodes.If:\n """Parse an if construct."""\n node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)\n while True:\n node.test = self.parse_tuple(with_condexpr=False)\n node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))\n node.elif_ = []\n node.else_ = []\n token = next(self.stream)\n if token.test("name:elif"):\n node = nodes.If(lineno=self.stream.current.lineno)\n result.elif_.append(node)\n continue\n elif token.test("name:else"):\n result.else_ = self.parse_statements(("name:endif",), drop_needle=True)\n break\n return result\n\n def parse_with(self) -> nodes.With:\n node = nodes.With(lineno=next(self.stream).lineno)\n targets: t.List[nodes.Expr] = []\n values: t.List[nodes.Expr] = []\n while self.stream.current.type != "block_end":\n if targets:\n self.stream.expect("comma")\n target = self.parse_assign_target()\n target.set_ctx("param")\n targets.append(target)\n self.stream.expect("assign")\n values.append(self.parse_expression())\n node.targets = targets\n node.values = values\n node.body = self.parse_statements(("name:endwith",), drop_needle=True)\n return node\n\n def parse_autoescape(self) -> nodes.Scope:\n node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)\n node.options = [nodes.Keyword("autoescape", self.parse_expression())]\n node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)\n return nodes.Scope([node])\n\n def parse_block(self) -> nodes.Block:\n node = nodes.Block(lineno=next(self.stream).lineno)\n node.name = self.stream.expect("name").value\n node.scoped = self.stream.skip_if("name:scoped")\n node.required = self.stream.skip_if("name:required")\n\n # common problem people encounter when switching from django\n # to jinja. we do not support hyphens in block names, so let's\n # raise a nicer error message in that case.\n if self.stream.current.type == "sub":\n self.fail(\n "Block names in Jinja have to be valid Python identifiers and may not"\n " contain hyphens, use an underscore instead."\n )\n\n node.body = self.parse_statements(("name:endblock",), drop_needle=True)\n\n # enforce that required blocks only contain whitespace or comments\n # by asserting that the body, if not empty, is just TemplateData nodes\n # with whitespace data\n if node.required:\n for body_node in node.body:\n if not isinstance(body_node, nodes.Output) or any(\n not isinstance(output_node, nodes.TemplateData)\n or not output_node.data.isspace()\n for output_node in body_node.nodes\n ):\n self.fail("Required blocks can only contain comments or whitespace")\n\n self.stream.skip_if("name:" + node.name)\n return node\n\n def parse_extends(self) -> nodes.Extends:\n node = nodes.Extends(lineno=next(self.stream).lineno)\n node.template = self.parse_expression()\n return node\n\n def parse_import_context(\n self, node: _ImportInclude, default: bool\n ) -> _ImportInclude:\n if self.stream.current.test_any(\n "name:with", "name:without"\n ) and self.stream.look().test("name:context"):\n node.with_context = next(self.stream).value == "with"\n self.stream.skip()\n else:\n node.with_context = default\n return node\n\n def parse_include(self) -> nodes.Include:\n node = nodes.Include(lineno=next(self.stream).lineno)\n node.template = self.parse_expression()\n if self.stream.current.test("name:ignore") and self.stream.look().test(\n "name:missing"\n ):\n node.ignore_missing = True\n self.stream.skip(2)\n else:\n node.ignore_missing = False\n return self.parse_import_context(node, True)\n\n def parse_import(self) -> nodes.Import:\n node = nodes.Import(lineno=next(self.stream).lineno)\n node.template = self.parse_expression()\n self.stream.expect("name:as")\n node.target = self.parse_assign_target(name_only=True).name\n return self.parse_import_context(node, False)\n\n def parse_from(self) -> nodes.FromImport:\n node = nodes.FromImport(lineno=next(self.stream).lineno)\n node.template = self.parse_expression()\n self.stream.expect("name:import")\n node.names = []\n\n def parse_context() -> bool:\n if self.stream.current.value in {\n "with",\n "without",\n } and self.stream.look().test("name:context"):\n node.with_context = next(self.stream).value == "with"\n self.stream.skip()\n return True\n return False\n\n while True:\n if node.names:\n self.stream.expect("comma")\n if self.stream.current.type == "name":\n if parse_context():\n break\n target = self.parse_assign_target(name_only=True)\n if target.name.startswith("_"):\n self.fail(\n "names starting with an underline can not be imported",\n target.lineno,\n exc=TemplateAssertionError,\n )\n if self.stream.skip_if("name:as"):\n alias = self.parse_assign_target(name_only=True)\n node.names.append((target.name, alias.name))\n else:\n node.names.append(target.name)\n if parse_context() or self.stream.current.type != "comma":\n break\n else:\n self.stream.expect("name")\n if not hasattr(node, "with_context"):\n node.with_context = False\n return node\n\n def parse_signature(self, node: _MacroCall) -> None:\n args = node.args = []\n defaults = node.defaults = []\n self.stream.expect("lparen")\n while self.stream.current.type != "rparen":\n if args:\n self.stream.expect("comma")\n arg = self.parse_assign_target(name_only=True)\n arg.set_ctx("param")\n if self.stream.skip_if("assign"):\n defaults.append(self.parse_expression())\n elif defaults:\n self.fail("non-default argument follows default argument")\n args.append(arg)\n self.stream.expect("rparen")\n\n def parse_call_block(self) -> nodes.CallBlock:\n node = nodes.CallBlock(lineno=next(self.stream).lineno)\n if self.stream.current.type == "lparen":\n self.parse_signature(node)\n else:\n node.args = []\n node.defaults = []\n\n call_node = self.parse_expression()\n if not isinstance(call_node, nodes.Call):\n self.fail("expected call", node.lineno)\n node.call = call_node\n node.body = self.parse_statements(("name:endcall",), drop_needle=True)\n return node\n\n def parse_filter_block(self) -> nodes.FilterBlock:\n node = nodes.FilterBlock(lineno=next(self.stream).lineno)\n node.filter = self.parse_filter(None, start_inline=True) # type: ignore\n node.body = self.parse_statements(("name:endfilter",), drop_needle=True)\n return node\n\n def parse_macro(self) -> nodes.Macro:\n node = nodes.Macro(lineno=next(self.stream).lineno)\n node.name = self.parse_assign_target(name_only=True).name\n self.parse_signature(node)\n node.body = self.parse_statements(("name:endmacro",), drop_needle=True)\n return node\n\n def parse_print(self) -> nodes.Output:\n node = nodes.Output(lineno=next(self.stream).lineno)\n node.nodes = []\n while self.stream.current.type != "block_end":\n if node.nodes:\n self.stream.expect("comma")\n node.nodes.append(self.parse_expression())\n return node\n\n @typing.overload\n def parse_assign_target(\n self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...\n ) -> nodes.Name: ...\n\n @typing.overload\n def parse_assign_target(\n self,\n with_tuple: bool = True,\n name_only: bool = False,\n extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,\n with_namespace: bool = False,\n ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...\n\n def parse_assign_target(\n self,\n with_tuple: bool = True,\n name_only: bool = False,\n extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,\n with_namespace: bool = False,\n ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:\n """Parse an assignment target. As Jinja allows assignments to\n tuples, this function can parse all allowed assignment targets. Per\n default assignments to tuples are parsed, that can be disable however\n by setting `with_tuple` to `False`. If only assignments to names are\n wanted `name_only` can be set to `True`. The `extra_end_rules`\n parameter is forwarded to the tuple parsing function. If\n `with_namespace` is enabled, a namespace assignment may be parsed.\n """\n target: nodes.Expr\n\n if name_only:\n token = self.stream.expect("name")\n target = nodes.Name(token.value, "store", lineno=token.lineno)\n else:\n if with_tuple:\n target = self.parse_tuple(\n simplified=True,\n extra_end_rules=extra_end_rules,\n with_namespace=with_namespace,\n )\n else:\n target = self.parse_primary(with_namespace=with_namespace)\n\n target.set_ctx("store")\n\n if not target.can_assign():\n self.fail(\n f"can't assign to {type(target).__name__.lower()!r}", target.lineno\n )\n\n return target # type: ignore\n\n def parse_expression(self, with_condexpr: bool = True) -> nodes.Expr:\n """Parse an expression. Per default all expressions are parsed, if\n the optional `with_condexpr` parameter is set to `False` conditional\n expressions are not parsed.\n """\n if with_condexpr:\n return self.parse_condexpr()\n return self.parse_or()\n\n def parse_condexpr(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n expr1 = self.parse_or()\n expr3: t.Optional[nodes.Expr]\n\n while self.stream.skip_if("name:if"):\n expr2 = self.parse_or()\n if self.stream.skip_if("name:else"):\n expr3 = self.parse_condexpr()\n else:\n expr3 = None\n expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)\n lineno = self.stream.current.lineno\n return expr1\n\n def parse_or(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n left = self.parse_and()\n while self.stream.skip_if("name:or"):\n right = self.parse_and()\n left = nodes.Or(left, right, lineno=lineno)\n lineno = self.stream.current.lineno\n return left\n\n def parse_and(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n left = self.parse_not()\n while self.stream.skip_if("name:and"):\n right = self.parse_not()\n left = nodes.And(left, right, lineno=lineno)\n lineno = self.stream.current.lineno\n return left\n\n def parse_not(self) -> nodes.Expr:\n if self.stream.current.test("name:not"):\n lineno = next(self.stream).lineno\n return nodes.Not(self.parse_not(), lineno=lineno)\n return self.parse_compare()\n\n def parse_compare(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n expr = self.parse_math1()\n ops = []\n while True:\n token_type = self.stream.current.type\n if token_type in _compare_operators:\n next(self.stream)\n ops.append(nodes.Operand(token_type, self.parse_math1()))\n elif self.stream.skip_if("name:in"):\n ops.append(nodes.Operand("in", self.parse_math1()))\n elif self.stream.current.test("name:not") and self.stream.look().test(\n "name:in"\n ):\n self.stream.skip(2)\n ops.append(nodes.Operand("notin", self.parse_math1()))\n else:\n break\n lineno = self.stream.current.lineno\n if not ops:\n return expr\n return nodes.Compare(expr, ops, lineno=lineno)\n\n def parse_math1(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n left = self.parse_concat()\n while self.stream.current.type in ("add", "sub"):\n cls = _math_nodes[self.stream.current.type]\n next(self.stream)\n right = self.parse_concat()\n left = cls(left, right, lineno=lineno)\n lineno = self.stream.current.lineno\n return left\n\n def parse_concat(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n args = [self.parse_math2()]\n while self.stream.current.type == "tilde":\n next(self.stream)\n args.append(self.parse_math2())\n if len(args) == 1:\n return args[0]\n return nodes.Concat(args, lineno=lineno)\n\n def parse_math2(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n left = self.parse_pow()\n while self.stream.current.type in ("mul", "div", "floordiv", "mod"):\n cls = _math_nodes[self.stream.current.type]\n next(self.stream)\n right = self.parse_pow()\n left = cls(left, right, lineno=lineno)\n lineno = self.stream.current.lineno\n return left\n\n def parse_pow(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n left = self.parse_unary()\n while self.stream.current.type == "pow":\n next(self.stream)\n right = self.parse_unary()\n left = nodes.Pow(left, right, lineno=lineno)\n lineno = self.stream.current.lineno\n return left\n\n def parse_unary(self, with_filter: bool = True) -> nodes.Expr:\n token_type = self.stream.current.type\n lineno = self.stream.current.lineno\n node: nodes.Expr\n\n if token_type == "sub":\n next(self.stream)\n node = nodes.Neg(self.parse_unary(False), lineno=lineno)\n elif token_type == "add":\n next(self.stream)\n node = nodes.Pos(self.parse_unary(False), lineno=lineno)\n else:\n node = self.parse_primary()\n node = self.parse_postfix(node)\n if with_filter:\n node = self.parse_filter_expr(node)\n return node\n\n def parse_primary(self, with_namespace: bool = False) -> nodes.Expr:\n """Parse a name or literal value. If ``with_namespace`` is enabled, also\n parse namespace attr refs, for use in assignments."""\n token = self.stream.current\n node: nodes.Expr\n if token.type == "name":\n next(self.stream)\n if token.value in ("true", "false", "True", "False"):\n node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)\n elif token.value in ("none", "None"):\n node = nodes.Const(None, lineno=token.lineno)\n elif with_namespace and self.stream.current.type == "dot":\n # If namespace attributes are allowed at this point, and the next\n # token is a dot, produce a namespace reference.\n next(self.stream)\n attr = self.stream.expect("name")\n node = nodes.NSRef(token.value, attr.value, lineno=token.lineno)\n else:\n node = nodes.Name(token.value, "load", lineno=token.lineno)\n elif token.type == "string":\n next(self.stream)\n buf = [token.value]\n lineno = token.lineno\n while self.stream.current.type == "string":\n buf.append(self.stream.current.value)\n next(self.stream)\n node = nodes.Const("".join(buf), lineno=lineno)\n elif token.type in ("integer", "float"):\n next(self.stream)\n node = nodes.Const(token.value, lineno=token.lineno)\n elif token.type == "lparen":\n next(self.stream)\n node = self.parse_tuple(explicit_parentheses=True)\n self.stream.expect("rparen")\n elif token.type == "lbracket":\n node = self.parse_list()\n elif token.type == "lbrace":\n node = self.parse_dict()\n else:\n self.fail(f"unexpected {describe_token(token)!r}", token.lineno)\n return node\n\n def parse_tuple(\n self,\n simplified: bool = False,\n with_condexpr: bool = True,\n extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,\n explicit_parentheses: bool = False,\n with_namespace: bool = False,\n ) -> t.Union[nodes.Tuple, nodes.Expr]:\n """Works like `parse_expression` but if multiple expressions are\n delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.\n This method could also return a regular expression instead of a tuple\n if no commas where found.\n\n The default parsing mode is a full tuple. If `simplified` is `True`\n only names and literals are parsed; ``with_namespace`` allows namespace\n attr refs as well. The `no_condexpr` parameter is forwarded to\n :meth:`parse_expression`.\n\n Because tuples do not require delimiters and may end in a bogus comma\n an extra hint is needed that marks the end of a tuple. For example\n for loops support tuples between `for` and `in`. In that case the\n `extra_end_rules` is set to ``['name:in']``.\n\n `explicit_parentheses` is true if the parsing was triggered by an\n expression in parentheses. This is used to figure out if an empty\n tuple is a valid expression or not.\n """\n lineno = self.stream.current.lineno\n if simplified:\n\n def parse() -> nodes.Expr:\n return self.parse_primary(with_namespace=with_namespace)\n\n else:\n\n def parse() -> nodes.Expr:\n return self.parse_expression(with_condexpr=with_condexpr)\n\n args: t.List[nodes.Expr] = []\n is_tuple = False\n\n while True:\n if args:\n self.stream.expect("comma")\n if self.is_tuple_end(extra_end_rules):\n break\n args.append(parse())\n if self.stream.current.type == "comma":\n is_tuple = True\n else:\n break\n lineno = self.stream.current.lineno\n\n if not is_tuple:\n if args:\n return args[0]\n\n # if we don't have explicit parentheses, an empty tuple is\n # not a valid expression. This would mean nothing (literally\n # nothing) in the spot of an expression would be an empty\n # tuple.\n if not explicit_parentheses:\n self.fail(\n "Expected an expression,"\n f" got {describe_token(self.stream.current)!r}"\n )\n\n return nodes.Tuple(args, "load", lineno=lineno)\n\n def parse_list(self) -> nodes.List:\n token = self.stream.expect("lbracket")\n items: t.List[nodes.Expr] = []\n while self.stream.current.type != "rbracket":\n if items:\n self.stream.expect("comma")\n if self.stream.current.type == "rbracket":\n break\n items.append(self.parse_expression())\n self.stream.expect("rbracket")\n return nodes.List(items, lineno=token.lineno)\n\n def parse_dict(self) -> nodes.Dict:\n token = self.stream.expect("lbrace")\n items: t.List[nodes.Pair] = []\n while self.stream.current.type != "rbrace":\n if items:\n self.stream.expect("comma")\n if self.stream.current.type == "rbrace":\n break\n key = self.parse_expression()\n self.stream.expect("colon")\n value = self.parse_expression()\n items.append(nodes.Pair(key, value, lineno=key.lineno))\n self.stream.expect("rbrace")\n return nodes.Dict(items, lineno=token.lineno)\n\n def parse_postfix(self, node: nodes.Expr) -> nodes.Expr:\n while True:\n token_type = self.stream.current.type\n if token_type == "dot" or token_type == "lbracket":\n node = self.parse_subscript(node)\n # calls are valid both after postfix expressions (getattr\n # and getitem) as well as filters and tests\n elif token_type == "lparen":\n node = self.parse_call(node)\n else:\n break\n return node\n\n def parse_filter_expr(self, node: nodes.Expr) -> nodes.Expr:\n while True:\n token_type = self.stream.current.type\n if token_type == "pipe":\n node = self.parse_filter(node) # type: ignore\n elif token_type == "name" and self.stream.current.value == "is":\n node = self.parse_test(node)\n # calls are valid both after postfix expressions (getattr\n # and getitem) as well as filters and tests\n elif token_type == "lparen":\n node = self.parse_call(node)\n else:\n break\n return node\n\n def parse_subscript(\n self, node: nodes.Expr\n ) -> t.Union[nodes.Getattr, nodes.Getitem]:\n token = next(self.stream)\n arg: nodes.Expr\n\n if token.type == "dot":\n attr_token = self.stream.current\n next(self.stream)\n if attr_token.type == "name":\n return nodes.Getattr(\n node, attr_token.value, "load", lineno=token.lineno\n )\n elif attr_token.type != "integer":\n self.fail("expected name or number", attr_token.lineno)\n arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)\n return nodes.Getitem(node, arg, "load", lineno=token.lineno)\n if token.type == "lbracket":\n args: t.List[nodes.Expr] = []\n while self.stream.current.type != "rbracket":\n if args:\n self.stream.expect("comma")\n args.append(self.parse_subscribed())\n self.stream.expect("rbracket")\n if len(args) == 1:\n arg = args[0]\n else:\n arg = nodes.Tuple(args, "load", lineno=token.lineno)\n return nodes.Getitem(node, arg, "load", lineno=token.lineno)\n self.fail("expected subscript expression", token.lineno)\n\n def parse_subscribed(self) -> nodes.Expr:\n lineno = self.stream.current.lineno\n args: t.List[t.Optional[nodes.Expr]]\n\n if self.stream.current.type == "colon":\n next(self.stream)\n args = [None]\n else:\n node = self.parse_expression()\n if self.stream.current.type != "colon":\n return node\n next(self.stream)\n args = [node]\n\n if self.stream.current.type == "colon":\n args.append(None)\n elif self.stream.current.type not in ("rbracket", "comma"):\n args.append(self.parse_expression())\n else:\n args.append(None)\n\n if self.stream.current.type == "colon":\n next(self.stream)\n if self.stream.current.type not in ("rbracket", "comma"):\n args.append(self.parse_expression())\n else:\n args.append(None)\n else:\n args.append(None)\n\n return nodes.Slice(lineno=lineno, *args) # noqa: B026\n\n def parse_call_args(\n self,\n ) -> t.Tuple[\n t.List[nodes.Expr],\n t.List[nodes.Keyword],\n t.Optional[nodes.Expr],\n t.Optional[nodes.Expr],\n ]:\n token = self.stream.expect("lparen")\n args = []\n kwargs = []\n dyn_args = None\n dyn_kwargs = None\n require_comma = False\n\n def ensure(expr: bool) -> None:\n if not expr:\n self.fail("invalid syntax for function call expression", token.lineno)\n\n while self.stream.current.type != "rparen":\n if require_comma:\n self.stream.expect("comma")\n\n # support for trailing comma\n if self.stream.current.type == "rparen":\n break\n\n if self.stream.current.type == "mul":\n ensure(dyn_args is None and dyn_kwargs is None)\n next(self.stream)\n dyn_args = self.parse_expression()\n elif self.stream.current.type == "pow":\n ensure(dyn_kwargs is None)\n next(self.stream)\n dyn_kwargs = self.parse_expression()\n else:\n if (\n self.stream.current.type == "name"\n and self.stream.look().type == "assign"\n ):\n # Parsing a kwarg\n ensure(dyn_kwargs is None)\n key = self.stream.current.value\n self.stream.skip(2)\n value = self.parse_expression()\n kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))\n else:\n # Parsing an arg\n ensure(dyn_args is None and dyn_kwargs is None and not kwargs)\n args.append(self.parse_expression())\n\n require_comma = True\n\n self.stream.expect("rparen")\n return args, kwargs, dyn_args, dyn_kwargs\n\n def parse_call(self, node: nodes.Expr) -> nodes.Call:\n # The lparen will be expected in parse_call_args, but the lineno\n # needs to be recorded before the stream is advanced.\n token = self.stream.current\n args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()\n return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)\n\n def parse_filter(\n self, node: t.Optional[nodes.Expr], start_inline: bool = False\n ) -> t.Optional[nodes.Expr]:\n while self.stream.current.type == "pipe" or start_inline:\n if not start_inline:\n next(self.stream)\n token = self.stream.expect("name")\n name = token.value\n while self.stream.current.type == "dot":\n next(self.stream)\n name += "." + self.stream.expect("name").value\n if self.stream.current.type == "lparen":\n args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()\n else:\n args = []\n kwargs = []\n dyn_args = dyn_kwargs = None\n node = nodes.Filter(\n node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno\n )\n start_inline = False\n return node\n\n def parse_test(self, node: nodes.Expr) -> nodes.Expr:\n token = next(self.stream)\n if self.stream.current.test("name:not"):\n next(self.stream)\n negated = True\n else:\n negated = False\n name = self.stream.expect("name").value\n while self.stream.current.type == "dot":\n next(self.stream)\n name += "." + self.stream.expect("name").value\n dyn_args = dyn_kwargs = None\n kwargs: t.List[nodes.Keyword] = []\n if self.stream.current.type == "lparen":\n args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()\n elif self.stream.current.type in {\n "name",\n "string",\n "integer",\n "float",\n "lparen",\n "lbracket",\n "lbrace",\n } and not self.stream.current.test_any("name:else", "name:or", "name:and"):\n if self.stream.current.test("name:is"):\n self.fail("You cannot chain multiple tests with is")\n arg_node = self.parse_primary()\n arg_node = self.parse_postfix(arg_node)\n args = [arg_node]\n else:\n args = []\n node = nodes.Test(\n node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno\n )\n if negated:\n node = nodes.Not(node, lineno=token.lineno)\n return node\n\n def subparse(\n self, end_tokens: t.Optional[t.Tuple[str, ...]] = None\n ) -> t.List[nodes.Node]:\n body: t.List[nodes.Node] = []\n data_buffer: t.List[nodes.Node] = []\n add_data = data_buffer.append\n\n if end_tokens is not None:\n self._end_token_stack.append(end_tokens)\n\n def flush_data() -> None:\n if data_buffer:\n lineno = data_buffer[0].lineno\n body.append(nodes.Output(data_buffer[:], lineno=lineno))\n del data_buffer[:]\n\n try:\n while self.stream:\n token = self.stream.current\n if token.type == "data":\n if token.value:\n add_data(nodes.TemplateData(token.value, lineno=token.lineno))\n next(self.stream)\n elif token.type == "variable_begin":\n next(self.stream)\n add_data(self.parse_tuple(with_condexpr=True))\n self.stream.expect("variable_end")\n elif token.type == "block_begin":\n flush_data()\n next(self.stream)\n if end_tokens is not None and self.stream.current.test_any(\n *end_tokens\n ):\n return body\n rv = self.parse_statement()\n if isinstance(rv, list):\n body.extend(rv)\n else:\n body.append(rv)\n self.stream.expect("block_end")\n else:\n raise AssertionError("internal parsing error")\n\n flush_data()\n finally:\n if end_tokens is not None:\n self._end_token_stack.pop()\n return body\n\n def parse(self) -> nodes.Template:\n """Parse the whole template into a `Template` node."""\n result = nodes.Template(self.subparse(), lineno=1)\n result.set_environment(self.environment)\n return result\n | .venv\Lib\site-packages\jinja2\parser.py | parser.py | Python | 40,383 | 0.95 | 0.213537 | 0.031915 | awesome-app | 799 | 2024-05-31T14:53:56.069847 | BSD-3-Clause | false | 0252f3fec9a2e6def22d4c9ba0e7625d |
"""A sandbox layer that ensures unsafe operations cannot be performed.\nUseful when the template itself comes from an untrusted source.\n"""\n\nimport operator\nimport types\nimport typing as t\nfrom _string import formatter_field_name_split # type: ignore\nfrom collections import abc\nfrom collections import deque\nfrom functools import update_wrapper\nfrom string import Formatter\n\nfrom markupsafe import EscapeFormatter\nfrom markupsafe import Markup\n\nfrom .environment import Environment\nfrom .exceptions import SecurityError\nfrom .runtime import Context\nfrom .runtime import Undefined\n\nF = t.TypeVar("F", bound=t.Callable[..., t.Any])\n\n#: maximum number of items a range may produce\nMAX_RANGE = 100000\n\n#: Unsafe function attributes.\nUNSAFE_FUNCTION_ATTRIBUTES: t.Set[str] = set()\n\n#: Unsafe method attributes. Function attributes are unsafe for methods too.\nUNSAFE_METHOD_ATTRIBUTES: t.Set[str] = set()\n\n#: unsafe generator attributes.\nUNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}\n\n#: unsafe attributes on coroutines\nUNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}\n\n#: unsafe attributes on async generators\nUNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}\n\n_mutable_spec: t.Tuple[t.Tuple[t.Type[t.Any], t.FrozenSet[str]], ...] = (\n (\n abc.MutableSet,\n frozenset(\n [\n "add",\n "clear",\n "difference_update",\n "discard",\n "pop",\n "remove",\n "symmetric_difference_update",\n "update",\n ]\n ),\n ),\n (\n abc.MutableMapping,\n frozenset(["clear", "pop", "popitem", "setdefault", "update"]),\n ),\n (\n abc.MutableSequence,\n frozenset(\n ["append", "clear", "pop", "reverse", "insert", "sort", "extend", "remove"]\n ),\n ),\n (\n deque,\n frozenset(\n [\n "append",\n "appendleft",\n "clear",\n "extend",\n "extendleft",\n "pop",\n "popleft",\n "remove",\n "rotate",\n ]\n ),\n ),\n)\n\n\ndef safe_range(*args: int) -> range:\n """A range that can't generate ranges with a length of more than\n MAX_RANGE items.\n """\n rng = range(*args)\n\n if len(rng) > MAX_RANGE:\n raise OverflowError(\n "Range too big. The sandbox blocks ranges larger than"\n f" MAX_RANGE ({MAX_RANGE})."\n )\n\n return rng\n\n\ndef unsafe(f: F) -> F:\n """Marks a function or method as unsafe.\n\n .. code-block: python\n\n @unsafe\n def delete(self):\n pass\n """\n f.unsafe_callable = True # type: ignore\n return f\n\n\ndef is_internal_attribute(obj: t.Any, attr: str) -> bool:\n """Test if the attribute given is an internal python attribute. For\n example this function returns `True` for the `func_code` attribute of\n python objects. This is useful if the environment method\n :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.\n\n >>> from jinja2.sandbox import is_internal_attribute\n >>> is_internal_attribute(str, "mro")\n True\n >>> is_internal_attribute(str, "upper")\n False\n """\n if isinstance(obj, types.FunctionType):\n if attr in UNSAFE_FUNCTION_ATTRIBUTES:\n return True\n elif isinstance(obj, types.MethodType):\n if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:\n return True\n elif isinstance(obj, type):\n if attr == "mro":\n return True\n elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):\n return True\n elif isinstance(obj, types.GeneratorType):\n if attr in UNSAFE_GENERATOR_ATTRIBUTES:\n return True\n elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):\n if attr in UNSAFE_COROUTINE_ATTRIBUTES:\n return True\n elif hasattr(types, "AsyncGeneratorType") and isinstance(\n obj, types.AsyncGeneratorType\n ):\n if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:\n return True\n return attr.startswith("__")\n\n\ndef modifies_known_mutable(obj: t.Any, attr: str) -> bool:\n """This function checks if an attribute on a builtin mutable object\n (list, dict, set or deque) or the corresponding ABCs would modify it\n if called.\n\n >>> modifies_known_mutable({}, "clear")\n True\n >>> modifies_known_mutable({}, "keys")\n False\n >>> modifies_known_mutable([], "append")\n True\n >>> modifies_known_mutable([], "index")\n False\n\n If called with an unsupported object, ``False`` is returned.\n\n >>> modifies_known_mutable("foo", "upper")\n False\n """\n for typespec, unsafe in _mutable_spec:\n if isinstance(obj, typespec):\n return attr in unsafe\n return False\n\n\nclass SandboxedEnvironment(Environment):\n """The sandboxed environment. It works like the regular environment but\n tells the compiler to generate sandboxed code. Additionally subclasses of\n this environment may override the methods that tell the runtime what\n attributes or functions are safe to access.\n\n If the template tries to access insecure code a :exc:`SecurityError` is\n raised. However also other exceptions may occur during the rendering so\n the caller has to ensure that all exceptions are caught.\n """\n\n sandboxed = True\n\n #: default callback table for the binary operators. A copy of this is\n #: available on each instance of a sandboxed environment as\n #: :attr:`binop_table`\n default_binop_table: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {\n "+": operator.add,\n "-": operator.sub,\n "*": operator.mul,\n "/": operator.truediv,\n "//": operator.floordiv,\n "**": operator.pow,\n "%": operator.mod,\n }\n\n #: default callback table for the unary operators. A copy of this is\n #: available on each instance of a sandboxed environment as\n #: :attr:`unop_table`\n default_unop_table: t.Dict[str, t.Callable[[t.Any], t.Any]] = {\n "+": operator.pos,\n "-": operator.neg,\n }\n\n #: a set of binary operators that should be intercepted. Each operator\n #: that is added to this set (empty by default) is delegated to the\n #: :meth:`call_binop` method that will perform the operator. The default\n #: operator callback is specified by :attr:`binop_table`.\n #:\n #: The following binary operators are interceptable:\n #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``\n #:\n #: The default operation form the operator table corresponds to the\n #: builtin function. Intercepted calls are always slower than the native\n #: operator call, so make sure only to intercept the ones you are\n #: interested in.\n #:\n #: .. versionadded:: 2.6\n intercepted_binops: t.FrozenSet[str] = frozenset()\n\n #: a set of unary operators that should be intercepted. Each operator\n #: that is added to this set (empty by default) is delegated to the\n #: :meth:`call_unop` method that will perform the operator. The default\n #: operator callback is specified by :attr:`unop_table`.\n #:\n #: The following unary operators are interceptable: ``+``, ``-``\n #:\n #: The default operation form the operator table corresponds to the\n #: builtin function. Intercepted calls are always slower than the native\n #: operator call, so make sure only to intercept the ones you are\n #: interested in.\n #:\n #: .. versionadded:: 2.6\n intercepted_unops: t.FrozenSet[str] = frozenset()\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n self.globals["range"] = safe_range\n self.binop_table = self.default_binop_table.copy()\n self.unop_table = self.default_unop_table.copy()\n\n def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:\n """The sandboxed environment will call this method to check if the\n attribute of an object is safe to access. Per default all attributes\n starting with an underscore are considered private as well as the\n special attributes of internal python objects as returned by the\n :func:`is_internal_attribute` function.\n """\n return not (attr.startswith("_") or is_internal_attribute(obj, attr))\n\n def is_safe_callable(self, obj: t.Any) -> bool:\n """Check if an object is safely callable. By default callables\n are considered safe unless decorated with :func:`unsafe`.\n\n This also recognizes the Django convention of setting\n ``func.alters_data = True``.\n """\n return not (\n getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)\n )\n\n def call_binop(\n self, context: Context, operator: str, left: t.Any, right: t.Any\n ) -> t.Any:\n """For intercepted binary operator calls (:meth:`intercepted_binops`)\n this function is executed instead of the builtin operator. This can\n be used to fine tune the behavior of certain operators.\n\n .. versionadded:: 2.6\n """\n return self.binop_table[operator](left, right)\n\n def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:\n """For intercepted unary operator calls (:meth:`intercepted_unops`)\n this function is executed instead of the builtin operator. This can\n be used to fine tune the behavior of certain operators.\n\n .. versionadded:: 2.6\n """\n return self.unop_table[operator](arg)\n\n def getitem(\n self, obj: t.Any, argument: t.Union[str, t.Any]\n ) -> t.Union[t.Any, Undefined]:\n """Subscribe an object from sandboxed code."""\n try:\n return obj[argument]\n except (TypeError, LookupError):\n if isinstance(argument, str):\n try:\n attr = str(argument)\n except Exception:\n pass\n else:\n try:\n value = getattr(obj, attr)\n except AttributeError:\n pass\n else:\n fmt = self.wrap_str_format(value)\n if fmt is not None:\n return fmt\n if self.is_safe_attribute(obj, argument, value):\n return value\n return self.unsafe_undefined(obj, argument)\n return self.undefined(obj=obj, name=argument)\n\n def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:\n """Subscribe an object from sandboxed code and prefer the\n attribute. The attribute passed *must* be a bytestring.\n """\n try:\n value = getattr(obj, attribute)\n except AttributeError:\n try:\n return obj[attribute]\n except (TypeError, LookupError):\n pass\n else:\n fmt = self.wrap_str_format(value)\n if fmt is not None:\n return fmt\n if self.is_safe_attribute(obj, attribute, value):\n return value\n return self.unsafe_undefined(obj, attribute)\n return self.undefined(obj=obj, name=attribute)\n\n def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:\n """Return an undefined object for unsafe attributes."""\n return self.undefined(\n f"access to attribute {attribute!r} of"\n f" {type(obj).__name__!r} object is unsafe.",\n name=attribute,\n obj=obj,\n exc=SecurityError,\n )\n\n def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:\n """If the given value is a ``str.format`` or ``str.format_map`` method,\n return a new function than handles sandboxing. This is done at access\n rather than in :meth:`call`, so that calls made without ``call`` are\n also sandboxed.\n """\n if not isinstance(\n value, (types.MethodType, types.BuiltinMethodType)\n ) or value.__name__ not in ("format", "format_map"):\n return None\n\n f_self: t.Any = value.__self__\n\n if not isinstance(f_self, str):\n return None\n\n str_type: t.Type[str] = type(f_self)\n is_format_map = value.__name__ == "format_map"\n formatter: SandboxedFormatter\n\n if isinstance(f_self, Markup):\n formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)\n else:\n formatter = SandboxedFormatter(self)\n\n vformat = formatter.vformat\n\n def wrapper(*args: t.Any, **kwargs: t.Any) -> str:\n if is_format_map:\n if kwargs:\n raise TypeError("format_map() takes no keyword arguments")\n\n if len(args) != 1:\n raise TypeError(\n f"format_map() takes exactly one argument ({len(args)} given)"\n )\n\n kwargs = args[0]\n args = ()\n\n return str_type(vformat(f_self, args, kwargs))\n\n return update_wrapper(wrapper, value)\n\n def call(\n __self, # noqa: B902\n __context: Context,\n __obj: t.Any,\n *args: t.Any,\n **kwargs: t.Any,\n ) -> t.Any:\n """Call an object from sandboxed code."""\n\n # the double prefixes are to avoid double keyword argument\n # errors when proxying the call.\n if not __self.is_safe_callable(__obj):\n raise SecurityError(f"{__obj!r} is not safely callable")\n return __context.call(__obj, *args, **kwargs)\n\n\nclass ImmutableSandboxedEnvironment(SandboxedEnvironment):\n """Works exactly like the regular `SandboxedEnvironment` but does not\n permit modifications on the builtin mutable objects `list`, `set`, and\n `dict` by using the :func:`modifies_known_mutable` function.\n """\n\n def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:\n if not super().is_safe_attribute(obj, attr, value):\n return False\n\n return not modifies_known_mutable(obj, attr)\n\n\nclass SandboxedFormatter(Formatter):\n def __init__(self, env: Environment, **kwargs: t.Any) -> None:\n self._env = env\n super().__init__(**kwargs)\n\n def get_field(\n self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]\n ) -> t.Tuple[t.Any, str]:\n first, rest = formatter_field_name_split(field_name)\n obj = self.get_value(first, args, kwargs)\n for is_attr, i in rest:\n if is_attr:\n obj = self._env.getattr(obj, i)\n else:\n obj = self._env.getitem(obj, i)\n return obj, first\n\n\nclass SandboxedEscapeFormatter(SandboxedFormatter, EscapeFormatter):\n pass\n | .venv\Lib\site-packages\jinja2\sandbox.py | sandbox.py | Python | 15,009 | 0.95 | 0.172018 | 0.116848 | react-lib | 424 | 2024-10-20T21:21:37.752692 | MIT | false | 9278585c4f9429bdbaf6e9f47eccf289 |
"""Built-in template tests used with the ``is`` operator."""\n\nimport operator\nimport typing as t\nfrom collections import abc\nfrom numbers import Number\n\nfrom .runtime import Undefined\nfrom .utils import pass_environment\n\nif t.TYPE_CHECKING:\n from .environment import Environment\n\n\ndef test_odd(value: int) -> bool:\n """Return true if the variable is odd."""\n return value % 2 == 1\n\n\ndef test_even(value: int) -> bool:\n """Return true if the variable is even."""\n return value % 2 == 0\n\n\ndef test_divisibleby(value: int, num: int) -> bool:\n """Check if a variable is divisible by a number."""\n return value % num == 0\n\n\ndef test_defined(value: t.Any) -> bool:\n """Return true if the variable is defined:\n\n .. sourcecode:: jinja\n\n {% if variable is defined %}\n value of variable: {{ variable }}\n {% else %}\n variable is not defined\n {% endif %}\n\n See the :func:`default` filter for a simple way to set undefined\n variables.\n """\n return not isinstance(value, Undefined)\n\n\ndef test_undefined(value: t.Any) -> bool:\n """Like :func:`defined` but the other way round."""\n return isinstance(value, Undefined)\n\n\n@pass_environment\ndef test_filter(env: "Environment", value: str) -> bool:\n """Check if a filter exists by name. Useful if a filter may be\n optionally available.\n\n .. code-block:: jinja\n\n {% if 'markdown' is filter %}\n {{ value | markdown }}\n {% else %}\n {{ value }}\n {% endif %}\n\n .. versionadded:: 3.0\n """\n return value in env.filters\n\n\n@pass_environment\ndef test_test(env: "Environment", value: str) -> bool:\n """Check if a test exists by name. Useful if a test may be\n optionally available.\n\n .. code-block:: jinja\n\n {% if 'loud' is test %}\n {% if value is loud %}\n {{ value|upper }}\n {% else %}\n {{ value|lower }}\n {% endif %}\n {% else %}\n {{ value }}\n {% endif %}\n\n .. versionadded:: 3.0\n """\n return value in env.tests\n\n\ndef test_none(value: t.Any) -> bool:\n """Return true if the variable is none."""\n return value is None\n\n\ndef test_boolean(value: t.Any) -> bool:\n """Return true if the object is a boolean value.\n\n .. versionadded:: 2.11\n """\n return value is True or value is False\n\n\ndef test_false(value: t.Any) -> bool:\n """Return true if the object is False.\n\n .. versionadded:: 2.11\n """\n return value is False\n\n\ndef test_true(value: t.Any) -> bool:\n """Return true if the object is True.\n\n .. versionadded:: 2.11\n """\n return value is True\n\n\n# NOTE: The existing 'number' test matches booleans and floats\ndef test_integer(value: t.Any) -> bool:\n """Return true if the object is an integer.\n\n .. versionadded:: 2.11\n """\n return isinstance(value, int) and value is not True and value is not False\n\n\n# NOTE: The existing 'number' test matches booleans and integers\ndef test_float(value: t.Any) -> bool:\n """Return true if the object is a float.\n\n .. versionadded:: 2.11\n """\n return isinstance(value, float)\n\n\ndef test_lower(value: str) -> bool:\n """Return true if the variable is lowercased."""\n return str(value).islower()\n\n\ndef test_upper(value: str) -> bool:\n """Return true if the variable is uppercased."""\n return str(value).isupper()\n\n\ndef test_string(value: t.Any) -> bool:\n """Return true if the object is a string."""\n return isinstance(value, str)\n\n\ndef test_mapping(value: t.Any) -> bool:\n """Return true if the object is a mapping (dict etc.).\n\n .. versionadded:: 2.6\n """\n return isinstance(value, abc.Mapping)\n\n\ndef test_number(value: t.Any) -> bool:\n """Return true if the variable is a number."""\n return isinstance(value, Number)\n\n\ndef test_sequence(value: t.Any) -> bool:\n """Return true if the variable is a sequence. Sequences are variables\n that are iterable.\n """\n try:\n len(value)\n value.__getitem__ # noqa B018\n except Exception:\n return False\n\n return True\n\n\ndef test_sameas(value: t.Any, other: t.Any) -> bool:\n """Check if an object points to the same memory address than another\n object:\n\n .. sourcecode:: jinja\n\n {% if foo.attribute is sameas false %}\n the foo attribute really is the `False` singleton\n {% endif %}\n """\n return value is other\n\n\ndef test_iterable(value: t.Any) -> bool:\n """Check if it's possible to iterate over an object."""\n try:\n iter(value)\n except TypeError:\n return False\n\n return True\n\n\ndef test_escaped(value: t.Any) -> bool:\n """Check if the value is escaped."""\n return hasattr(value, "__html__")\n\n\ndef test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:\n """Check if value is in seq.\n\n .. versionadded:: 2.10\n """\n return value in seq\n\n\nTESTS = {\n "odd": test_odd,\n "even": test_even,\n "divisibleby": test_divisibleby,\n "defined": test_defined,\n "undefined": test_undefined,\n "filter": test_filter,\n "test": test_test,\n "none": test_none,\n "boolean": test_boolean,\n "false": test_false,\n "true": test_true,\n "integer": test_integer,\n "float": test_float,\n "lower": test_lower,\n "upper": test_upper,\n "string": test_string,\n "mapping": test_mapping,\n "number": test_number,\n "sequence": test_sequence,\n "iterable": test_iterable,\n "callable": callable,\n "sameas": test_sameas,\n "escaped": test_escaped,\n "in": test_in,\n "==": operator.eq,\n "eq": operator.eq,\n "equalto": operator.eq,\n "!=": operator.ne,\n "ne": operator.ne,\n ">": operator.gt,\n "gt": operator.gt,\n "greaterthan": operator.gt,\n "ge": operator.ge,\n ">=": operator.ge,\n "<": operator.lt,\n "lt": operator.lt,\n "lessthan": operator.lt,\n "<=": operator.le,\n "le": operator.le,\n}\n | .venv\Lib\site-packages\jinja2\tests.py | tests.py | Python | 5,926 | 0.95 | 0.21875 | 0.010811 | vue-tools | 111 | 2024-02-21T06:12:42.710436 | BSD-3-Clause | true | 78ef6eaf3dfd0cf803816f8aad3db67c |
"""Jinja is a template engine written in pure Python. It provides a\nnon-XML syntax that supports inline expressions and an optional\nsandboxed environment.\n"""\n\nfrom .bccache import BytecodeCache as BytecodeCache\nfrom .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache\nfrom .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache\nfrom .environment import Environment as Environment\nfrom .environment import Template as Template\nfrom .exceptions import TemplateAssertionError as TemplateAssertionError\nfrom .exceptions import TemplateError as TemplateError\nfrom .exceptions import TemplateNotFound as TemplateNotFound\nfrom .exceptions import TemplateRuntimeError as TemplateRuntimeError\nfrom .exceptions import TemplatesNotFound as TemplatesNotFound\nfrom .exceptions import TemplateSyntaxError as TemplateSyntaxError\nfrom .exceptions import UndefinedError as UndefinedError\nfrom .loaders import BaseLoader as BaseLoader\nfrom .loaders import ChoiceLoader as ChoiceLoader\nfrom .loaders import DictLoader as DictLoader\nfrom .loaders import FileSystemLoader as FileSystemLoader\nfrom .loaders import FunctionLoader as FunctionLoader\nfrom .loaders import ModuleLoader as ModuleLoader\nfrom .loaders import PackageLoader as PackageLoader\nfrom .loaders import PrefixLoader as PrefixLoader\nfrom .runtime import ChainableUndefined as ChainableUndefined\nfrom .runtime import DebugUndefined as DebugUndefined\nfrom .runtime import make_logging_undefined as make_logging_undefined\nfrom .runtime import StrictUndefined as StrictUndefined\nfrom .runtime import Undefined as Undefined\nfrom .utils import clear_caches as clear_caches\nfrom .utils import is_undefined as is_undefined\nfrom .utils import pass_context as pass_context\nfrom .utils import pass_environment as pass_environment\nfrom .utils import pass_eval_context as pass_eval_context\nfrom .utils import select_autoescape as select_autoescape\n\n__version__ = "3.1.6"\n | .venv\Lib\site-packages\jinja2\__init__.py | __init__.py | Python | 1,928 | 0.85 | 0 | 0 | python-kit | 769 | 2025-03-28T15:09:11.580978 | Apache-2.0 | false | 705561be599d620e6cb43360629c44f1 |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\async_utils.cpython-313.pyc | async_utils.cpython-313.pyc | Other | 5,063 | 0.8 | 0 | 0 | vue-tools | 98 | 2025-02-15T23:08:39.750362 | GPL-3.0 | false | 9656dfcf22b3e20403433b98c93e4c39 |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\bccache.cpython-313.pyc | bccache.cpython-313.pyc | Other | 19,377 | 0.95 | 0.12093 | 0 | python-kit | 324 | 2024-11-04T17:44:37.327877 | Apache-2.0 | false | e0278eb123720626549ef7802aa13b22 |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\compiler.cpython-313.pyc | compiler.cpython-313.pyc | Other | 105,657 | 0.75 | 0.055208 | 0.003632 | node-utils | 211 | 2023-11-20T05:45:26.912940 | MIT | false | 3df7446b404297368782af5917e604b1 |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\constants.cpython-313.pyc | constants.cpython-313.pyc | Other | 1,553 | 0.85 | 0.05 | 0 | node-utils | 525 | 2023-10-10T16:12:41.565357 | Apache-2.0 | false | 50f41d0372d3bfb631a1837babba08df |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\debug.cpython-313.pyc | debug.cpython-313.pyc | Other | 6,574 | 0.95 | 0.012048 | 0.025974 | python-kit | 838 | 2025-03-23T18:12:32.866268 | Apache-2.0 | false | d629dea2bd4b54982ade09a59dfcef9c |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\defaults.cpython-313.pyc | defaults.cpython-313.pyc | Other | 1,613 | 0.95 | 0 | 0 | vue-tools | 131 | 2025-02-19T14:11:45.167915 | GPL-3.0 | false | 3346a4ae2ac685d64e632e28853fe68b |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\environment.cpython-313.pyc | environment.cpython-313.pyc | Other | 74,825 | 0.75 | 0.085417 | 0.003619 | python-kit | 348 | 2024-10-14T01:45:27.618008 | BSD-3-Clause | false | b30084982366e9a7d023d434ce544aba |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\exceptions.cpython-313.pyc | exceptions.cpython-313.pyc | Other | 8,019 | 0.95 | 0.149425 | 0 | vue-tools | 619 | 2025-03-07T11:35:55.953317 | BSD-3-Clause | false | b50c03dfac595c59d534981efb3cfc65 |
\n\n | .venv\Lib\site-packages\jinja2\__pycache__\ext.cpython-313.pyc | ext.cpython-313.pyc | Other | 42,195 | 0.95 | 0.079186 | 0.025126 | python-kit | 167 | 2024-06-27T16:26:18.917349 | BSD-3-Clause | false | 1eb5ed9e7b1ba2b5b4b71a2e5e818b43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.