id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
29,800
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/mail/backends/base.pyi
import types from typing import Any, TypeVar, Type, Iterable, Optional from django.core.mail.message import EmailMessage _T = TypeVar("_T", bound="BaseEmailBackend") class BaseEmailBackend: def __init__(self, fail_silently: bool = ..., **kwargs: Any) -> None: ... def open(self) -> Optional[bool]: ... def close(self) -> None: ... def __enter__(self: _T) -> _T: ... def __exit__( self, exc_type: Type[BaseException], exc_value: BaseException, traceback: types.TracebackType ) -> None: ... def send_messages(self, email_messages: Iterable[EmailMessage]) -> int: ...
604
Python
.py
13
42.461538
101
0.656463
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,801
wsgi.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/handlers/wsgi.pyi
from io import BytesIO from typing import Any, Callable, Dict, Optional, Union from django.contrib.sessions.backends.base import SessionBase from django.core.handlers import base from django.http import HttpRequest from django.http.response import HttpResponse _Stream = Union[BytesIO, str] _WSGIEnviron = Dict[str, Any] class LimitedStream: stream: _Stream = ... remaining: int = ... buffer: bytes = ... buf_size: int = ... def __init__(self, stream: _Stream, limit: int, buf_size: int = ...) -> None: ... def read(self, size: Optional[int] = ...) -> bytes: ... def readline(self, size: Optional[int] = ...) -> bytes: ... class WSGIRequest(HttpRequest): environ: _WSGIEnviron = ... session: SessionBase encoding: Any = ... def __init__(self, environ: _WSGIEnviron) -> None: ... class WSGIHandler(base.BaseHandler): request_class: Any = ... def __init__(self, *args: Any, **kwargs: Any) -> None: ... def __call__(self, environ: _WSGIEnviron, start_response: Callable) -> HttpResponse: ... def get_path_info(environ: _WSGIEnviron) -> str: ... def get_script_name(environ: _WSGIEnviron) -> str: ... def get_bytes_from_wsgi(environ: _WSGIEnviron, key: str, default: str) -> bytes: ... def get_str_from_wsgi(environ: _WSGIEnviron, key: str, default: str) -> str: ...
1,325
Python
.py
29
42.551724
92
0.671318
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,802
exception.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/handlers/exception.pyi
from typing import Any, Callable from django.http.request import HttpRequest from django.http.response import HttpResponse from django.urls.resolvers import URLResolver def convert_exception_to_response(get_response: Callable) -> Callable: ... def response_for_exception(request: HttpRequest, exc: Exception) -> HttpResponse: ... def get_exception_response( request: HttpRequest, resolver: URLResolver, status_code: int, exception: Exception, sender: None = ... ) -> HttpResponse: ... def handle_uncaught_exception(request: Any, resolver: Any, exc_info: Any): ...
570
Python
.py
10
55.4
107
0.781362
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,803
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/handlers/base.pyi
from typing import Any, Callable from django.http.request import HttpRequest from django.http.response import HttpResponse, HttpResponseBase logger: Any class BaseHandler: def load_middleware(self) -> None: ... def make_view_atomic(self, view: Callable) -> Callable: ... def get_exception_response(self, request: Any, resolver: Any, status_code: Any, exception: Any): ... def get_response(self, request: HttpRequest) -> HttpResponseBase: ... def process_exception_by_middleware(self, exception: Exception, request: HttpRequest) -> HttpResponse: ...
572
Python
.py
10
53.9
110
0.751342
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,804
templates.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/templates.pyi
from typing import Any from django.core.management.base import BaseCommand class TemplateCommand(BaseCommand): url_schemes: Any = ... rewrite_template_suffixes: Any = ... app_or_project: Any = ... paths_to_remove: Any = ... verbosity: Any = ... def handle_template(self, template: Any, subdir: Any): ... def validate_name(self, name: Any, app_or_project: Any) -> None: ... def download(self, url: Any): ... def splitext(self, the_path: Any): ... def extract(self, filename: Any): ... def is_url(self, template: Any): ... def make_writeable(self, filename: Any) -> None: ...
624
Python
.py
15
37.266667
72
0.645799
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,805
utils.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/utils.pyi
from typing import List, Optional, Set, Tuple, Type from django.apps.config import AppConfig from django.db.models.base import Model def popen_wrapper(args: List[str], stdout_encoding: str = ...) -> Tuple[str, str, int]: ... def handle_extensions(extensions: List[str]) -> Set[str]: ... def find_command(cmd: str, path: Optional[str] = ..., pathext: Optional[str] = ...) -> Optional[str]: ... def get_random_secret_key(): ... def parse_apps_and_model_labels(labels: List[str]) -> Tuple[Set[Type[Model]], Set[AppConfig]]: ...
527
Python
.py
8
64.625
105
0.696325
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,806
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/__init__.pyi
from typing import Any, Dict, List, Tuple, Union from .base import BaseCommand as BaseCommand, CommandError as CommandError def find_commands(management_dir: str) -> List[str]: ... def load_command_class(app_name: str, name: str) -> BaseCommand: ... def get_commands() -> Dict[str, str]: ... def call_command(command_name: Union[Tuple[str], BaseCommand, str], *args: Any, **options: Any) -> str: ... class ManagementUtility: argv: List[str] = ... prog_name: str = ... settings_exception: None = ... def __init__(self, argv: List[str] = ...) -> None: ... def main_help_text(self, commands_only: bool = ...): ... def fetch_command(self, subcommand: str) -> BaseCommand: ... def autocomplete(self) -> None: ... def execute(self) -> None: ... def execute_from_command_line(argv: List[str] = ...) -> None: ...
841
Python
.py
16
49.3125
107
0.64799
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,807
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/base.pyi
from argparse import ArgumentParser, HelpFormatter, Namespace from io import StringIO, TextIOBase, TextIOWrapper from typing import Any, Callable, List, Optional, Union, Tuple from django.apps.config import AppConfig from django.core.management.color import Style class CommandError(Exception): ... class SystemCheckError(CommandError): ... class CommandParser(ArgumentParser): missing_args_message: None = ... called_from_command_line: bool = ... def __init__(self, **kwargs: Any) -> None: ... def error(self, message: str) -> Any: ... def handle_default_options(options: Namespace) -> None: ... def no_translations(handle_func: Callable) -> Callable: ... class DjangoHelpFormatter(HelpFormatter): ... class OutputWrapper(TextIOBase): @property def style_func(self): ... @style_func.setter def style_func(self, style_func: Callable[[str], str]): ... ending: str = ... def __init__( self, out: Union[StringIO, TextIOWrapper], style_func: Optional[Callable[[str], str]] = ..., ending: str = ... ) -> None: ... def __getattr__(self, name: str) -> Callable: ... def isatty(self) -> bool: ... def write( # type: ignore[override] self, msg: str, style_func: Optional[Callable[[str], str]] = ..., ending: Optional[str] = ... ) -> None: ... class BaseCommand: help: str = ... output_transaction: bool = ... requires_migrations_checks: bool = ... requires_system_checks: bool = ... base_stealth_options: Tuple[str, ...] = ... stealth_options: Tuple[str, ...] = ... stdout: OutputWrapper = ... stderr: OutputWrapper = ... style: Style = ... def __init__( self, stdout: Optional[StringIO] = ..., stderr: Optional[StringIO] = ..., no_color: bool = ..., force_color: bool = ..., ) -> None: ... def get_version(self) -> str: ... def create_parser(self, prog_name: str, subcommand: str, **kwargs: Any) -> CommandParser: ... def add_arguments(self, parser: CommandParser) -> None: ... def print_help(self, prog_name: str, subcommand: str) -> None: ... def run_from_argv(self, argv: List[str]) -> None: ... def execute(self, *args: Any, **options: Any) -> Any: ... def check( self, app_configs: Optional[List[AppConfig]] = ..., tags: Optional[List[str]] = ..., display_num_errors: bool = ..., include_deployment_checks: bool = ..., fail_level: int = ..., ) -> None: ... def check_migrations(self) -> None: ... def handle(self, *args: Any, **options: Any) -> Optional[str]: ... class AppCommand(BaseCommand): missing_args_message: str = ... def handle_app_config(self, app_config: Any, **options: Any) -> None: ... class LabelCommand(BaseCommand): label: str = ... missing_args_message: Any = ... def handle_label(self, label: Any, **options: Any) -> None: ...
2,922
Python
.py
69
37.333333
118
0.61955
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,808
color.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/color.pyi
def supports_color() -> bool: ... class Style: def ERROR(self, text: str) -> str: ... def SUCCESS(self, text: str) -> str: ... def WARNING(self, text: str) -> str: ... def NOTICE(self, text: str) -> str: ... def SQL_FIELD(self, text: str) -> str: ... def SQL_COLTYPE(self, text: str) -> str: ... def SQL_KEYWORD(self, text: str) -> str: ... def SQL_TABLE(self, text: str) -> str: ... def HTTP_INFO(self, text: str) -> str: ... def HTTP_SUCCESS(self, text: str) -> str: ... def HTTP_REDIRECT(self, text: str) -> str: ... def HTTP_NOT_MODIFIED(self, text: str) -> str: ... def HTTP_BAD_REQUEST(self, text: str) -> str: ... def HTTP_NOT_FOUND(self, text: str) -> str: ... def HTTP_SERVER_ERROR(self, text: str) -> str: ... def MIGRATE_HEADING(self, text: str) -> str: ... def MIGRATE_LABEL(self, text: str) -> str: ... def ERROR_OUTPUT(self, text: str) -> str: ... def make_style(config_string: str = ...) -> Style: ... def no_style() -> Style: ... def color_style() -> Style: ...
1,052
Python
.py
23
41.521739
54
0.570594
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,809
sql.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/sql.pyi
from typing import Any, List from django.core.management.color import Style def sql_flush( style: Style, connection: Any, only_django: bool = ..., reset_sequences: bool = ..., allow_cascade: bool = ... ) -> List[str]: ... def emit_pre_migrate_signal(verbosity: int, interactive: bool, db: str, **kwargs: Any) -> None: ... def emit_post_migrate_signal(verbosity: int, interactive: bool, db: str, **kwargs: Any) -> None: ...
429
Python
.py
7
59.428571
114
0.688095
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,810
dumpdata.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/commands/dumpdata.pyi
from django.core.management.base import BaseCommand class ProxyModelWarning(Warning): ... class Command(BaseCommand): ...
123
Python
.py
3
39.666667
51
0.815126
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,811
loaddata.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/commands/loaddata.pyi
import zipfile from typing import Iterable, List, Optional, Tuple from django.core.management.base import BaseCommand READ_STDIN: str = ... class Command(BaseCommand): missing_args_message: str = ... def loaddata(self, fixture_labels: Iterable[str]) -> None: ... def load_label(self, fixture_label: str) -> None: ... def find_fixtures(self, fixture_label: str) -> List[Optional[str]]: ... @property def fixture_dirs(self) -> List[str]: ... def parse_name(self, fixture_name: str) -> Tuple[str, str, str]: ... class SingleZipReader(zipfile.ZipFile): ... def humanize(dirname: str) -> str: ...
625
Python
.py
14
41.285714
75
0.688119
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,812
runserver.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/commands/runserver.pyi
from django.core.management.base import BaseCommand class Command(BaseCommand): default_addr: str = ... default_addr_ipv6: str = ... default_port: int = ... protocol: str = ...
194
Python
.py
6
28.5
51
0.668449
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,813
makemessages.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/management/commands/makemessages.pyi
from typing import Any, Optional, Pattern, Type from django.core.management.base import BaseCommand plural_forms_re: Pattern = ... STATUS_OK: int = ... NO_LOCALE_DIR: Any = ... def check_programs(*programs: str) -> None: ... class TranslatableFile: dirpath: str file_name: str locale_dir: str def __init__(self, dirpath: str, file_name: str, locale_dir: Optional[str]) -> None: ... class BuildFile: """ Represent the state of a translatable file during the build process. """ def __init__(self, command: BaseCommand, domain: str, translatable: TranslatableFile) -> None: ... @property def is_templatized(self) -> bool: ... @property def path(self) -> str: ... @property def work_path(self) -> str: ... def preprocess(self) -> None: ... def postprocess_messages(self, msgs: str) -> str: ... def cleanup(self) -> None: ... def normalize_eols(raw_contents: str) -> str: ... def write_pot_file(potfile: str, msgs: str) -> None: ... class Command(BaseCommand): translatable_file_class: Type[TranslatableFile] = ... build_file_class: Type[BuildFile] = ...
1,134
Python
.py
30
34
102
0.661496
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,814
templates.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/templates.pyi
from typing import Any, List, Iterable, Optional from django.core.checks.messages import Error from django.apps.config import AppConfig E001: Any E002: Any def check_setting_app_dirs_loaders(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ... def check_string_if_invalid_is_string(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ...
391
Python
.py
7
54.285714
116
0.771053
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,815
model_checks.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/model_checks.pyi
from typing import Any, List, Iterable, Optional from django.core.checks.messages import Warning from django.apps.config import AppConfig def check_all_models(app_configs: Optional[Iterable[AppConfig]] = ..., **kwargs: Any) -> List[Warning]: ... def check_lazy_references(app_configs: Optional[Iterable[AppConfig]] = ..., **kwargs: Any) -> List[Any]: ...
358
Python
.py
5
70
108
0.742857
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,816
urls.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/urls.pyi
from typing import Any, Callable, List, Tuple, Union, Iterable, Optional from django.core.checks.messages import CheckMessage, Error, Warning from django.urls.resolvers import URLPattern, URLResolver from django.apps.config import AppConfig def check_url_config(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[CheckMessage]: ... def check_resolver(resolver: Union[Tuple[str, Callable], URLPattern, URLResolver]) -> List[CheckMessage]: ... def check_url_namespaces_unique(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def get_warning_for_invalid_pattern(pattern: Any) -> List[Error]: ... def check_url_settings(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ... def E006(name: str) -> Error: ...
780
Python
.py
10
76.7
112
0.757497
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,817
translation.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/translation.pyi
from typing import Any, List from . import Error E001: Error = ... def check_setting_language_code(app_configs: Any, **kwargs: Any) -> List[Error]: ...
155
Python
.py
4
37
84
0.709459
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,818
caches.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/caches.pyi
from typing import Any, List, Iterable, Optional from django.core.checks.messages import Error from django.apps.config import AppConfig E001: Any def check_default_cache_is_configured(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Error]: ...
267
Python
.py
5
51.6
116
0.794574
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,819
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/__init__.pyi
from .messages import ( CheckMessage as CheckMessage, Debug as Debug, Info as Info, Warning as Warning, Error as Error, Critical as Critical, DEBUG as DEBUG, INFO as INFO, WARNING as WARNING, ERROR as ERROR, CRITICAL as CRITICAL, ) from .registry import register as register, run_checks as run_checks, tag_exists as tag_exists, Tags as Tags from . import model_checks as model_checks
430
Python
.py
15
24.6
108
0.726392
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,820
registry.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/registry.pyi
from typing import Any, Callable, List, Optional, Set, Union from django.apps.config import AppConfig from django.core.checks.messages import CheckMessage class Tags: admin: str = ... caches: str = ... compatibility: str = ... database: str = ... models: str = ... security: str = ... signals: str = ... templates: str = ... translation: str = ... urls: str = ... class CheckRegistry: registered_checks: Set[Callable] = ... deployment_checks: Set[Callable] = ... def __init__(self) -> None: ... def register(self, check: Optional[Union[Callable, str]] = ..., *tags: Any, **kwargs: Any) -> Callable: ... def run_checks( self, app_configs: Optional[List[AppConfig]] = ..., tags: Optional[List[str]] = ..., include_deployment_checks: bool = ..., ) -> Union[List[CheckMessage], List[int], List[str]]: ... def tag_exists(self, tag: str, include_deployment_checks: bool = ...) -> bool: ... def tags_available(self, deployment_checks: bool = ...) -> Set[str]: ... def get_checks(self, include_deployment_checks: bool = ...) -> List[Callable]: ... registry: Any register: Any run_checks: Any tag_exists: Any
1,212
Python
.py
32
33.375
111
0.618197
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,821
database.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/database.pyi
from typing import Any, List def check_database_backends(*args: Any, **kwargs: Any) -> List[Any]: ...
103
Python
.py
2
50
72
0.7
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,822
messages.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/messages.pyi
from typing import Any, Optional DEBUG: int INFO: int WARNING: int ERROR: int CRITICAL: int class CheckMessage: level: int = ... msg: str = ... hint: Optional[str] = ... obj: Any = ... id: Optional[str] = ... def __init__( self, level: int, msg: str, hint: Optional[str] = ..., obj: Any = ..., id: Optional[str] = ... ) -> None: ... def is_serious(self, level: int = ...) -> bool: ... def is_silenced(self) -> bool: ... class Debug(CheckMessage): def __init__(self, *args: Any, **kwargs: Any) -> None: ... class Info(CheckMessage): def __init__(self, *args: Any, **kwargs: Any) -> None: ... class Warning(CheckMessage): def __init__(self, *args: Any, **kwargs: Any) -> None: ... class Error(CheckMessage): def __init__(self, *args: Any, **kwargs: Any) -> None: ... class Critical(CheckMessage): def __init__(self, *args: Any, **kwargs: Any) -> None: ...
925
Python
.py
27
30.62963
102
0.580247
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,823
csrf.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/security/csrf.pyi
from typing import Any, List, Iterable, Optional from django.core.checks.messages import Warning from django.apps.config import AppConfig W003: Any W016: Any def check_csrf_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_csrf_cookie_secure(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
379
Python
.py
7
52.571429
109
0.774457
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,824
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/security/base.pyi
from typing import Any, List, Iterable, Optional from django.core.checks.messages import Warning from django.apps.config import AppConfig SECRET_KEY_MIN_LENGTH: int SECRET_KEY_MIN_UNIQUE_CHARACTERS: int W001: Any W002: Any W004: Any W005: Any W006: Any W007: Any W008: Any W009: Any W018: Any W019: Any W020: Any W021: Any def check_security_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_xframe_options_middleware(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_sts(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_sts_include_subdomains(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_sts_preload(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_content_type_nosniff(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_xss_filter(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_ssl_redirect(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_secret_key(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_debug(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_xframe_deny(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_allowed_hosts(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
1,592
Python
.py
29
53.758621
116
0.74086
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,825
sessions.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/checks/security/sessions.pyi
from typing import Any, List, Iterable, Optional from django.core.checks.messages import Warning from django.apps.config import AppConfig def add_session_cookie_message(message: Any): ... W010: Any W011: Any W012: Any def add_httponly_message(message: Any): ... W013: Any W014: Any W015: Any def check_session_cookie_secure(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ... def check_session_cookie_httponly(app_configs: Optional[Iterable[AppConfig]], **kwargs: Any) -> List[Warning]: ...
527
Python
.py
13
39
114
0.769231
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,826
utils.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/utils.pyi
from typing import Any, Iterable, Optional TEMPLATE_FRAGMENT_KEY_TEMPLATE: str def make_template_fragment_key(fragment_name: str, vary_on: Optional[Iterable[Any]] = ...) -> str: ...
184
Python
.py
3
59.666667
102
0.748603
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,827
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/__init__.pyi
from collections import OrderedDict from typing import Any, Callable, Dict, Union from .backends.base import ( BaseCache as BaseCache, CacheKeyWarning as CacheKeyWarning, InvalidCacheBackendError as InvalidCacheBackendError, ) DEFAULT_CACHE_ALIAS: str class CacheHandler: def __init__(self) -> None: ... def __getitem__(self, alias: str) -> BaseCache: ... def all(self): ... class DefaultCacheProxy: def __getattr__(self, name: str) -> Union[Callable, Dict[str, float], OrderedDict, int]: ... def __setattr__(self, name: str, value: Callable) -> None: ... def __delattr__(self, name: Any): ... def __contains__(self, key: str) -> bool: ... cache: Any caches: CacheHandler
717
Python
.py
19
34.368421
96
0.688312
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,828
filebased.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/backends/filebased.pyi
from typing import Any, Dict from django.core.cache.backends.base import BaseCache class FileBasedCache(BaseCache): cache_suffix: str = ... def __init__(self, dir: str, params: Dict[str, Any]) -> None: ...
216
Python
.py
5
40.2
69
0.708134
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,829
dummy.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/backends/dummy.pyi
from typing import Any from django.core.cache.backends.base import BaseCache class DummyCache(BaseCache): def __init__(self, host: str, *args: Any, **kwargs: Any) -> None: ...
182
Python
.py
4
43
73
0.721591
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,830
locmem.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/backends/locmem.pyi
from typing import Any, Dict from django.core.cache.backends.base import BaseCache class LocMemCache(BaseCache): def __init__(self, name: str, params: Dict[str, Any]) -> None: ...
186
Python
.py
4
44
70
0.733333
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,831
memcached.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/backends/memcached.pyi
from django.core.cache.backends.base import BaseCache class BaseMemcachedCache(BaseCache): def __init__(self, server, params, library, value_not_found_exception) -> None: ... class MemcachedCache(BaseMemcachedCache): def __init__(self, server, params): ... class PyLibMCCache(BaseMemcachedCache): def __init__(self, server, params): ...
352
Python
.py
7
47.142857
87
0.736842
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,832
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/backends/base.pyi
from typing import Any, Callable, Dict, Iterable, List, Optional, Union from django.core.exceptions import ImproperlyConfigured class InvalidCacheBackendError(ImproperlyConfigured): ... class CacheKeyWarning(RuntimeWarning): ... DEFAULT_TIMEOUT: Any MEMCACHE_MAX_KEY_LENGTH: int def default_key_func(key: Any, key_prefix: str, version: Any) -> str: ... def get_key_func(key_func: Optional[Union[Callable, str]]) -> Callable: ... class BaseCache: default_timeout: int = ... key_prefix: str = ... version: int = ... key_func: Callable = ... def __init__(self, params: Dict[str, Any]) -> None: ... def get_backend_timeout(self, timeout: Any = ...) -> Optional[float]: ... def make_key(self, key: Any, version: Optional[Any] = ...) -> str: ... def add(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> bool: ... def get(self, key: Any, default: Optional[Any] = ..., version: Optional[Any] = ...) -> Any: ... def set(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> None: ... def touch(self, key: Any, timeout: Any = ..., version: Optional[Any] = ...) -> bool: ... def delete(self, key: Any, version: Optional[Any] = ...) -> None: ... def get_many(self, keys: List[str], version: Optional[int] = ...) -> Dict[str, Union[int, str]]: ... def get_or_set( self, key: Any, default: Optional[Any], timeout: Any = ..., version: Optional[int] = ... ) -> Optional[Any]: ... def has_key(self, key: Any, version: Optional[Any] = ...) -> bool: ... def incr(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... def decr(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... def __contains__(self, key: str) -> bool: ... def set_many(self, data: Dict[str, Any], timeout: Any = ..., version: Optional[Any] = ...) -> List[Any]: ... def delete_many(self, keys: Iterable[Any], version: Optional[Any] = ...) -> None: ... def clear(self) -> None: ... def validate_key(self, key: str) -> None: ... def incr_version(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... def decr_version(self, key: str, delta: int = ..., version: Optional[int] = ...) -> int: ... def close(self, **kwargs: Any) -> None: ...
2,327
Python
.py
36
60.388889
112
0.596238
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,833
db.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/cache/backends/db.pyi
from typing import Any, Dict from django.core.cache.backends.base import BaseCache class Options: db_table: str = ... app_label: str = ... model_name: str = ... verbose_name: str = ... verbose_name_plural: str = ... object_name: str = ... abstract: bool = ... managed: bool = ... proxy: bool = ... swapped: bool = ... def __init__(self, table: str) -> None: ... class BaseDatabaseCache(BaseCache): cache_model_class: Any = ... def __init__(self, table: str, params: Dict[str, Any]) -> None: ... class DatabaseCache(BaseDatabaseCache): ...
595
Python
.py
18
28.944444
71
0.61082
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,834
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/serializers/__init__.pyi
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Type, Union from django.db.models.base import Model from .base import ( DeserializationError as DeserializationError, DeserializedObject, Deserializer as Deserializer, M2MDeserializationError as M2MDeserializationError, SerializationError as SerializationError, Serializer as Serializer, SerializerDoesNotExist as SerializerDoesNotExist, ) BUILTIN_SERIALIZERS: Any class BadSerializer: internal_use_only: bool = ... exception: BaseException = ... def __init__(self, exception: BaseException) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def register_serializer(format: str, serializer_module: str, serializers: Optional[Dict[str, Any]] = ...) -> None: ... def unregister_serializer(format: str) -> None: ... def get_serializer(format: str) -> Union[Type[Serializer], BadSerializer]: ... def get_serializer_formats() -> List[str]: ... def get_public_serializer_formats() -> List[str]: ... def get_deserializer(format: str) -> Union[Callable, Type[Deserializer]]: ... def serialize(format: str, queryset: Iterable[Model], **options: Any) -> Any: ... def deserialize(format: str, stream_or_string: Any, **options: Any) -> Iterator[DeserializedObject]: ... def sort_dependencies(app_list: Iterable[Any]) -> List[Type[Model]]: ...
1,377
Python
.py
26
50.076923
118
0.728083
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,835
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/serializers/base.pyi
from datetime import date from io import BufferedReader, StringIO, TextIOWrapper from typing import Any, Dict, Iterable, List, Mapping, Optional, Type, Union, Collection from uuid import UUID from django.core.management.base import OutputWrapper from django.db.models.base import Model from django.db.models.fields.related import ForeignKey, ManyToManyField from django.db.models.fields import Field class SerializerDoesNotExist(KeyError): ... class SerializationError(Exception): ... class DeserializationError(Exception): @classmethod def WithData( cls, original_exc: Exception, model: str, fk: Union[int, str], field_value: Optional[Union[List[str], str]] ) -> DeserializationError: ... class M2MDeserializationError(Exception): original_exc: Exception = ... pk: List[str] = ... def __init__(self, original_exc: Exception, pk: Union[List[str], str]) -> None: ... class ProgressBar: progress_width: int = ... output: None = ... total_count: int = ... prev_done: int = ... def __init__(self, output: Optional[Union[StringIO, OutputWrapper]], total_count: int) -> None: ... def update(self, count: int) -> None: ... class Serializer: internal_use_only: bool = ... progress_class: Any = ... stream_class: Any = ... options: Dict[str, Any] = ... stream: Any = ... selected_fields: Optional[Collection[str]] = ... use_natural_foreign_keys: bool = ... use_natural_primary_keys: bool = ... first: bool = ... def serialize( self, queryset: Iterable[Model], *, stream: Optional[Any] = ..., fields: Optional[Collection[str]] = ..., use_natural_foreign_keys: bool = ..., use_natural_primary_keys: bool = ..., progress_output: Optional[Any] = ..., object_count: int = ..., **options: Any ) -> Any: ... def start_serialization(self) -> None: ... def end_serialization(self) -> None: ... def start_object(self, obj: Any) -> None: ... def end_object(self, obj: Any) -> None: ... def handle_field(self, obj: Any, field: Any) -> None: ... def handle_fk_field(self, obj: Any, field: Any) -> None: ... def handle_m2m_field(self, obj: Any, field: Any) -> None: ... def getvalue(self) -> Optional[Union[bytes, str]]: ... class Deserializer: options: Dict[str, Any] = ... stream: Any = ... def __init__(self, stream_or_string: Union[BufferedReader, TextIOWrapper, str], **options: Any) -> None: ... def __iter__(self) -> Deserializer: ... def __next__(self) -> None: ... class DeserializedObject: object: Any = ... m2m_data: Dict[str, List[int]] = ... deferred_fields: Mapping[Field, Any] def __init__( self, obj: Model, m2m_data: Optional[Dict[str, List[int]]] = ..., deferred_fields: Optional[Mapping[Field, Any]] = ..., ) -> None: ... def save(self, save_m2m: bool = ..., using: Optional[str] = ..., **kwargs: Any) -> None: ... def save_deferred_fields(self, using: Optional[str] = ...) -> None: ... def build_instance(Model: Type[Model], data: Dict[str, Optional[Union[date, int, str, UUID]]], db: str) -> Model: ... def deserialize_m2m_values(field: ManyToManyField, field_value: Any, using: str) -> List[Any]: ... def deserialize_fk_value(field: ForeignKey, field_value: Any, using: str) -> Any: ...
3,388
Python
.py
77
39.077922
117
0.632233
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,836
json.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/serializers/json.pyi
import json from typing import Any, Dict from django.core.serializers.python import Serializer as PythonSerializer class Serializer(PythonSerializer): json_kwargs: Dict[str, Any] def Deserializer(stream_or_string: Any, **options: Any) -> None: ... class DjangoJSONEncoder(json.JSONEncoder): allow_nan: bool check_circular: bool ensure_ascii: bool indent: int skipkeys: bool sort_keys: bool
422
Python
.py
13
29
73
0.762963
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,837
python.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/serializers/python.pyi
from collections import OrderedDict from typing import Any, Dict, Iterator, List, Optional from django.core.serializers.base import DeserializedObject from django.db.models.base import Model from django.core.serializers import base class Serializer(base.Serializer): objects: List[Any] = ... def get_dump_object(self, obj: Model) -> OrderedDict: ... def Deserializer( object_list: List[Dict[str, Any]], *, using: Optional[str] = ..., ignorenonexistent: bool = ..., **options: Any ) -> Iterator[DeserializedObject]: ...
535
Python
.py
11
46.181818
115
0.75
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,838
basehttp.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/core/servers/basehttp.pyi
import socketserver from io import BytesIO from typing import Any, Dict from wsgiref import simple_server from django.core.handlers.wsgi import WSGIRequest, WSGIHandler from django.core.wsgi import get_wsgi_application as get_wsgi_application # noqa: F401 class WSGIServer(simple_server.WSGIServer): request_queue_size: int = ... address_family: Any = ... allow_reuse_address: Any = ... def __init__(self, *args: Any, ipv6: bool = ..., allow_reuse_address: bool = ..., **kwargs: Any) -> None: ... def handle_error(self, request: Any, client_address: Any) -> None: ... class ThreadedWSGIServer(socketserver.ThreadingMixIn, WSGIServer): ... class ServerHandler(simple_server.ServerHandler): def handle_error(self) -> None: ... class WSGIRequestHandler(simple_server.WSGIRequestHandler): close_connection: bool connection: WSGIRequest request: WSGIRequest rfile: BytesIO wfile: BytesIO protocol_version: str = ... def address_string(self) -> str: ... def log_message(self, format: str, *args: Any) -> None: ... def get_environ(self) -> Dict[str, str]: ... raw_requestline: bytes = ... requestline: str = ... request_version: str = ... def handle(self) -> None: ... def get_internal_wsgi_application() -> WSGIHandler: ...
1,301
Python
.py
30
39.633333
113
0.698814
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,839
defaulttags.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/defaulttags.pyi
from collections import namedtuple from datetime import date from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from django.template.base import FilterExpression, Parser, Token from django.template.context import Context from django.utils.safestring import SafeText from .base import Node, NodeList from .library import Library from .smartif import IfParser, Literal register: Any class AutoEscapeControlNode(Node): nodelist: NodeList setting: bool def __init__(self, setting: bool, nodelist: NodeList) -> None: ... class CommentNode(Node): ... class CsrfTokenNode(Node): ... class CycleNode(Node): cyclevars: List[FilterExpression] = ... variable_name: Optional[str] = ... silent: bool = ... def __init__( self, cyclevars: List[FilterExpression], variable_name: Optional[str] = ..., silent: bool = ... ) -> None: ... def reset(self, context: Context) -> None: ... class DebugNode(Node): ... class FilterNode(Node): filter_expr: FilterExpression nodelist: NodeList def __init__(self, filter_expr: FilterExpression, nodelist: NodeList) -> None: ... class FirstOfNode(Node): vars: List[FilterExpression] = ... asvar: Optional[str] = ... def __init__(self, variables: List[FilterExpression], asvar: Optional[str] = ...) -> None: ... class ForNode(Node): loopvars: Union[List[str], str] sequence: Union[FilterExpression, str] child_nodelists: Any = ... is_reversed: bool = ... nodelist_loop: Union[List[str], NodeList] = ... nodelist_empty: Union[List[str], NodeList] = ... def __init__( self, loopvars: Union[List[str], str], sequence: Union[FilterExpression, str], is_reversed: bool, nodelist_loop: Union[List[str], NodeList], nodelist_empty: Optional[Union[List[str], NodeList]] = ..., ) -> None: ... class IfChangedNode(Node): nodelist_false: NodeList nodelist_true: NodeList child_nodelists: Any = ... def __init__(self, nodelist_true: NodeList, nodelist_false: NodeList, *varlist: Any) -> None: ... class IfEqualNode(Node): nodelist_false: Union[List[Any], NodeList] nodelist_true: Union[List[Any], NodeList] var1: Union[FilterExpression, str] var2: Union[FilterExpression, str] child_nodelists: Any = ... negate: bool = ... def __init__( self, var1: Union[FilterExpression, str], var2: Union[FilterExpression, str], nodelist_true: Union[List[Any], NodeList], nodelist_false: Union[List[Any], NodeList], negate: bool, ) -> None: ... class IfNode(Node): conditions_nodelists: List[Tuple[Optional[TemplateLiteral], NodeList]] = ... def __init__(self, conditions_nodelists: List[Tuple[Optional[TemplateLiteral], NodeList]]) -> None: ... def __iter__(self) -> None: ... @property def nodelist(self) -> NodeList: ... class LoremNode(Node): common: bool count: FilterExpression method: str def __init__(self, count: FilterExpression, method: str, common: bool) -> None: ... GroupedResult = namedtuple("GroupedResult", ["grouper", "list"]) class RegroupNode(Node): expression: FilterExpression target: FilterExpression var_name: str = ... def __init__(self, target: FilterExpression, expression: FilterExpression, var_name: str) -> None: ... def resolve_expression(self, obj: Dict[str, date], context: Context) -> Union[int, str]: ... class LoadNode(Node): ... class NowNode(Node): format_string: str = ... asvar: Optional[str] = ... def __init__(self, format_string: str, asvar: Optional[str] = ...) -> None: ... class ResetCycleNode(Node): node: CycleNode = ... def __init__(self, node: CycleNode) -> None: ... class SpacelessNode(Node): nodelist: NodeList = ... def __init__(self, nodelist: NodeList) -> None: ... class TemplateTagNode(Node): mapping: Any = ... tagtype: str = ... def __init__(self, tagtype: str) -> None: ... class URLNode(Node): view_name: FilterExpression = ... args: List[FilterExpression] = ... kwargs: Dict[str, FilterExpression] = ... asvar: Optional[str] = ... def __init__( self, view_name: FilterExpression, args: List[FilterExpression], kwargs: Dict[str, FilterExpression], asvar: Optional[str], ) -> None: ... class VerbatimNode(Node): content: SafeText = ... def __init__(self, content: SafeText) -> None: ... class WidthRatioNode(Node): val_expr: FilterExpression = ... max_expr: FilterExpression = ... max_width: FilterExpression = ... asvar: Optional[str] = ... def __init__( self, val_expr: FilterExpression, max_expr: FilterExpression, max_width: FilterExpression, asvar: Optional[str] = ..., ) -> None: ... class WithNode(Node): nodelist: NodeList = ... extra_context: Dict[str, Any] = ... def __init__( self, var: Optional[str], name: Optional[str], nodelist: Union[NodeList, Sequence[Node]], extra_context: Optional[Dict[str, Any]] = ..., ) -> None: ... def autoescape(parser: Parser, token: Token) -> AutoEscapeControlNode: ... def comment(parser: Parser, token: Token) -> CommentNode: ... def cycle(parser: Parser, token: Token) -> CycleNode: ... def csrf_token(parser: Parser, token: Token) -> CsrfTokenNode: ... def debug(parser: Parser, token: Token) -> DebugNode: ... def do_filter(parser: Parser, token: Token) -> FilterNode: ... def firstof(parser: Parser, token: Token) -> FirstOfNode: ... def do_for(parser: Parser, token: Token) -> ForNode: ... def do_ifequal(parser: Parser, token: Token, negate: bool) -> IfEqualNode: ... def ifequal(parser: Parser, token: Token) -> IfEqualNode: ... def ifnotequal(parser: Parser, token: Token) -> IfEqualNode: ... class TemplateLiteral(Literal): text: str = ... def __init__(self, value: FilterExpression, text: str) -> None: ... def display(self) -> str: ... class TemplateIfParser(IfParser): current_token: TemplateLiteral pos: int tokens: List[TemplateLiteral] error_class: Any = ... template_parser: Parser = ... def __init__(self, parser: Parser, *args: Any, **kwargs: Any) -> None: ... def do_if(parser: Parser, token: Token) -> IfNode: ... def ifchanged(parser: Parser, token: Token) -> IfChangedNode: ... def find_library(parser: Parser, name: str) -> Library: ... def load_from_library(library: Library, label: str, names: List[str]) -> Library: ... def load(parser: Parser, token: Token) -> LoadNode: ... def lorem(parser: Parser, token: Token) -> LoremNode: ... def now(parser: Parser, token: Token) -> NowNode: ... def regroup(parser: Parser, token: Token) -> RegroupNode: ... def resetcycle(parser: Parser, token: Token) -> ResetCycleNode: ... def spaceless(parser: Parser, token: Token) -> SpacelessNode: ... def templatetag(parser: Parser, token: Token) -> TemplateTagNode: ... def url(parser: Parser, token: Token) -> URLNode: ... def verbatim(parser: Parser, token: Token) -> VerbatimNode: ... def widthratio(parser: Parser, token: Token) -> WidthRatioNode: ... def do_with(parser: Parser, token: Token) -> WithNode: ...
7,237
Python
.py
175
36.942857
107
0.658609
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,840
response.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/response.pyi
import functools from http.cookies import SimpleCookie from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from django.core.handlers.wsgi import WSGIRequest from django.http.request import HttpRequest from django.template.base import Template from django.template.context import RequestContext from django.test.client import Client from django.http import HttpResponse class ContentNotRenderedError(Exception): ... class SimpleTemplateResponse(HttpResponse): content: Any = ... closed: bool cookies: SimpleCookie status_code: int rendering_attrs: Any = ... template_name: Union[List[str], Template, str] = ... context_data: Optional[Dict[str, Any]] = ... using: Optional[str] = ... def __init__( self, template: Union[List[str], Template, str], context: Optional[Dict[str, Any]] = ..., content_type: Optional[str] = ..., status: Optional[int] = ..., charset: Optional[str] = ..., using: Optional[str] = ..., ) -> None: ... def resolve_template(self, template: Union[Sequence[str], Template, str]) -> Template: ... def resolve_context(self, context: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: ... @property def rendered_content(self) -> str: ... def add_post_render_callback(self, callback: Callable) -> None: ... def render(self) -> SimpleTemplateResponse: ... @property def is_rendered(self) -> bool: ... def __iter__(self) -> Any: ... class TemplateResponse(SimpleTemplateResponse): client: Client closed: bool context: RequestContext context_data: Optional[Dict[str, Any]] cookies: SimpleCookie csrf_cookie_set: bool json: functools.partial redirect_chain: List[Tuple[str, int]] request: Dict[str, Union[int, str]] status_code: int template_name: Union[List[str], Template, str] templates: List[Template] using: Optional[str] wsgi_request: WSGIRequest rendering_attrs: Any = ... def __init__( self, request: HttpRequest, template: Union[List[str], Template, str], context: Optional[Dict[str, Any]] = ..., content_type: Optional[str] = ..., status: Optional[int] = ..., charset: None = ..., using: Optional[str] = ..., ) -> None: ...
2,344
Python
.py
63
31.936508
97
0.656854
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,841
library.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/library.pyi
from typing import Any, Callable, Dict, List, Optional, Tuple, Union from django.template.base import FilterExpression, Parser, Origin, Token from django.template.context import Context from django.utils.safestring import SafeText from .base import Node, Template class InvalidTemplateLibrary(Exception): ... class Library: filters: Dict[str, Callable] = ... tags: Dict[str, Callable] = ... def __init__(self) -> None: ... def tag( self, name: Optional[Union[Callable, str]] = ..., compile_function: Optional[Union[Callable, str]] = ... ) -> Callable: ... def tag_function(self, func: Callable) -> Callable: ... def filter( self, name: Optional[Union[Callable, str]] = ..., filter_func: Optional[Union[Callable, str]] = ..., **flags: Any ) -> Callable: ... def filter_function(self, func: Callable, **flags: Any) -> Callable: ... def simple_tag( self, func: Optional[Union[Callable, str]] = ..., takes_context: Optional[bool] = ..., name: Optional[str] = ... ) -> Callable: ... def inclusion_tag( self, filename: Union[Template, str], func: None = ..., takes_context: Optional[bool] = ..., name: Optional[str] = ..., ) -> Callable: ... class TagHelperNode(Node): func: Any = ... takes_context: Any = ... args: Any = ... kwargs: Any = ... def __init__( self, func: Callable, takes_context: Optional[bool], args: List[FilterExpression], kwargs: Dict[str, FilterExpression], ) -> None: ... def get_resolved_arguments(self, context: Context) -> Tuple[List[int], Dict[str, Union[SafeText, int]]]: ... class SimpleNode(TagHelperNode): args: List[FilterExpression] func: Callable kwargs: Dict[str, FilterExpression] origin: Origin takes_context: Optional[bool] token: Token target_var: Optional[str] = ... def __init__( self, func: Callable, takes_context: Optional[bool], args: List[FilterExpression], kwargs: Dict[str, FilterExpression], target_var: Optional[str], ) -> None: ... class InclusionNode(TagHelperNode): args: List[FilterExpression] func: Callable kwargs: Dict[str, FilterExpression] origin: Origin takes_context: Optional[bool] token: Token filename: Union[Template, str] = ... def __init__( self, func: Callable, takes_context: Optional[bool], args: List[FilterExpression], kwargs: Dict[str, FilterExpression], filename: Optional[Union[Template, str]], ) -> None: ... def parse_bits( parser: Parser, bits: List[str], params: List[str], varargs: Optional[str], varkw: Optional[str], defaults: Optional[Tuple[Union[bool, str]]], kwonly: List[str], kwonly_defaults: Optional[Dict[str, int]], takes_context: Optional[bool], name: str, ) -> Tuple[List[FilterExpression], Dict[str, FilterExpression]]: ... def import_library(name: str) -> Library: ...
3,079
Python
.py
89
28.831461
120
0.62609
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,842
utils.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/utils.pyi
import collections from typing import Any, Dict, List, Tuple from django.core.exceptions import ImproperlyConfigured from django.template.backends.base import BaseEngine class InvalidTemplateEngineError(ImproperlyConfigured): ... class EngineHandler: templates: collections.OrderedDict def __init__(self, templates: List[Dict[str, Any]] = ...) -> None: ... def __getitem__(self, alias: str) -> BaseEngine: ... def __iter__(self) -> Any: ... def all(self) -> List[BaseEngine]: ... def get_app_template_dirs(dirname: str) -> Tuple: ...
558
Python
.py
12
43.5
74
0.717712
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,843
loader.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/loader.pyi
from typing import Any, Dict, List, Optional, Union from . import engines as engines # noqa: F401 from django.http.request import HttpRequest from django.template.exceptions import TemplateDoesNotExist as TemplateDoesNotExist # noqa: F401 def get_template(template_name: str, using: Optional[str] = ...) -> Any: ... def select_template(template_name_list: Union[List[str], str], using: Optional[str] = ...) -> Any: ... def render_to_string( template_name: Union[List[str], str], context: Optional[Dict[str, Any]] = ..., request: Optional[HttpRequest] = ..., using: Optional[str] = ..., ) -> str: ...
620
Python
.py
12
49.166667
102
0.70132
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,844
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/__init__.pyi
from .engine import Engine as Engine from .utils import EngineHandler as EngineHandler engines: EngineHandler from .base import VariableDoesNotExist as VariableDoesNotExist from .context import ContextPopException as ContextPopException from .exceptions import TemplateDoesNotExist as TemplateDoesNotExist, TemplateSyntaxError as TemplateSyntaxError # Template parts from .base import Node as Node, NodeList as NodeList, Origin as Origin, Template as Template, Variable as Variable from .context import Context as Context, RequestContext as RequestContext from .library import Library as Library from . import defaultfilters as defaultfilters
648
Python
.py
11
57.454545
114
0.868671
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,845
context.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/context.pyi
from typing import Any, Callable, Dict, Iterator, List, Optional, Type, Union, Iterable from django.http.request import HttpRequest from django.template.base import Node, Origin, Template from django.template.defaulttags import IfChangedNode from django.template.loader_tags import IncludeNode _ContextValues = Union[Dict[str, Any], "Context"] class ContextPopException(Exception): ... class ContextDict(dict): context: BaseContext = ... def __init__(self, context: BaseContext, *args: Any, **kwargs: Any) -> None: ... def __enter__(self) -> ContextDict: ... def __exit__(self, *args: Any, **kwargs: Any) -> None: ... class BaseContext(Iterable[Any]): def __init__(self, dict_: Any = ...) -> None: ... def __copy__(self) -> BaseContext: ... def __iter__(self) -> Iterator[Any]: ... def push(self, *args: Any, **kwargs: Any) -> ContextDict: ... def pop(self) -> ContextDict: ... def __setitem__(self, key: Union[Node, str], value: Any) -> None: ... def set_upward(self, key: str, value: Union[int, str]) -> None: ... def __getitem__(self, key: Union[int, str]) -> Any: ... def __delitem__(self, key: Any) -> None: ... def __contains__(self, key: str) -> bool: ... def get(self, key: str, otherwise: Optional[Any] = ...) -> Optional[Any]: ... def setdefault( self, key: Union[IfChangedNode, str], default: Optional[Union[List[Origin], int]] = ... ) -> Optional[Union[List[Origin], int]]: ... def new(self, values: Optional[_ContextValues] = ...) -> Context: ... def flatten(self) -> Dict[str, Optional[Union[Dict[str, Union[Type[Any], str]], int, str]]]: ... class Context(BaseContext): dicts: Any autoescape: bool = ... use_l10n: Optional[bool] = ... use_tz: Optional[bool] = ... template_name: Optional[str] = ... render_context: RenderContext = ... template: Optional[Template] = ... def __init__( self, dict_: Any = ..., autoescape: bool = ..., use_l10n: Optional[bool] = ..., use_tz: None = ... ) -> None: ... def bind_template(self, template: Template) -> Iterator[None]: ... def update(self, other_dict: Union[Dict[str, Any], Context]) -> ContextDict: ... class RenderContext(BaseContext): dicts: List[Dict[Union[IncludeNode, str], str]] template: Optional[Template] = ... def push_state(self, template: Template, isolated_context: bool = ...) -> Iterator[None]: ... class RequestContext(Context): autoescape: bool dicts: List[Dict[str, str]] render_context: RenderContext template_name: Optional[str] use_l10n: None use_tz: None request: HttpRequest = ... def __init__( self, request: HttpRequest, dict_: Optional[Dict[str, Any]] = ..., processors: Optional[List[Callable]] = ..., use_l10n: None = ..., use_tz: None = ..., autoescape: bool = ..., ) -> None: ... template: Optional[Template] = ... def bind_template(self, template: Template) -> Iterator[None]: ... def new(self, values: Optional[_ContextValues] = ...) -> RequestContext: ... def make_context(context: Any, request: Optional[HttpRequest] = ..., **kwargs: Any) -> Context: ...
3,208
Python
.py
67
42.985075
106
0.621328
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,846
loader_tags.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/loader_tags.pyi
import collections from typing import Any, Dict, List, Optional, Union from django.template.base import FilterExpression, NodeList, Parser, Token, Origin from django.template.context import Context from django.utils.safestring import SafeText from .base import Node, Template register: Any BLOCK_CONTEXT_KEY: str class BlockContext: blocks: collections.defaultdict = ... def __init__(self) -> None: ... def add_blocks(self, blocks: Dict[str, BlockNode]) -> None: ... def pop(self, name: str) -> BlockNode: ... def push(self, name: str, block: BlockNode) -> None: ... def get_block(self, name: str) -> BlockNode: ... class BlockNode(Node): context: Context name: str nodelist: NodeList origin: Origin parent: None token: Token def __init__(self, name: str, nodelist: NodeList, parent: None = ...) -> None: ... def render(self, context: Context) -> SafeText: ... def super(self) -> SafeText: ... class ExtendsNode(Node): origin: Origin token: Token must_be_first: bool = ... context_key: str = ... nodelist: NodeList = ... parent_name: Union[FilterExpression, Node] = ... template_dirs: Optional[List[Any]] = ... blocks: Dict[str, BlockNode] = ... def __init__( self, nodelist: NodeList, parent_name: Union[FilterExpression, Node], template_dirs: Optional[List[Any]] = ... ) -> None: ... def find_template(self, template_name: str, context: Context) -> Template: ... def get_parent(self, context: Context) -> Template: ... def render(self, context: Context) -> Any: ... class IncludeNode(Node): origin: Origin token: Token context_key: str = ... template: FilterExpression = ... extra_context: Dict[str, FilterExpression] = ... isolated_context: bool = ... def __init__( self, template: FilterExpression, *args: Any, extra_context: Optional[Any] = ..., isolated_context: bool = ..., **kwargs: Any ) -> None: ... def render(self, context: Context) -> SafeText: ... def do_block(parser: Parser, token: Token) -> BlockNode: ... def construct_relative_path(current_template_name: Optional[str], relative_name: str) -> str: ... def do_extends(parser: Parser, token: Token) -> ExtendsNode: ... def do_include(parser: Parser, token: Token) -> IncludeNode: ...
2,363
Python
.py
60
34.85
118
0.652723
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,847
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/base.pyi
from enum import Enum from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union from django.http.request import HttpRequest from django.template.context import Context as Context from django.template.engine import Engine from django.template.library import Library from django.template.loaders.base import Loader from django.utils.safestring import SafeText FILTER_SEPARATOR: str FILTER_ARGUMENT_SEPARATOR: str VARIABLE_ATTRIBUTE_SEPARATOR: str BLOCK_TAG_START: str BLOCK_TAG_END: str VARIABLE_TAG_START: str VARIABLE_TAG_END: str COMMENT_TAG_START: str COMMENT_TAG_END: str TRANSLATOR_COMMENT_MARK: str SINGLE_BRACE_START: str SINGLE_BRACE_END: str UNKNOWN_SOURCE: str tag_re: Any logger: Any class TokenType(Enum): TEXT: int = ... VAR: int = ... BLOCK: int = ... COMMENT: int = ... class VariableDoesNotExist(Exception): msg: str = ... params: Tuple[Union[Dict[str, str], str]] = ... def __init__(self, msg: str, params: Tuple[Union[Dict[str, str], str]] = ...) -> None: ... class Origin: name: str = ... template_name: Optional[Union[bytes, str]] = ... loader: Optional[Loader] = ... def __init__( self, name: str, template_name: Optional[Union[bytes, str]] = ..., loader: Optional[Loader] = ... ) -> None: ... @property def loader_name(self) -> Optional[str]: ... class Template: name: Optional[str] = ... origin: Origin = ... engine: Engine = ... source: str = ... nodelist: NodeList = ... def __init__( self, template_string: Union[Template, str], origin: Optional[Origin] = ..., name: Optional[str] = ..., engine: Optional[Engine] = ..., ) -> None: ... def __iter__(self) -> None: ... def render( self, context: Optional[Union[Context, Dict[str, Any]]] = ..., request: Optional[HttpRequest] = ... ) -> Any: ... def compile_nodelist(self) -> NodeList: ... def get_exception_info(self, exception: Exception, token: Token) -> Dict[str, Any]: ... def linebreak_iter(template_source: str) -> Iterator[int]: ... class Token: contents: str token_type: TokenType lineno: Optional[int] = ... position: Optional[Tuple[int, int]] = ... def __init__( self, token_type: TokenType, contents: str, position: Optional[Tuple[int, int]] = ..., lineno: Optional[int] = ..., ) -> None: ... def split_contents(self) -> List[str]: ... class Lexer: template_string: str = ... verbatim: Union[bool, str] = ... def __init__(self, template_string: str) -> None: ... def tokenize(self) -> List[Token]: ... def create_token( self, token_string: str, position: Optional[Tuple[int, int]], lineno: int, in_tag: bool ) -> Token: ... class DebugLexer(Lexer): template_string: str verbatim: Union[bool, str] def tokenize(self) -> List[Token]: ... class Parser: tokens: Union[List[Token], str] = ... tags: Dict[str, Callable] = ... filters: Dict[str, Callable] = ... command_stack: List[Tuple[str, Token]] = ... libraries: Dict[str, Library] = ... origin: Optional[Origin] = ... def __init__( self, tokens: Union[List[Token], str], libraries: Optional[Dict[str, Library]] = ..., builtins: Optional[List[Library]] = ..., origin: Optional[Origin] = ..., ) -> None: ... def parse(self, parse_until: Optional[Tuple[str]] = ...) -> NodeList: ... def skip_past(self, endtag: str) -> None: ... def extend_nodelist(self, nodelist: NodeList, node: Node, token: Token) -> None: ... def error(self, token: Token, e: Union[Exception, str]) -> Exception: ... def invalid_block_tag(self, token: Token, command: str, parse_until: Union[List[Any], Tuple[str]] = ...) -> Any: ... def unclosed_block_tag(self, parse_until: Tuple[str]) -> Any: ... def next_token(self) -> Token: ... def prepend_token(self, token: Token) -> None: ... def delete_first_token(self) -> None: ... def add_library(self, lib: Library) -> None: ... def compile_filter(self, token: str) -> FilterExpression: ... def find_filter(self, filter_name: str) -> Callable: ... constant_string: Any filter_raw_string: Any filter_re: Any class FilterExpression: token: str = ... filters: List[Any] = ... var: Any = ... def __init__(self, token: str, parser: Parser) -> None: ... def resolve(self, context: Mapping[str, Any], ignore_failures: bool = ...) -> Any: ... @staticmethod def args_check(name: str, func: Callable, provided: List[Tuple[bool, Any]]) -> bool: ... class Variable: var: Union[Dict[Any, Any], str] = ... literal: Optional[Union[SafeText, float]] = ... lookups: Optional[Tuple[str]] = ... translate: bool = ... message_context: Optional[str] = ... def __init__(self, var: Union[Dict[Any, Any], str]) -> None: ... def resolve(self, context: Union[Mapping[str, Mapping[str, Any]], Context, int, str]) -> Any: ... class Node: must_be_first: bool = ... child_nodelists: Any = ... origin: Origin token: Token = ... def render(self, context: Context) -> str: ... def render_annotated(self, context: Context) -> Union[int, str]: ... def __iter__(self) -> None: ... def get_nodes_by_type(self, nodetype: Type[Node]) -> List[Node]: ... class NodeList(List[Node]): contains_nontext: bool = ... def render(self, context: Context) -> SafeText: ... def get_nodes_by_type(self, nodetype: Type[Node]) -> List[Node]: ... class TextNode(Node): s: str = ... def __init__(self, s: str) -> None: ... def render_value_in_context(value: Any, context: Context) -> str: ... class VariableNode(Node): filter_expression: FilterExpression = ... def __init__(self, filter_expression: FilterExpression) -> None: ... kwarg_re: Any def token_kwargs(bits: Sequence[str], parser: Parser, support_legacy: bool = ...) -> Dict[str, FilterExpression]: ...
6,030
Python
.py
153
34.954248
120
0.625854
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,848
smartif.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/smartif.pyi
from typing import Any, Dict, List, Optional, Union from django.template.defaulttags import TemplateLiteral _Token = Union[List[int], int, str] class TokenBase: id: Any = ... value: Any = ... first: Any = ... second: Any = ... def nud(self, parser: Any) -> None: ... def led(self, left: Any, parser: Any) -> None: ... def display(self): ... def infix(bp: Any, func: Any): ... def prefix(bp: Any, func: Any): ... OPERATORS: Any class Literal(TokenBase): id: str = ... lbp: int = ... value: Optional[_Token] = ... def __init__(self, value: Optional[_Token]) -> None: ... def display(self): ... def eval(self, context: Dict[Any, Any]) -> Optional[_Token]: ... class EndToken(TokenBase): lbp: int = ... def nud(self, parser: Any) -> None: ... class IfParser: error_class: Any = ... tokens: Any = ... pos: int = ... current_token: Any = ... def __init__(self, tokens: List[Optional[_Token]]) -> None: ... def translate_token(self, token: Optional[_Token]) -> Literal: ... def next_token(self) -> Literal: ... def parse(self) -> TemplateLiteral: ... def expression(self, rbp: int = ...) -> Literal: ... def create_var(self, value: Optional[_Token]) -> Literal: ...
1,267
Python
.py
35
32.114286
70
0.593954
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,849
engine.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/engine.pyi
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from django.template.base import Origin from django.template.library import Library from django.template.loaders.base import Loader from django.utils.safestring import SafeText from .base import Template _Loader = Any class Engine: template_context_processors: Tuple[Callable] template_loaders: List[Loader] default_builtins: Any = ... dirs: List[str] = ... app_dirs: bool = ... autoescape: bool = ... context_processors: Union[List[str], Tuple[str]] = ... debug: bool = ... loaders: Sequence[_Loader] = ... string_if_invalid: str = ... file_charset: str = ... libraries: Dict[str, str] = ... template_libraries: Dict[str, Library] = ... builtins: List[str] = ... template_builtins: List[Library] = ... def __init__( self, dirs: Optional[List[str]] = ..., app_dirs: bool = ..., context_processors: Optional[Union[List[str], Tuple[str]]] = ..., debug: bool = ..., loaders: Optional[Sequence[_Loader]] = ..., string_if_invalid: str = ..., file_charset: str = ..., libraries: Optional[Dict[str, str]] = ..., builtins: Optional[List[str]] = ..., autoescape: bool = ..., ) -> None: ... @staticmethod def get_default() -> Engine: ... def get_template_builtins(self, builtins: List[str]) -> List[Library]: ... def get_template_libraries(self, libraries: Dict[str, str]) -> Dict[str, Library]: ... def get_template_loaders(self, template_loaders: Sequence[_Loader]) -> List[Loader]: ... def find_template_loader(self, loader: _Loader) -> Loader: ... def find_template( self, name: str, dirs: None = ..., skip: Optional[List[Origin]] = ... ) -> Tuple[Template, Origin]: ... def from_string(self, template_code: str) -> Template: ... def get_template(self, template_name: str) -> Template: ... def render_to_string(self, template_name: str, context: Optional[Dict[str, Any]] = ...) -> SafeText: ... def select_template(self, template_name_list: List[str]) -> Template: ...
2,158
Python
.py
49
38.632653
108
0.624228
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,850
context_processors.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/context_processors.pyi
from typing import Any, Callable, Dict, List, Tuple, Union from django.core.handlers.wsgi import WSGIRequest from django.http.request import HttpRequest from django.utils.functional import SimpleLazyObject def csrf(request: HttpRequest) -> Dict[str, SimpleLazyObject]: ... def debug(request: HttpRequest) -> Dict[str, Union[Callable, bool]]: ... def i18n(request: WSGIRequest) -> Dict[str, Union[List[Tuple[str, str]], bool, str]]: ... def tz(request: HttpRequest) -> Dict[str, str]: ... def static(request: HttpRequest) -> Dict[str, str]: ... def media(request: Any): ... def request(request: HttpRequest) -> Dict[str, HttpRequest]: ...
640
Python
.py
11
57
89
0.740032
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,851
exceptions.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/exceptions.pyi
from typing import List, Optional, Tuple, Union from django.template.backends.base import BaseEngine from django.template.base import Origin class TemplateDoesNotExist(Exception): backend: Optional[BaseEngine] = ... tried: List[Tuple[Origin, str]] = ... chain: List[TemplateDoesNotExist] = ... def __init__( self, msg: Union[Origin, str], tried: Optional[List[Tuple[Origin, str]]] = ..., backend: Optional[BaseEngine] = ..., chain: Optional[List[TemplateDoesNotExist]] = ..., ) -> None: ... class TemplateSyntaxError(Exception): ...
596
Python
.py
15
34.533333
58
0.66955
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,852
defaultfilters.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/defaultfilters.pyi
from datetime import date as _date, datetime, time as _time from typing import Any, Callable, Dict, List, Optional, Union from django.utils.safestring import SafeText from django.utils.html import escape as escape # noqa: F401 register: Any def stringfilter(func: Callable) -> Callable: ... def addslashes(value: str) -> str: ... def capfirst(value: str) -> str: ... def escapejs_filter(value: str) -> SafeText: ... def json_script(value: Dict[str, str], element_id: SafeText) -> SafeText: ... def floatformat(text: Optional[Any], arg: Union[int, str] = ...) -> str: ... def iriencode(value: str) -> str: ... def linenumbers(value: str, autoescape: bool = ...) -> SafeText: ... def lower(value: str) -> str: ... def make_list(value: str) -> List[str]: ... def slugify(value: str) -> SafeText: ... def stringformat(value: Any, arg: str) -> str: ... def title(value: str) -> str: ... def truncatechars(value: str, arg: Union[SafeText, int]) -> str: ... def truncatechars_html(value: str, arg: Union[int, str]) -> str: ... def truncatewords(value: str, arg: Union[int, str]) -> str: ... def truncatewords_html(value: str, arg: Union[int, str]) -> str: ... def upper(value: str) -> str: ... def urlencode(value: str, safe: Optional[SafeText] = ...) -> str: ... def urlize(value: str, autoescape: bool = ...) -> SafeText: ... def urlizetrunc(value: str, limit: Union[SafeText, int], autoescape: bool = ...) -> SafeText: ... def wordcount(value: str) -> int: ... def wordwrap(value: str, arg: Union[SafeText, int]) -> str: ... def ljust(value: str, arg: Union[SafeText, int]) -> str: ... def rjust(value: str, arg: Union[SafeText, int]) -> str: ... def center(value: str, arg: Union[SafeText, int]) -> str: ... def cut(value: str, arg: str) -> str: ... def escape_filter(value: str) -> SafeText: ... def force_escape(value: str) -> SafeText: ... def linebreaks_filter(value: str, autoescape: bool = ...) -> SafeText: ... def linebreaksbr(value: str, autoescape: bool = ...) -> SafeText: ... def safe(value: str) -> SafeText: ... def safeseq(value: List[str]) -> List[SafeText]: ... def striptags(value: str) -> str: ... def dictsort(value: Any, arg: Union[int, str]) -> Any: ... def dictsortreversed(value: Any, arg: Union[int, str]) -> Any: ... def first(value: Any) -> Any: ... def join(value: Any, arg: str, autoescape: bool = ...) -> Any: ... def last(value: List[str]) -> str: ... def length(value: Any) -> int: ... def length_is(value: Optional[Any], arg: Union[SafeText, int]) -> Union[bool, str]: ... def random(value: List[str]) -> str: ... def slice_filter(value: Any, arg: Union[str, int]) -> Any: ... def unordered_list(value: Any, autoescape: bool = ...) -> Any: ... def add(value: Any, arg: Any) -> Any: ... def get_digit(value: Any, arg: int) -> Any: ... def date(value: Optional[Union[_date, datetime, str]], arg: Optional[str] = ...) -> str: ... def time(value: Optional[Union[datetime, _time, str]], arg: Optional[str] = ...) -> str: ... def timesince_filter(value: Optional[_date], arg: Optional[_date] = ...) -> str: ... def timeuntil_filter(value: Optional[_date], arg: Optional[_date] = ...) -> str: ... def default(value: Optional[Union[int, str]], arg: Union[int, str]) -> Union[int, str]: ... def default_if_none(value: Optional[str], arg: Union[int, str]) -> Union[int, str]: ... def divisibleby(value: int, arg: int) -> bool: ... def yesno(value: Optional[int], arg: Optional[str] = ...) -> Optional[Union[bool, str]]: ... def filesizeformat(bytes_: Union[complex, int, str]) -> str: ... def pluralize(value: Any, arg: str = ...) -> str: ... def phone2numeric_filter(value: str) -> str: ... def pprint(value: Any) -> str: ...
3,651
Python
.py
63
56.904762
97
0.646025
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,853
cached.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/loaders/cached.pyi
from typing import Any, Dict, List, Optional, Sequence from django.template.base import Origin from django.template.engine import Engine from .base import Loader as BaseLoader class Loader(BaseLoader): template_cache: Dict[str, Any] = ... loaders: List[BaseLoader] = ... def __init__(self, engine: Engine, loaders: Sequence[Any]) -> None: ... def get_contents(self, origin: Origin) -> str: ... def cache_key(self, template_name: str, skip: Optional[List[Origin]] = ...) -> str: ... def generate_hash(self, values: List[str]) -> str: ...
564
Python
.py
11
47.818182
91
0.687273
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,854
locmem.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/loaders/locmem.pyi
from typing import Dict from django.template.base import Origin from django.template.engine import Engine from .base import Loader as BaseLoader class Loader(BaseLoader): templates_dict: Dict[str, str] = ... def __init__(self, engine: Engine, templates_dict: Dict[str, str]) -> None: ... def get_contents(self, origin: Origin) -> str: ...
354
Python
.py
8
41.375
83
0.725948
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,855
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/loaders/base.pyi
from typing import Any, List, Optional, Dict from django.template.base import Origin, Template from django.template.engine import Engine class Loader: engine: Engine = ... get_template_cache: Dict[str, Any] = ... def __init__(self, engine: Engine) -> None: ... def get_template(self, template_name: str, skip: Optional[List[Origin]] = ...) -> Template: ... def get_template_sources(self, template_name: str) -> None: ... def reset(self) -> None: ...
476
Python
.py
10
44
99
0.672414
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,856
filesystem.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/loaders/filesystem.pyi
from typing import Any, List, Optional, Union from django.template.base import Origin from django.template.engine import Engine from .base import Loader as BaseLoader class Loader(BaseLoader): dirs: Optional[List[str]] = ... def __init__(self, engine: Engine, dirs: Optional[List[str]] = ...) -> None: ... def get_dirs(self) -> Union[List[bytes], List[str]]: ... def get_contents(self, origin: Origin) -> Any: ...
433
Python
.py
9
45
84
0.693587
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,857
utils.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/backends/utils.pyi
from typing import Any from django.http.request import HttpRequest from django.utils.safestring import SafeText def csrf_input(request: HttpRequest) -> SafeText: ... csrf_input_lazy: Any csrf_token_lazy: Any
211
Python
.py
6
33.666667
53
0.821782
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,858
jinja2.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/backends/jinja2.pyi
from typing import Any, Callable, Dict, List, Optional from django.template.exceptions import TemplateSyntaxError from .base import BaseEngine class Jinja2(BaseEngine): context_processors: List[str] = ... def __init__(self, params: Dict[str, Any]) -> None: ... @property def template_context_processors(self) -> List[Callable]: ... class Origin: name: str = ... template_name: Optional[str] = ... def __init__(self, name: str, template_name: Optional[str]) -> None: ... def get_exception_info(exception: TemplateSyntaxError) -> Dict[str, Any]: ...
581
Python
.py
13
41.153846
77
0.694494
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,859
dummy.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/backends/dummy.pyi
import string from typing import Any, Dict, List, Optional, Tuple, Union from django.http.request import HttpRequest from .base import BaseEngine class TemplateStrings(BaseEngine): template_dirs: Tuple[str] def __init__(self, params: Dict[str, Union[Dict[Any, Any], List[Any], bool, str]]) -> None: ... class Template(string.Template): template: str def render(self, context: Optional[Dict[str, str]] = ..., request: Optional[HttpRequest] = ...) -> str: ...
478
Python
.py
10
44.8
111
0.713362
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,860
base.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/backends/base.pyi
from typing import Any, Iterator, List, Mapping, Optional, Tuple from django.template.base import Template class BaseEngine: name: str = ... dirs: List[str] = ... app_dirs: bool = ... def __init__(self, params: Mapping[str, Any]) -> None: ... @property def app_dirname(self) -> Optional[str]: ... def from_string(self, template_code: str) -> Template: ... def get_template(self, template_name: str) -> Optional[Template]: ... @property def template_dirs(self) -> Tuple[str]: ... def iter_template_filenames(self, template_name: str) -> Iterator[str]: ...
601
Python
.py
14
38.642857
79
0.647863
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,861
django.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/template/backends/django.pyi
from typing import Any, Dict, Iterator, Optional from django.template.engine import Engine from django.template.exceptions import TemplateDoesNotExist from .base import BaseEngine class DjangoTemplates(BaseEngine): engine: Engine = ... def __init__(self, params: Dict[str, Any]) -> None: ... def get_templatetag_libraries(self, custom_libraries: Dict[str, str]) -> Dict[str, str]: ... def copy_exception(exc: TemplateDoesNotExist, backend: Optional[DjangoTemplates] = ...) -> TemplateDoesNotExist: ... def reraise(exc: TemplateDoesNotExist, backend: DjangoTemplates) -> Any: ... def get_installed_libraries() -> Dict[str, str]: ... def get_package_libraries(pkg: Any) -> Iterator[str]: ...
706
Python
.py
12
56.5
116
0.74058
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,862
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/conf/__init__.pyi
from typing import Any from django.utils.functional import LazyObject # explicit dependency on standard settings to make it loaded from . import global_settings ENVIRONMENT_VARIABLE: str = ... DEFAULT_CONTENT_TYPE_DEPRECATED_MSG: str = ... FILE_CHARSET_DEPRECATED_MSG: str = ... # required for plugin to be able to distinguish this specific instance of LazySettings from others class _DjangoConfLazyObject(LazyObject): def __getattr__(self, item: Any) -> Any: ... class LazySettings(_DjangoConfLazyObject): configured: bool def configure(self, default_settings: Any = ..., **options: Any) -> Any: ... settings: LazySettings = ... class Settings: def __init__(self, settings_module: str): ... def is_overridden(self, setting: str) -> bool: ... class UserSettingsHolder: ... class SettingsReference(str): def __init__(self, value: str, setting_name: str) -> None: ...
899
Python
.py
20
42.3
98
0.729885
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,863
global_settings.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/conf/global_settings.pyi
""" Default Django settings. Override these with settings in the module pointed to by the DJANGO_SETTINGS_MODULE environment variable. """ # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. from typing import Any, Dict, List, Optional, Pattern, Protocol, Sequence, Tuple, Union #################### # CORE # #################### DEBUG: bool = ... # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing situations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS: bool = ... # People who get code error notifications. # In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')] ADMINS: List[Tuple[str, str]] = ... # List of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS: List[str] = ... # Hosts/domain names that are valid for this site. # "*" matches anything, ".example.com" matches example.com and all subdomains ALLOWED_HOSTS: List[str] = ... # Local time zone for this installation. All choices can be found here: # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). When USE_TZ is True, this is # interpreted as the default user time zone. TIME_ZONE: str = ... # If you set this to True, Django will use timezone-aware datetimes. USE_TZ: bool = ... # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE: str = ... # Languages we provide translations for, out of the box. LANGUAGES: List[Tuple[str, str]] = ... # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI: List[str] = ... # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N: bool = ... LOCALE_PATHS: List[str] = ... # Settings for language cookie LANGUAGE_COOKIE_NAME: str = ... LANGUAGE_COOKIE_AGE: Optional[int] = ... LANGUAGE_COOKIE_DOMAIN: Optional[str] = ... LANGUAGE_COOKIE_PATH: str = ... # If you set this to True, Django will format dates, numbers and calendars # according to user current locale. USE_L10N: bool = ... # Not-necessarily-technical managers of the site. They get broken link # notifications and other various emails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE: str = ... DEFAULT_CHARSET: str = ... # Encoding of files read from disk (template and initial SQL files). FILE_CHARSET: str = ... # Email address that error messages come from. SERVER_EMAIL: str = ... # Database connection info. If left empty, will default to the dummy backend. DATABASES: Dict[str, Dict[str, Any]] = ... # Classes used to implement DB routing behavior. class Router(Protocol): def allow_migrate(self, db, app_label, **hints): ... DATABASE_ROUTERS: List[Union[str, Router]] = ... # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND: str = ... # Host for sending email. EMAIL_HOST: str = ... # Port for sending email. EMAIL_PORT: int = ... # Whether to send SMTP 'Date' header in the local time zone or in UTC. EMAIL_USE_LOCALTIME: bool = ... # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER: str = ... EMAIL_HOST_PASSWORD: str = ... EMAIL_USE_TLS: bool = ... EMAIL_USE_SSL: bool = ... EMAIL_SSL_CERTFILE: Optional[str] = ... EMAIL_SSL_KEYFILE: Optional[str] = ... EMAIL_TIMEOUT: Optional[int] = ... # List of strings representing installed apps. INSTALLED_APPS: List[str] = ... TEMPLATES: List[Dict[str, Any]] = ... # Default form rendering class. FORM_RENDERER: str = ... # Default email address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL: str = ... # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX: str = ... # Whether to append trailing slashes to URLs. APPEND_SLASH: bool = ... # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW: bool = ... # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = [ # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search'), # ] DISALLOWED_USER_AGENTS: List[Pattern] = ... ABSOLUTE_URL_OVERRIDES: Dict[str, Any] = ... # List of compiled regular expression objects representing URLs that need not # be reported by BrokenLinkEmailsMiddleware. Here are a few examples: # import re # IGNORABLE_404_URLS = [ # re.compile(r'^/apple-touch-icon.*\.png$'), # re.compile(r'^/favicon.ico$'), # re.compile(r'^/robots.txt$'), # re.compile(r'^/phpmyadmin/'), # re.compile(r'\.(cgi|php|pl)$'), # ] IGNORABLE_404_URLS: List[Pattern] = ... # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY: str = ... # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE: str = ... # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT: str = ... # URL that handles the media served from MEDIA_ROOT. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL: str = ... # Absolute path to the directory static files should be collected to. # Example: "/var/www/example.com/static/" STATIC_ROOT: Optional[str] = ... # URL that handles the static files served from STATIC_ROOT. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL: Optional[str] = ... # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS: List[str] = ... # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE: int = ... # i.e. 2.5 MB # Maximum size in bytes of request data (excluding file uploads) that will be # read before a SuspiciousOperation (RequestDataTooBig) is raised. DATA_UPLOAD_MAX_MEMORY_SIZE: int = ... # i.e. 2.5 MB # Maximum number of GET/POST parameters that will be read before a # SuspiciousOperation (TooManyFieldsSent) is raised. DATA_UPLOAD_MAX_NUMBER_FIELDS: int = ... # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR: Optional[str] = ... # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_PERMISSIONS = None # The numeric mode to assign to newly-created directories, when uploading files. # The value should be a mode as you'd pass to os.chmod; # see https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_DIRECTORY_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH: Optional[str] = ... # Default formatting for date objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT: str = ... # Default formatting for datetime objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT: str = ... # Default formatting for time objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT: str = ... # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT: str = ... # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT: str = ... # Default short formatting for date objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT: str = ... # Default short formatting for datetime objects. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT: str = ... # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS: List[str] = ... # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS: List[str] = ... # '14:30:59' # '14:30:59.000200' # '14:30' # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS: List[str] = ... # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK: int = ... # Decimal separator symbol DECIMAL_SEPARATOR: str = ... # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR: bool = ... # Number of digits that will be together, when splitting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING: int = ... # Thousand separator symbol THOUSAND_SEPARATOR: str = ... # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE: str = ... DEFAULT_INDEX_TABLESPACE: str = ... # Default X-Frame-Options header value X_FRAME_OPTIONS: str = ... USE_X_FORWARDED_HOST: bool = ... USE_X_FORWARDED_PORT: bool = ... # The Python dotted path to the WSGI application that Django's internal server # (runserver) will use. If `None`, the return value of # 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same # behavior as previous versions of Django. Otherwise this should point to an # actual WSGI application object. WSGI_APPLICATION: Optional[str] = ... # If your Django app is behind a proxy that sets a header to specify secure # connections, AND that proxy ensures that user-submitted headers with the # same name are ignored (so that people can't spoof it), set this value to # a tuple of (header_name, header_value). For any requests that come in with # that header/value, request.is_secure() will return True. # WARNING! Only set this if you fully understand what you're doing. Otherwise, # you may be opening yourself up to a security risk. SECURE_PROXY_SSL_HEADER: Optional[Tuple[str, str]] = ... ############## # MIDDLEWARE # ############## # List of middleware to use. Order is important; in the request phase, these # middleware will be applied in the order given, and in the response # phase the middleware will be applied in reverse order. MIDDLEWARE: List[str] = ... ############ # SESSIONS # ############ # Cache to store session data if using the cache session backend. SESSION_CACHE_ALIAS = "default" # Cookie name. This can be whatever you want. SESSION_COOKIE_NAME = "sessionid" # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # A string like "example.com", or None for standard domain cookie. SESSION_COOKIE_DOMAIN: Optional[str] = ... # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_SECURE = False # The path of the session cookie. SESSION_COOKIE_PATH = "/" # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others) SESSION_COOKIE_HTTPONLY = True # Whether to set the flag restricting cookie leaks on cross-site requests. # This can be 'Lax', 'Strict', or None to disable the flag. SESSION_COOKIE_SAMESITE: Optional[str] = ... # Whether to save the session data on every request. SESSION_SAVE_EVERY_REQUEST = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # The module to store session data SESSION_ENGINE = "django.contrib.sessions.backends.db" # Directory to store session files if using the file session module. If None, # the backend will use a sensible default. SESSION_FILE_PATH: Optional[str] = ... # class to serialize session data SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer" ######### # CACHE # ######### # The cache backends to use. CACHES: Dict[str, Dict[str, Any]] = ... CACHE_MIDDLEWARE_KEY_PREFIX = "" CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = "default" ################## # AUTHENTICATION # ################## AUTH_USER_MODEL: str = ... AUTHENTICATION_BACKENDS: Sequence[str] = ... LOGIN_URL = "/accounts/login/" LOGIN_REDIRECT_URL: str = ... LOGOUT_REDIRECT_URL: Optional[str] = ... # The number of days a password reset link is valid for PASSWORD_RESET_TIMEOUT_DAYS = 3 # the first hasher in this list is the preferred algorithm. any # password using different algorithms will be converted automatically # upon login PASSWORD_HASHERS: List[str] = ... AUTH_PASSWORD_VALIDATORS: List[Dict[str, str]] = ... ########### # SIGNING # ########### SIGNING_BACKEND = "django.core.signing.TimestampSigner" ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = "django.views.csrf.csrf_failure" # Settings for CSRF cookie. CSRF_COOKIE_NAME = "csrftoken" CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_PATH = "/" CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE: Optional[str] = ... CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" CSRF_TRUSTED_ORIGINS: List[str] = ... CSRF_USE_SESSIONS = False ############ # MESSAGES # ############ # Class to use as messages backend MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage" # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = "logging.config.dictConfig" # Custom logging configuration. LOGGING: Dict[str, Any] = ... # Default exception reporter filter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER_FILTER = "django.views.debug.SafeExceptionReporterFilter" ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = "django.test.runner.DiscoverRunner" # Apps that don't need to be serialized at test database creation time # (only apps with migrations are to start with) TEST_NON_SERIALIZED_APPS: List[str] = ... ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS: List[str] = ... ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS: List[str] = ... # The default file storage backend used during the build process STATICFILES_STORAGE: str = ... # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS: List[str] = ... ############## # MIGRATIONS # ############## # Migration module overrides for apps, by app label. MIGRATION_MODULES: Dict[str, str] = ... ################# # SYSTEM CHECKS # ################# # List of all issues generated by system checks that should be silenced. Light # issues like warnings, infos or debugs will not generate a message. Silencing # serious issues like errors and criticals does not result in hiding the # message, but Django will not stop you from e.g. running server. SILENCED_SYSTEM_CHECKS: List[str] = ... ####################### # SECURITY MIDDLEWARE # ####################### SECURE_BROWSER_XSS_FILTER = False SECURE_CONTENT_TYPE_NOSNIFF = False SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_HSTS_PRELOAD = False SECURE_HSTS_SECONDS = 0 SECURE_REDIRECT_EXEMPT: List[str] = ... SECURE_SSL_HOST = None SECURE_SSL_REDIRECT = False
17,462
Python
.py
392
43.25
101
0.735641
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,864
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/conf/locale/__init__.pyi
from typing import Dict, Any LANG_INFO: Dict[str, Any] = ...
62
Python
.py
2
29.5
31
0.694915
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,865
i18n.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/conf/urls/i18n.pyi
from typing import Any, List, Tuple, Callable from django.urls.resolvers import URLPattern def i18n_patterns(*urls: Any, prefix_default_language: bool = ...) -> List[List[URLPattern]]: ... def is_language_prefix_patterns_used(urlconf: str) -> Tuple[bool, bool]: ... urlpatterns: List[Callable]
297
Python
.py
5
57.8
97
0.750865
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,866
__init__.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/conf/urls/__init__.pyi
# Stubs for django.conf.urls (Python 3.5) from typing import Any, Callable, Dict, List, Optional, overload, Tuple, Union from django.http.response import HttpResponse, HttpResponseBase from django.urls import URLResolver, URLPattern handler400: Union[str, Callable[..., HttpResponse]] = ... handler403: Union[str, Callable[..., HttpResponse]] = ... handler404: Union[str, Callable[..., HttpResponse]] = ... handler500: Union[str, Callable[..., HttpResponse]] = ... IncludedURLConf = Tuple[List[URLResolver], Optional[str], Optional[str]] def include(arg: Any, namespace: str = ..., app_name: str = ...) -> IncludedURLConf: ... @overload def url( regex: str, view: Callable[..., HttpResponseBase], kwargs: Dict[str, Any] = ..., name: str = ... ) -> URLPattern: ... @overload def url(regex: str, view: IncludedURLConf, kwargs: Dict[str, Any] = ..., name: str = ...) -> URLResolver: ... @overload def url( regex: str, view: List[Union[URLResolver, str]], kwargs: Dict[str, Any] = ..., name: str = ... ) -> URLResolver: ...
1,033
Python
.py
20
50
109
0.685516
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,867
static.pyi
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/django-stubs/conf/urls/static.pyi
from typing import Any, Callable, List from django.urls.resolvers import URLPattern def static(prefix: str, view: Callable = ..., **kwargs: Any) -> List[URLPattern]: ...
172
Python
.py
3
55.666667
85
0.736527
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,868
main.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/main.py
import configparser from functools import partial from typing import Callable, Dict, List, Optional, Tuple from django.db.models.fields.related import RelatedField from mypy.errors import Errors from mypy.nodes import MypyFile, TypeInfo from mypy.options import Options from mypy.plugin import ( AttributeContext, ClassDefContext, DynamicClassDefContext, FunctionContext, MethodContext, Plugin, ) from mypy.types import Type as MypyType import mypy_django_plugin.transformers.orm_lookups from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import fullnames, helpers from mypy_django_plugin.transformers import ( fields, forms, init_create, meta, querysets, request, settings, ) from mypy_django_plugin.transformers.managers import ( create_new_manager_class_from_from_queryset_method, ) from mypy_django_plugin.transformers.models import process_model_class def transform_model_class(ctx: ClassDefContext, django_context: DjangoContext) -> None: sym = ctx.api.lookup_fully_qualified_or_none(fullnames.MODEL_CLASS_FULLNAME) if sym is not None and isinstance(sym.node, TypeInfo): helpers.get_django_metadata(sym.node)['model_bases'][ctx.cls.fullname] = 1 else: if not ctx.api.final_iteration: ctx.api.defer() return process_model_class(ctx, django_context) def transform_form_class(ctx: ClassDefContext) -> None: sym = ctx.api.lookup_fully_qualified_or_none(fullnames.BASEFORM_CLASS_FULLNAME) if sym is not None and isinstance(sym.node, TypeInfo): helpers.get_django_metadata(sym.node)['baseform_bases'][ctx.cls.fullname] = 1 forms.make_meta_nested_class_inherit_from_any(ctx) def add_new_manager_base(ctx: ClassDefContext) -> None: sym = ctx.api.lookup_fully_qualified_or_none(fullnames.MANAGER_CLASS_FULLNAME) if sym is not None and isinstance(sym.node, TypeInfo): helpers.get_django_metadata(sym.node)['manager_bases'][ctx.cls.fullname] = 1 def extract_django_settings_module(config_file_path: Optional[str]) -> str: errors = Errors() if config_file_path is None: errors.report(0, None, "'django_settings_module' is not set: no mypy config file specified") errors.raise_error() parser = configparser.ConfigParser() parser.read(config_file_path) # type: ignore if not parser.has_section('mypy.plugins.django-stubs'): errors.report(0, None, "'django_settings_module' is not set: no section [mypy.plugins.django-stubs]", file=config_file_path) errors.raise_error() if not parser.has_option('mypy.plugins.django-stubs', 'django_settings_module'): errors.report(0, None, "'django_settings_module' is not set: setting is not provided", file=config_file_path) errors.raise_error() django_settings_module = parser.get('mypy.plugins.django-stubs', 'django_settings_module').strip('\'"') return django_settings_module class NewSemanalDjangoPlugin(Plugin): def __init__(self, options: Options) -> None: super().__init__(options) django_settings_module = extract_django_settings_module(options.config_file) self.django_context = DjangoContext(django_settings_module) def _get_current_queryset_bases(self) -> Dict[str, int]: model_sym = self.lookup_fully_qualified(fullnames.QUERYSET_CLASS_FULLNAME) if model_sym is not None and isinstance(model_sym.node, TypeInfo): return (helpers.get_django_metadata(model_sym.node) .setdefault('queryset_bases', {fullnames.QUERYSET_CLASS_FULLNAME: 1})) else: return {} def _get_current_manager_bases(self) -> Dict[str, int]: model_sym = self.lookup_fully_qualified(fullnames.MANAGER_CLASS_FULLNAME) if model_sym is not None and isinstance(model_sym.node, TypeInfo): return (helpers.get_django_metadata(model_sym.node) .setdefault('manager_bases', {fullnames.MANAGER_CLASS_FULLNAME: 1})) else: return {} def _get_current_model_bases(self) -> Dict[str, int]: model_sym = self.lookup_fully_qualified(fullnames.MODEL_CLASS_FULLNAME) if model_sym is not None and isinstance(model_sym.node, TypeInfo): return helpers.get_django_metadata(model_sym.node).setdefault('model_bases', {fullnames.MODEL_CLASS_FULLNAME: 1}) else: return {} def _get_current_form_bases(self) -> Dict[str, int]: model_sym = self.lookup_fully_qualified(fullnames.BASEFORM_CLASS_FULLNAME) if model_sym is not None and isinstance(model_sym.node, TypeInfo): return (helpers.get_django_metadata(model_sym.node) .setdefault('baseform_bases', {fullnames.BASEFORM_CLASS_FULLNAME: 1, fullnames.FORM_CLASS_FULLNAME: 1, fullnames.MODELFORM_CLASS_FULLNAME: 1})) else: return {} def _get_typeinfo_or_none(self, class_name: str) -> Optional[TypeInfo]: sym = self.lookup_fully_qualified(class_name) if sym is not None and isinstance(sym.node, TypeInfo): return sym.node return None def _new_dependency(self, module: str) -> Tuple[int, str, int]: return 10, module, -1 def get_additional_deps(self, file: MypyFile) -> List[Tuple[int, str, int]]: # for settings if file.fullname == 'django.conf' and self.django_context.django_settings_module: return [self._new_dependency(self.django_context.django_settings_module)] # for values / values_list if file.fullname == 'django.db.models': return [self._new_dependency('mypy_extensions'), self._new_dependency('typing')] # for `get_user_model()` if self.django_context.settings: if (file.fullname == 'django.contrib.auth' or file.fullname in {'django.http', 'django.http.request'}): auth_user_model_name = self.django_context.settings.AUTH_USER_MODEL try: auth_user_module = self.django_context.apps_registry.get_model(auth_user_model_name).__module__ except LookupError: # get_user_model() model app is not installed return [] return [self._new_dependency(auth_user_module)] # ensure that all mentioned to='someapp.SomeModel' are loaded with corresponding related Fields defined_model_classes = self.django_context.model_modules.get(file.fullname) if not defined_model_classes: return [] deps = set() for model_class in defined_model_classes: # forward relations for field in self.django_context.get_model_fields(model_class): if isinstance(field, RelatedField): related_model_cls = self.django_context.get_field_related_model_cls(field) if related_model_cls is None: continue related_model_module = related_model_cls.__module__ if related_model_module != file.fullname: deps.add(self._new_dependency(related_model_module)) # reverse relations for relation in model_class._meta.related_objects: related_model_cls = self.django_context.get_field_related_model_cls(relation) related_model_module = related_model_cls.__module__ if related_model_module != file.fullname: deps.add(self._new_dependency(related_model_module)) return list(deps) def get_function_hook(self, fullname: str ) -> Optional[Callable[[FunctionContext], MypyType]]: if fullname == 'django.contrib.auth.get_user_model': return partial(settings.get_user_model_hook, django_context=self.django_context) manager_bases = self._get_current_manager_bases() if fullname in manager_bases: return querysets.determine_proper_manager_type info = self._get_typeinfo_or_none(fullname) if info: if info.has_base(fullnames.FIELD_FULLNAME): return partial(fields.transform_into_proper_return_type, django_context=self.django_context) if helpers.is_model_subclass_info(info, self.django_context): return partial(init_create.redefine_and_typecheck_model_init, django_context=self.django_context) return None def get_method_hook(self, fullname: str ) -> Optional[Callable[[MethodContext], MypyType]]: class_fullname, _, method_name = fullname.rpartition('.') if method_name == 'get_form_class': info = self._get_typeinfo_or_none(class_fullname) if info and info.has_base(fullnames.FORM_MIXIN_CLASS_FULLNAME): return forms.extract_proper_type_for_get_form_class if method_name == 'get_form': info = self._get_typeinfo_or_none(class_fullname) if info and info.has_base(fullnames.FORM_MIXIN_CLASS_FULLNAME): return forms.extract_proper_type_for_get_form if method_name == 'values': info = self._get_typeinfo_or_none(class_fullname) if info and info.has_base(fullnames.QUERYSET_CLASS_FULLNAME): return partial(querysets.extract_proper_type_queryset_values, django_context=self.django_context) if method_name == 'values_list': info = self._get_typeinfo_or_none(class_fullname) if info and info.has_base(fullnames.QUERYSET_CLASS_FULLNAME): return partial(querysets.extract_proper_type_queryset_values_list, django_context=self.django_context) if method_name == 'get_field': info = self._get_typeinfo_or_none(class_fullname) if info and info.has_base(fullnames.OPTIONS_CLASS_FULLNAME): return partial(meta.return_proper_field_type_from_get_field, django_context=self.django_context) manager_classes = self._get_current_manager_bases() if class_fullname in manager_classes and method_name == 'create': return partial(init_create.redefine_and_typecheck_model_create, django_context=self.django_context) if class_fullname in manager_classes and method_name in {'filter', 'get', 'exclude'}: return partial(mypy_django_plugin.transformers.orm_lookups.typecheck_queryset_filter, django_context=self.django_context) return None def get_base_class_hook(self, fullname: str ) -> Optional[Callable[[ClassDefContext], None]]: if (fullname in self.django_context.all_registered_model_class_fullnames or fullname in self._get_current_model_bases()): return partial(transform_model_class, django_context=self.django_context) if fullname in self._get_current_manager_bases(): return add_new_manager_base if fullname in self._get_current_form_bases(): return transform_form_class return None def get_attribute_hook(self, fullname: str ) -> Optional[Callable[[AttributeContext], MypyType]]: class_name, _, attr_name = fullname.rpartition('.') if class_name == fullnames.DUMMY_SETTINGS_BASE_CLASS: return partial(settings.get_type_of_settings_attribute, django_context=self.django_context) info = self._get_typeinfo_or_none(class_name) if info and info.has_base(fullnames.HTTPREQUEST_CLASS_FULLNAME) and attr_name == 'user': return partial(request.set_auth_user_model_as_type_for_request_user, django_context=self.django_context) return None def get_dynamic_class_hook(self, fullname: str ) -> Optional[Callable[[DynamicClassDefContext], None]]: if fullname.endswith('from_queryset'): class_name, _, _ = fullname.rpartition('.') info = self._get_typeinfo_or_none(class_name) if info and info.has_base(fullnames.BASE_MANAGER_CLASS_FULLNAME): return create_new_manager_class_from_from_queryset_method return None def plugin(version): return NewSemanalDjangoPlugin
12,581
Python
.py
213
47.558685
118
0.654602
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,869
fullnames.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/lib/fullnames.py
MODEL_CLASS_FULLNAME = 'django.db.models.base.Model' FIELD_FULLNAME = 'django.db.models.fields.Field' CHAR_FIELD_FULLNAME = 'django.db.models.fields.CharField' ARRAY_FIELD_FULLNAME = 'django.contrib.postgres.fields.array.ArrayField' AUTO_FIELD_FULLNAME = 'django.db.models.fields.AutoField' GENERIC_FOREIGN_KEY_FULLNAME = 'django.contrib.contenttypes.fields.GenericForeignKey' FOREIGN_KEY_FULLNAME = 'django.db.models.fields.related.ForeignKey' ONETOONE_FIELD_FULLNAME = 'django.db.models.fields.related.OneToOneField' MANYTOMANY_FIELD_FULLNAME = 'django.db.models.fields.related.ManyToManyField' DUMMY_SETTINGS_BASE_CLASS = 'django.conf._DjangoConfLazyObject' QUERYSET_CLASS_FULLNAME = 'django.db.models.query.QuerySet' BASE_MANAGER_CLASS_FULLNAME = 'django.db.models.manager.BaseManager' MANAGER_CLASS_FULLNAME = 'django.db.models.manager.Manager' RELATED_MANAGER_CLASS = 'django.db.models.manager.RelatedManager' BASEFORM_CLASS_FULLNAME = 'django.forms.forms.BaseForm' FORM_CLASS_FULLNAME = 'django.forms.forms.Form' MODELFORM_CLASS_FULLNAME = 'django.forms.models.ModelForm' FORM_MIXIN_CLASS_FULLNAME = 'django.views.generic.edit.FormMixin' MANAGER_CLASSES = { MANAGER_CLASS_FULLNAME, BASE_MANAGER_CLASS_FULLNAME, } RELATED_FIELDS_CLASSES = { FOREIGN_KEY_FULLNAME, ONETOONE_FIELD_FULLNAME, MANYTOMANY_FIELD_FULLNAME } MIGRATION_CLASS_FULLNAME = 'django.db.migrations.migration.Migration' OPTIONS_CLASS_FULLNAME = 'django.db.models.options.Options' HTTPREQUEST_CLASS_FULLNAME = 'django.http.request.HttpRequest' F_EXPRESSION_FULLNAME = 'django.db.models.expressions.F'
1,600
Python
.py
31
49.709677
85
0.81294
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,870
helpers.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/lib/helpers.py
from collections import OrderedDict from typing import ( TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple, Union, ) from django.db.models.fields import Field from django.db.models.fields.related import RelatedField from django.db.models.fields.reverse_related import ForeignObjectRel from mypy import checker from mypy.checker import TypeChecker from mypy.mro import calculate_mro from mypy.nodes import ( GDEF, MDEF, Argument, Block, ClassDef, Expression, FuncDef, MemberExpr, MypyFile, NameExpr, PlaceholderNode, StrExpr, SymbolNode, SymbolTable, SymbolTableNode, TypeInfo, Var, ) from mypy.plugin import ( AttributeContext, CheckerPluginInterface, ClassDefContext, DynamicClassDefContext, FunctionContext, MethodContext, ) from mypy.plugins.common import add_method from mypy.semanal import SemanticAnalyzer from mypy.types import AnyType, CallableType, Instance, NoneTyp, TupleType from mypy.types import Type as MypyType from mypy.types import TypedDictType, TypeOfAny, UnionType from mypy_django_plugin.lib import fullnames if TYPE_CHECKING: from mypy_django_plugin.django.context import DjangoContext def get_django_metadata(model_info: TypeInfo) -> Dict[str, Any]: return model_info.metadata.setdefault('django', {}) class IncompleteDefnException(Exception): pass def lookup_fully_qualified_sym(fullname: str, all_modules: Dict[str, MypyFile]) -> Optional[SymbolTableNode]: if '.' not in fullname: return None module, cls_name = fullname.rsplit('.', 1) module_file = all_modules.get(module) if module_file is None: return None sym = module_file.names.get(cls_name) if sym is None: return None return sym def lookup_fully_qualified_generic(name: str, all_modules: Dict[str, MypyFile]) -> Optional[SymbolNode]: sym = lookup_fully_qualified_sym(name, all_modules) if sym is None: return None return sym.node def lookup_fully_qualified_typeinfo(api: Union[TypeChecker, SemanticAnalyzer], fullname: str) -> Optional[TypeInfo]: node = lookup_fully_qualified_generic(fullname, api.modules) if not isinstance(node, TypeInfo): return None return node def lookup_class_typeinfo(api: TypeChecker, klass: type) -> Optional[TypeInfo]: fullname = get_class_fullname(klass) field_info = lookup_fully_qualified_typeinfo(api, fullname) return field_info def reparametrize_instance(instance: Instance, new_args: List[MypyType]) -> Instance: return Instance(instance.type, args=new_args, line=instance.line, column=instance.column) def get_class_fullname(klass: type) -> str: return klass.__module__ + '.' + klass.__qualname__ def get_call_argument_by_name(ctx: Union[FunctionContext, MethodContext], name: str) -> Optional[Expression]: """ Return the expression for the specific argument. This helper should only be used with non-star arguments. """ if name not in ctx.callee_arg_names: return None idx = ctx.callee_arg_names.index(name) args = ctx.args[idx] if len(args) != 1: # Either an error or no value passed. return None return args[0] def get_call_argument_type_by_name(ctx: Union[FunctionContext, MethodContext], name: str) -> Optional[MypyType]: """Return the type for the specific argument. This helper should only be used with non-star arguments. """ if name not in ctx.callee_arg_names: return None idx = ctx.callee_arg_names.index(name) arg_types = ctx.arg_types[idx] if len(arg_types) != 1: # Either an error or no value passed. return None return arg_types[0] def make_optional(typ: MypyType) -> MypyType: return UnionType.make_union([typ, NoneTyp()]) def parse_bool(expr: Expression) -> Optional[bool]: if isinstance(expr, NameExpr): if expr.fullname == 'builtins.True': return True if expr.fullname == 'builtins.False': return False return None def has_any_of_bases(info: TypeInfo, bases: Iterable[str]) -> bool: for base_fullname in bases: if info.has_base(base_fullname): return True return False def iter_bases(info: TypeInfo) -> Iterator[Instance]: for base in info.bases: yield base yield from iter_bases(base.type) def get_private_descriptor_type(type_info: TypeInfo, private_field_name: str, is_nullable: bool) -> MypyType: """ Return declared type of type_info's private_field_name (used for private Field attributes)""" sym = type_info.get(private_field_name) if sym is None: return AnyType(TypeOfAny.explicit) node = sym.node if isinstance(node, Var): descriptor_type = node.type if descriptor_type is None: return AnyType(TypeOfAny.explicit) if is_nullable: descriptor_type = make_optional(descriptor_type) return descriptor_type return AnyType(TypeOfAny.explicit) def get_field_lookup_exact_type(api: TypeChecker, field: Field) -> MypyType: if isinstance(field, (RelatedField, ForeignObjectRel)): lookup_type_class = field.related_model rel_model_info = lookup_class_typeinfo(api, lookup_type_class) if rel_model_info is None: return AnyType(TypeOfAny.from_error) return make_optional(Instance(rel_model_info, [])) field_info = lookup_class_typeinfo(api, field.__class__) if field_info is None: return AnyType(TypeOfAny.explicit) return get_private_descriptor_type(field_info, '_pyi_lookup_exact_type', is_nullable=field.null) def get_nested_meta_node_for_current_class(info: TypeInfo) -> Optional[TypeInfo]: metaclass_sym = info.names.get('Meta') if metaclass_sym is not None and isinstance(metaclass_sym.node, TypeInfo): return metaclass_sym.node return None def add_new_class_for_module(module: MypyFile, name: str, bases: List[Instance], fields: Optional[Dict[str, MypyType]] = None ) -> TypeInfo: new_class_unique_name = checker.gen_unique_name(name, module.names) # make new class expression classdef = ClassDef(new_class_unique_name, Block([])) classdef.fullname = module.fullname + '.' + new_class_unique_name # make new TypeInfo new_typeinfo = TypeInfo(SymbolTable(), classdef, module.fullname) new_typeinfo.bases = bases calculate_mro(new_typeinfo) new_typeinfo.calculate_metaclass_type() # add fields if fields: for field_name, field_type in fields.items(): var = Var(field_name, type=field_type) var.info = new_typeinfo var._fullname = new_typeinfo.fullname + '.' + field_name new_typeinfo.names[field_name] = SymbolTableNode(MDEF, var, plugin_generated=True) classdef.info = new_typeinfo module.names[new_class_unique_name] = SymbolTableNode(GDEF, new_typeinfo, plugin_generated=True) return new_typeinfo def get_current_module(api: TypeChecker) -> MypyFile: current_module = None for item in reversed(api.scope.stack): if isinstance(item, MypyFile): current_module = item break assert current_module is not None return current_module def make_oneoff_named_tuple(api: TypeChecker, name: str, fields: 'OrderedDict[str, MypyType]') -> TupleType: current_module = get_current_module(api) namedtuple_info = add_new_class_for_module(current_module, name, bases=[api.named_generic_type('typing.NamedTuple', [])], fields=fields) return TupleType(list(fields.values()), fallback=Instance(namedtuple_info, [])) def make_tuple(api: 'TypeChecker', fields: List[MypyType]) -> TupleType: # fallback for tuples is any builtins.tuple instance fallback = api.named_generic_type('builtins.tuple', [AnyType(TypeOfAny.special_form)]) return TupleType(fields, fallback=fallback) def convert_any_to_type(typ: MypyType, referred_to_type: MypyType) -> MypyType: if isinstance(typ, UnionType): converted_items = [] for item in typ.items: converted_items.append(convert_any_to_type(item, referred_to_type)) return UnionType.make_union(converted_items, line=typ.line, column=typ.column) if isinstance(typ, Instance): args = [] for default_arg in typ.args: if isinstance(default_arg, AnyType): args.append(referred_to_type) else: args.append(default_arg) return reparametrize_instance(typ, args) if isinstance(typ, AnyType): return referred_to_type return typ def make_typeddict(api: CheckerPluginInterface, fields: 'OrderedDict[str, MypyType]', required_keys: Set[str]) -> TypedDictType: object_type = api.named_generic_type('mypy_extensions._TypedDict', []) typed_dict_type = TypedDictType(fields, required_keys=required_keys, fallback=object_type) return typed_dict_type def resolve_string_attribute_value(attr_expr: Expression, django_context: 'DjangoContext') -> Optional[str]: if isinstance(attr_expr, StrExpr): return attr_expr.value # support extracting from settings, in general case it's unresolvable yet if isinstance(attr_expr, MemberExpr): member_name = attr_expr.name if isinstance(attr_expr.expr, NameExpr) and attr_expr.expr.fullname == 'django.conf.settings': if hasattr(django_context.settings, member_name): return getattr(django_context.settings, member_name) return None def get_semanal_api(ctx: Union[ClassDefContext, DynamicClassDefContext]) -> SemanticAnalyzer: if not isinstance(ctx.api, SemanticAnalyzer): raise ValueError('Not a SemanticAnalyzer') return ctx.api def get_typechecker_api(ctx: Union[AttributeContext, MethodContext, FunctionContext]) -> TypeChecker: if not isinstance(ctx.api, TypeChecker): raise ValueError('Not a TypeChecker') return ctx.api def is_model_subclass_info(info: TypeInfo, django_context: 'DjangoContext') -> bool: return (info.fullname in django_context.all_registered_model_class_fullnames or info.has_base(fullnames.MODEL_CLASS_FULLNAME)) def check_types_compatible(ctx: Union[FunctionContext, MethodContext], *, expected_type: MypyType, actual_type: MypyType, error_message: str) -> None: api = get_typechecker_api(ctx) api.check_subtype(actual_type, expected_type, ctx.context, error_message, 'got', 'expected') def add_new_sym_for_info(info: TypeInfo, *, name: str, sym_type: MypyType) -> None: # type=: type of the variable itself var = Var(name=name, type=sym_type) # var.info: type of the object variable is bound to var.info = info var._fullname = info.fullname + '.' + name var.is_initialized_in_class = True var.is_inferred = True info.names[name] = SymbolTableNode(MDEF, var, plugin_generated=True) def build_unannotated_method_args(method_node: FuncDef) -> Tuple[List[Argument], MypyType]: prepared_arguments = [] for argument in method_node.arguments[1:]: argument.type_annotation = AnyType(TypeOfAny.unannotated) prepared_arguments.append(argument) return_type = AnyType(TypeOfAny.unannotated) return prepared_arguments, return_type def copy_method_to_another_class(ctx: ClassDefContext, self_type: Instance, new_method_name: str, method_node: FuncDef) -> None: semanal_api = get_semanal_api(ctx) if method_node.type is None: if not semanal_api.final_iteration: semanal_api.defer() return arguments, return_type = build_unannotated_method_args(method_node) add_method(ctx, new_method_name, args=arguments, return_type=return_type, self_type=self_type) return method_type = method_node.type if not isinstance(method_type, CallableType): if not semanal_api.final_iteration: semanal_api.defer() return arguments = [] bound_return_type = semanal_api.anal_type(method_type.ret_type, allow_placeholder=True) assert bound_return_type is not None if isinstance(bound_return_type, PlaceholderNode): return for arg_name, arg_type, original_argument in zip(method_type.arg_names[1:], method_type.arg_types[1:], method_node.arguments[1:]): bound_arg_type = semanal_api.anal_type(arg_type, allow_placeholder=True) assert bound_arg_type is not None if isinstance(bound_arg_type, PlaceholderNode): return var = Var(name=original_argument.variable.name, type=arg_type) var.line = original_argument.variable.line var.column = original_argument.variable.column argument = Argument(variable=var, type_annotation=bound_arg_type, initializer=original_argument.initializer, kind=original_argument.kind) argument.set_line(original_argument) arguments.append(argument) add_method(ctx, new_method_name, args=arguments, return_type=bound_return_type, self_type=self_type)
13,900
Python
.py
290
39.165517
118
0.669945
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,871
models.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/models.py
from typing import Dict, List, Optional, Type, cast from django.db.models.base import Model from django.db.models.fields import DateField, DateTimeField from django.db.models.fields.related import ForeignKey from django.db.models.fields.reverse_related import ( ManyToManyRel, ManyToOneRel, OneToOneRel, ) from mypy.nodes import ARG_STAR2, Argument, Context, FuncDef, TypeInfo, Var from mypy.plugin import ClassDefContext from mypy.plugins import common from mypy.semanal import SemanticAnalyzer from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import fullnames, helpers from mypy_django_plugin.transformers import fields from mypy_django_plugin.transformers.fields import get_field_descriptor_types class ModelClassInitializer: api: SemanticAnalyzer def __init__(self, ctx: ClassDefContext, django_context: DjangoContext): self.api = cast(SemanticAnalyzer, ctx.api) self.model_classdef = ctx.cls self.django_context = django_context self.ctx = ctx def lookup_typeinfo(self, fullname: str) -> Optional[TypeInfo]: return helpers.lookup_fully_qualified_typeinfo(self.api, fullname) def lookup_typeinfo_or_incomplete_defn_error(self, fullname: str) -> TypeInfo: info = self.lookup_typeinfo(fullname) if info is None: raise helpers.IncompleteDefnException(f'No {fullname!r} found') return info def lookup_class_typeinfo_or_incomplete_defn_error(self, klass: type) -> TypeInfo: fullname = helpers.get_class_fullname(klass) field_info = self.lookup_typeinfo_or_incomplete_defn_error(fullname) return field_info def create_new_var(self, name: str, typ: MypyType) -> Var: # type=: type of the variable itself var = Var(name=name, type=typ) # var.info: type of the object variable is bound to var.info = self.model_classdef.info var._fullname = self.model_classdef.info.fullname + '.' + name var.is_initialized_in_class = True var.is_inferred = True return var def add_new_node_to_model_class(self, name: str, typ: MypyType) -> None: helpers.add_new_sym_for_info(self.model_classdef.info, name=name, sym_type=typ) def add_new_class_for_current_module(self, name: str, bases: List[Instance]) -> TypeInfo: current_module = self.api.modules[self.model_classdef.info.module_name] new_class_info = helpers.add_new_class_for_module(current_module, name=name, bases=bases) return new_class_info def run(self) -> None: model_cls = self.django_context.get_model_class_by_fullname(self.model_classdef.fullname) if model_cls is None: return self.run_with_model_cls(model_cls) def run_with_model_cls(self, model_cls): pass class InjectAnyAsBaseForNestedMeta(ModelClassInitializer): """ Replaces class MyModel(models.Model): class Meta: pass with class MyModel(models.Model): class Meta(Any): pass to get around incompatible Meta inner classes for different models. """ def run(self) -> None: meta_node = helpers.get_nested_meta_node_for_current_class(self.model_classdef.info) if meta_node is None: return None meta_node.fallback_to_any = True class AddDefaultPrimaryKey(ModelClassInitializer): def run_with_model_cls(self, model_cls: Type[Model]) -> None: auto_field = model_cls._meta.auto_field if auto_field and not self.model_classdef.info.has_readable_member(auto_field.attname): # autogenerated field auto_field_fullname = helpers.get_class_fullname(auto_field.__class__) auto_field_info = self.lookup_typeinfo_or_incomplete_defn_error(auto_field_fullname) set_type, get_type = fields.get_field_descriptor_types(auto_field_info, is_nullable=False) self.add_new_node_to_model_class(auto_field.attname, Instance(auto_field_info, [set_type, get_type])) class AddRelatedModelsId(ModelClassInitializer): def run_with_model_cls(self, model_cls: Type[Model]) -> None: for field in model_cls._meta.get_fields(): if isinstance(field, ForeignKey): related_model_cls = self.django_context.get_field_related_model_cls(field) if related_model_cls is None: error_context: Context = self.ctx.cls field_sym = self.ctx.cls.info.get(field.name) if field_sym is not None and field_sym.node is not None: error_context = field_sym.node self.api.fail(f'Cannot find model {field.related_model!r} ' f'referenced in field {field.name!r} ', ctx=error_context) self.add_new_node_to_model_class(field.attname, AnyType(TypeOfAny.explicit)) continue if related_model_cls._meta.abstract: continue rel_primary_key_field = self.django_context.get_primary_key_field(related_model_cls) try: field_info = self.lookup_class_typeinfo_or_incomplete_defn_error(rel_primary_key_field.__class__) except helpers.IncompleteDefnException as exc: if not self.api.final_iteration: raise exc else: continue is_nullable = self.django_context.get_field_nullability(field, None) set_type, get_type = get_field_descriptor_types(field_info, is_nullable) self.add_new_node_to_model_class(field.attname, Instance(field_info, [set_type, get_type])) class AddManagers(ModelClassInitializer): def has_any_parametrized_manager_as_base(self, info: TypeInfo) -> bool: for base in helpers.iter_bases(info): if self.is_any_parametrized_manager(base): return True return False def is_any_parametrized_manager(self, typ: Instance) -> bool: return typ.type.fullname in fullnames.MANAGER_CLASSES and isinstance(typ.args[0], AnyType) def get_generated_manager_mappings(self, base_manager_fullname: str) -> Dict[str, str]: base_manager_info = self.lookup_typeinfo(base_manager_fullname) if (base_manager_info is None or 'from_queryset_managers' not in base_manager_info.metadata): return {} return base_manager_info.metadata['from_queryset_managers'] def create_new_model_parametrized_manager(self, name: str, base_manager_info: TypeInfo) -> Instance: bases = [] for original_base in base_manager_info.bases: if self.is_any_parametrized_manager(original_base): if original_base.type is None: raise helpers.IncompleteDefnException() original_base = helpers.reparametrize_instance(original_base, [Instance(self.model_classdef.info, [])]) bases.append(original_base) new_manager_info = self.add_new_class_for_current_module(name, bases) # copy fields to a new manager new_cls_def_context = ClassDefContext(cls=new_manager_info.defn, reason=self.ctx.reason, api=self.api) custom_manager_type = Instance(new_manager_info, [Instance(self.model_classdef.info, [])]) for name, sym in base_manager_info.names.items(): # replace self type with new class, if copying method if isinstance(sym.node, FuncDef): helpers.copy_method_to_another_class(new_cls_def_context, self_type=custom_manager_type, new_method_name=name, method_node=sym.node) continue new_sym = sym.copy() if isinstance(new_sym.node, Var): new_var = Var(name, type=sym.type) new_var.info = new_manager_info new_var._fullname = new_manager_info.fullname + '.' + name new_sym.node = new_var new_manager_info.names[name] = new_sym return custom_manager_type def run_with_model_cls(self, model_cls: Type[Model]) -> None: for manager_name, manager in model_cls._meta.managers_map.items(): manager_class_name = manager.__class__.__name__ manager_fullname = helpers.get_class_fullname(manager.__class__) try: manager_info = self.lookup_typeinfo_or_incomplete_defn_error(manager_fullname) except helpers.IncompleteDefnException as exc: if not self.api.final_iteration: raise exc else: base_manager_fullname = helpers.get_class_fullname(manager.__class__.__bases__[0]) generated_managers = self.get_generated_manager_mappings(base_manager_fullname) if manager_fullname not in generated_managers: # not a generated manager, continue with the loop continue real_manager_fullname = generated_managers[manager_fullname] manager_info = self.lookup_typeinfo(real_manager_fullname) # type: ignore if manager_info is None: continue manager_class_name = real_manager_fullname.rsplit('.', maxsplit=1)[1] if manager_name not in self.model_classdef.info.names: manager_type = Instance(manager_info, [Instance(self.model_classdef.info, [])]) self.add_new_node_to_model_class(manager_name, manager_type) else: # creates new MODELNAME_MANAGERCLASSNAME class that represents manager parametrized with current model if not self.has_any_parametrized_manager_as_base(manager_info): continue custom_model_manager_name = manager.model.__name__ + '_' + manager_class_name try: custom_manager_type = self.create_new_model_parametrized_manager(custom_model_manager_name, base_manager_info=manager_info) except helpers.IncompleteDefnException: continue self.add_new_node_to_model_class(manager_name, custom_manager_type) class AddDefaultManagerAttribute(ModelClassInitializer): def run_with_model_cls(self, model_cls: Type[Model]) -> None: # add _default_manager if '_default_manager' not in self.model_classdef.info.names: default_manager_fullname = helpers.get_class_fullname(model_cls._meta.default_manager.__class__) default_manager_info = self.lookup_typeinfo_or_incomplete_defn_error(default_manager_fullname) default_manager = Instance(default_manager_info, [Instance(self.model_classdef.info, [])]) self.add_new_node_to_model_class('_default_manager', default_manager) class AddRelatedManagers(ModelClassInitializer): def run_with_model_cls(self, model_cls: Type[Model]) -> None: # add related managers for relation in self.django_context.get_model_relations(model_cls): attname = relation.get_accessor_name() if attname is None: # no reverse accessor continue related_model_cls = self.django_context.get_field_related_model_cls(relation) if related_model_cls is None: continue try: related_model_info = self.lookup_class_typeinfo_or_incomplete_defn_error(related_model_cls) except helpers.IncompleteDefnException as exc: if not self.api.final_iteration: raise exc else: continue if isinstance(relation, OneToOneRel): self.add_new_node_to_model_class(attname, Instance(related_model_info, [])) continue if isinstance(relation, (ManyToOneRel, ManyToManyRel)): try: related_manager_info = self.lookup_typeinfo_or_incomplete_defn_error(fullnames.RELATED_MANAGER_CLASS) # noqa: E501 if 'objects' not in related_model_info.names: raise helpers.IncompleteDefnException() except helpers.IncompleteDefnException as exc: if not self.api.final_iteration: raise exc else: continue # create new RelatedManager subclass parametrized_related_manager_type = Instance(related_manager_info, [Instance(related_model_info, [])]) default_manager_type = related_model_info.names['objects'].type if (default_manager_type is None or not isinstance(default_manager_type, Instance) or default_manager_type.type.fullname == fullnames.MANAGER_CLASS_FULLNAME): self.add_new_node_to_model_class(attname, parametrized_related_manager_type) continue name = related_model_cls.__name__ + '_' + 'RelatedManager' bases = [parametrized_related_manager_type, default_manager_type] new_related_manager_info = self.add_new_class_for_current_module(name, bases) self.add_new_node_to_model_class(attname, Instance(new_related_manager_info, [])) class AddExtraFieldMethods(ModelClassInitializer): def run_with_model_cls(self, model_cls: Type[Model]) -> None: # get_FOO_display for choices for field in self.django_context.get_model_fields(model_cls): if field.choices: info = self.lookup_typeinfo_or_incomplete_defn_error('builtins.str') return_type = Instance(info, []) common.add_method(self.ctx, name='get_{}_display'.format(field.attname), args=[], return_type=return_type) # get_next_by, get_previous_by for Date, DateTime for field in self.django_context.get_model_fields(model_cls): if isinstance(field, (DateField, DateTimeField)) and not field.null: return_type = Instance(self.model_classdef.info, []) common.add_method(self.ctx, name='get_next_by_{}'.format(field.attname), args=[Argument(Var('kwargs', AnyType(TypeOfAny.explicit)), AnyType(TypeOfAny.explicit), initializer=None, kind=ARG_STAR2)], return_type=return_type) common.add_method(self.ctx, name='get_previous_by_{}'.format(field.attname), args=[Argument(Var('kwargs', AnyType(TypeOfAny.explicit)), AnyType(TypeOfAny.explicit), initializer=None, kind=ARG_STAR2)], return_type=return_type) class AddMetaOptionsAttribute(ModelClassInitializer): def run_with_model_cls(self, model_cls: Type[Model]) -> None: if '_meta' not in self.model_classdef.info.names: options_info = self.lookup_typeinfo_or_incomplete_defn_error(fullnames.OPTIONS_CLASS_FULLNAME) self.add_new_node_to_model_class('_meta', Instance(options_info, [ Instance(self.model_classdef.info, []) ])) def process_model_class(ctx: ClassDefContext, django_context: DjangoContext) -> None: initializers = [ InjectAnyAsBaseForNestedMeta, AddDefaultPrimaryKey, AddRelatedModelsId, AddManagers, AddDefaultManagerAttribute, AddRelatedManagers, AddExtraFieldMethods, AddMetaOptionsAttribute, ] for initializer_cls in initializers: try: initializer_cls(ctx, django_context).run() except helpers.IncompleteDefnException: if not ctx.api.final_iteration: ctx.api.defer()
17,481
Python
.py
304
41.256579
135
0.5884
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,872
settings.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/settings.py
from mypy.nodes import MemberExpr from mypy.plugin import AttributeContext, FunctionContext from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny, TypeType from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import helpers def get_user_model_hook(ctx: FunctionContext, django_context: DjangoContext) -> MypyType: auth_user_model = django_context.settings.AUTH_USER_MODEL model_cls = django_context.apps_registry.get_model(auth_user_model) model_cls_fullname = helpers.get_class_fullname(model_cls) model_info = helpers.lookup_fully_qualified_typeinfo(helpers.get_typechecker_api(ctx), model_cls_fullname) if model_info is None: return AnyType(TypeOfAny.unannotated) return TypeType(Instance(model_info, [])) def get_type_of_settings_attribute(ctx: AttributeContext, django_context: DjangoContext) -> MypyType: assert isinstance(ctx.context, MemberExpr) setting_name = ctx.context.name if not hasattr(django_context.settings, setting_name): ctx.api.fail(f"'Settings' object has no attribute {setting_name!r}", ctx.context) return ctx.default_attr_type typechecker_api = helpers.get_typechecker_api(ctx) # first look for the setting in the project settings file, then global settings settings_module = typechecker_api.modules.get(django_context.django_settings_module) global_settings_module = typechecker_api.modules.get('django.conf.global_settings') for module in [settings_module, global_settings_module]: if module is not None: sym = module.names.get(setting_name) if sym is not None and sym.type is not None: return sym.type # if by any reason it isn't present there, get type from django settings value = getattr(django_context.settings, setting_name) value_fullname = helpers.get_class_fullname(value.__class__) value_info = helpers.lookup_fully_qualified_typeinfo(typechecker_api, value_fullname) if value_info is None: return ctx.default_attr_type return Instance(value_info, [])
2,213
Python
.py
38
51.210526
101
0.735552
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,873
meta.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/meta.py
from django.core.exceptions import FieldDoesNotExist from mypy.plugin import MethodContext from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import helpers def _get_field_instance(ctx: MethodContext, field_fullname: str) -> MypyType: field_info = helpers.lookup_fully_qualified_typeinfo(helpers.get_typechecker_api(ctx), field_fullname) if field_info is None: return AnyType(TypeOfAny.unannotated) return Instance(field_info, [AnyType(TypeOfAny.explicit), AnyType(TypeOfAny.explicit)]) def return_proper_field_type_from_get_field(ctx: MethodContext, django_context: DjangoContext) -> MypyType: # Options instance assert isinstance(ctx.type, Instance) # bail if list of generic params is empty if len(ctx.type.args) == 0: return ctx.default_return_type model_type = ctx.type.args[0] if not isinstance(model_type, Instance): return ctx.default_return_type model_cls = django_context.get_model_class_by_fullname(model_type.type.fullname) if model_cls is None: return ctx.default_return_type field_name_expr = helpers.get_call_argument_by_name(ctx, 'field_name') if field_name_expr is None: return ctx.default_return_type field_name = helpers.resolve_string_attribute_value(field_name_expr, django_context) if field_name is None: return ctx.default_return_type try: field = model_cls._meta.get_field(field_name) except FieldDoesNotExist as exc: # if model is abstract, do not raise exception, skip false positives if not model_cls._meta.abstract: ctx.api.fail(exc.args[0], ctx.context) return AnyType(TypeOfAny.from_error) field_fullname = helpers.get_class_fullname(field.__class__) return _get_field_instance(ctx, field_fullname)
2,017
Python
.py
40
43.5
107
0.722137
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,874
request.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/request.py
from mypy.plugin import AttributeContext from mypy.types import Instance from mypy.types import Type as MypyType from mypy.types import UnionType from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import helpers def set_auth_user_model_as_type_for_request_user(ctx: AttributeContext, django_context: DjangoContext) -> MypyType: auth_user_model = django_context.settings.AUTH_USER_MODEL user_cls = django_context.apps_registry.get_model(auth_user_model) user_info = helpers.lookup_class_typeinfo(helpers.get_typechecker_api(ctx), user_cls) if user_info is None: return ctx.default_attr_type # Imported here because django isn't properly loaded yet when module is loaded from django.contrib.auth.models import AnonymousUser anonymous_user_info = helpers.lookup_class_typeinfo(helpers.get_typechecker_api(ctx), AnonymousUser) if anonymous_user_info is None: # This shouldn't be able to happen, as we managed to import the model above... return Instance(user_info, []) return UnionType([Instance(user_info, []), Instance(anonymous_user_info, [])])
1,148
Python
.py
19
55.894737
115
0.771836
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,875
init_create.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/init_create.py
from typing import List, Tuple, Type, Union from django.db.models.base import Model from mypy.plugin import FunctionContext, MethodContext from mypy.types import Instance from mypy.types import Type as MypyType from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import helpers def get_actual_types(ctx: Union[MethodContext, FunctionContext], expected_keys: List[str]) -> List[Tuple[str, MypyType]]: actual_types = [] # positionals for pos, (actual_name, actual_type) in enumerate(zip(ctx.arg_names[0], ctx.arg_types[0])): if actual_name is None: if ctx.callee_arg_names[0] == 'kwargs': # unpacked dict as kwargs is not supported continue actual_name = expected_keys[pos] actual_types.append((actual_name, actual_type)) # kwargs if len(ctx.callee_arg_names) > 1: for actual_name, actual_type in zip(ctx.arg_names[1], ctx.arg_types[1]): if actual_name is None: # unpacked dict as kwargs is not supported continue actual_types.append((actual_name, actual_type)) return actual_types def typecheck_model_method(ctx: Union[FunctionContext, MethodContext], django_context: DjangoContext, model_cls: Type[Model], method: str) -> MypyType: typechecker_api = helpers.get_typechecker_api(ctx) expected_types = django_context.get_expected_types(typechecker_api, model_cls, method=method) expected_keys = [key for key in expected_types.keys() if key != 'pk'] for actual_name, actual_type in get_actual_types(ctx, expected_keys): if actual_name not in expected_types: ctx.api.fail('Unexpected attribute "{}" for model "{}"'.format(actual_name, model_cls.__name__), ctx.context) continue helpers.check_types_compatible(ctx, expected_type=expected_types[actual_name], actual_type=actual_type, error_message='Incompatible type for "{}" of "{}"'.format(actual_name, model_cls.__name__)) return ctx.default_return_type def redefine_and_typecheck_model_init(ctx: FunctionContext, django_context: DjangoContext) -> MypyType: assert isinstance(ctx.default_return_type, Instance) model_fullname = ctx.default_return_type.type.fullname model_cls = django_context.get_model_class_by_fullname(model_fullname) if model_cls is None: return ctx.default_return_type return typecheck_model_method(ctx, django_context, model_cls, '__init__') def redefine_and_typecheck_model_create(ctx: MethodContext, django_context: DjangoContext) -> MypyType: if not isinstance(ctx.default_return_type, Instance): # only work with ctx.default_return_type = model Instance return ctx.default_return_type model_fullname = ctx.default_return_type.type.fullname model_cls = django_context.get_model_class_by_fullname(model_fullname) if model_cls is None: return ctx.default_return_type return typecheck_model_method(ctx, django_context, model_cls, 'create')
3,415
Python
.py
59
45.525424
117
0.637725
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,876
orm_lookups.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/orm_lookups.py
from mypy.plugin import MethodContext from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import fullnames, helpers def typecheck_queryset_filter(ctx: MethodContext, django_context: DjangoContext) -> MypyType: lookup_kwargs = ctx.arg_names[1] provided_lookup_types = ctx.arg_types[1] assert isinstance(ctx.type, Instance) if not ctx.type.args or not isinstance(ctx.type.args[0], Instance): return ctx.default_return_type model_cls_fullname = ctx.type.args[0].type.fullname model_cls = django_context.get_model_class_by_fullname(model_cls_fullname) if model_cls is None: return ctx.default_return_type for lookup_kwarg, provided_type in zip(lookup_kwargs, provided_lookup_types): if lookup_kwarg is None: continue if (isinstance(provided_type, Instance) and provided_type.type.has_base('django.db.models.expressions.Combinable')): provided_type = resolve_combinable_type(provided_type, django_context) lookup_type = django_context.resolve_lookup_expected_type(ctx, model_cls, lookup_kwarg) # Managers as provided_type is not supported yet if (isinstance(provided_type, Instance) and helpers.has_any_of_bases(provided_type.type, (fullnames.MANAGER_CLASS_FULLNAME, fullnames.QUERYSET_CLASS_FULLNAME))): return ctx.default_return_type helpers.check_types_compatible(ctx, expected_type=lookup_type, actual_type=provided_type, error_message=f'Incompatible type for lookup {lookup_kwarg!r}:') return ctx.default_return_type def resolve_combinable_type(combinable_type: Instance, django_context: DjangoContext) -> MypyType: if combinable_type.type.fullname != fullnames.F_EXPRESSION_FULLNAME: # Combinables aside from F expressions are unsupported return AnyType(TypeOfAny.explicit) return django_context.resolve_f_expression_type(combinable_type)
2,278
Python
.py
38
48.736842
103
0.686125
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,877
querysets.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/querysets.py
from collections import OrderedDict from typing import List, Optional, Sequence, Type from django.core.exceptions import FieldError from django.db.models.base import Model from django.db.models.fields.related import RelatedField from django.db.models.fields.reverse_related import ForeignObjectRel from mypy.nodes import Expression, NameExpr from mypy.plugin import FunctionContext, MethodContext from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny from mypy_django_plugin.django.context import ( DjangoContext, LookupsAreUnsupported, ) from mypy_django_plugin.lib import fullnames, helpers def _extract_model_type_from_queryset(queryset_type: Instance) -> Optional[Instance]: for base_type in [queryset_type, *queryset_type.type.bases]: if (len(base_type.args) and isinstance(base_type.args[0], Instance) and base_type.args[0].type.has_base(fullnames.MODEL_CLASS_FULLNAME)): return base_type.args[0] return None def determine_proper_manager_type(ctx: FunctionContext) -> MypyType: default_return_type = ctx.default_return_type assert isinstance(default_return_type, Instance) outer_model_info = helpers.get_typechecker_api(ctx).scope.active_class() if (outer_model_info is None or not outer_model_info.has_base(fullnames.MODEL_CLASS_FULLNAME)): return default_return_type return helpers.reparametrize_instance(default_return_type, [Instance(outer_model_info, [])]) def get_field_type_from_lookup(ctx: MethodContext, django_context: DjangoContext, model_cls: Type[Model], *, method: str, lookup: str) -> Optional[MypyType]: try: lookup_field = django_context.resolve_lookup_into_field(model_cls, lookup) except FieldError as exc: ctx.api.fail(exc.args[0], ctx.context) return None except LookupsAreUnsupported: return AnyType(TypeOfAny.explicit) if ((isinstance(lookup_field, RelatedField) and lookup_field.column == lookup) or isinstance(lookup_field, ForeignObjectRel)): related_model_cls = django_context.get_field_related_model_cls(lookup_field) if related_model_cls is None: return AnyType(TypeOfAny.from_error) lookup_field = django_context.get_primary_key_field(related_model_cls) field_get_type = django_context.get_field_get_type(helpers.get_typechecker_api(ctx), lookup_field, method=method) return field_get_type def get_values_list_row_type(ctx: MethodContext, django_context: DjangoContext, model_cls: Type[Model], flat: bool, named: bool) -> MypyType: field_lookups = resolve_field_lookups(ctx.args[0], django_context) if field_lookups is None: return AnyType(TypeOfAny.from_error) typechecker_api = helpers.get_typechecker_api(ctx) if len(field_lookups) == 0: if flat: primary_key_field = django_context.get_primary_key_field(model_cls) lookup_type = get_field_type_from_lookup(ctx, django_context, model_cls, lookup=primary_key_field.attname, method='values_list') assert lookup_type is not None return lookup_type elif named: column_types: 'OrderedDict[str, MypyType]' = OrderedDict() for field in django_context.get_model_fields(model_cls): column_type = django_context.get_field_get_type(typechecker_api, field, method='values_list') column_types[field.attname] = column_type return helpers.make_oneoff_named_tuple(typechecker_api, 'Row', column_types) else: # flat=False, named=False, all fields field_lookups = [] for field in django_context.get_model_fields(model_cls): field_lookups.append(field.attname) if len(field_lookups) > 1 and flat: typechecker_api.fail("'flat' is not valid when 'values_list' is called with more than one field", ctx.context) return AnyType(TypeOfAny.from_error) column_types = OrderedDict() for field_lookup in field_lookups: lookup_field_type = get_field_type_from_lookup(ctx, django_context, model_cls, lookup=field_lookup, method='values_list') if lookup_field_type is None: return AnyType(TypeOfAny.from_error) column_types[field_lookup] = lookup_field_type if flat: assert len(column_types) == 1 row_type = next(iter(column_types.values())) elif named: row_type = helpers.make_oneoff_named_tuple(typechecker_api, 'Row', column_types) else: row_type = helpers.make_tuple(typechecker_api, list(column_types.values())) return row_type def extract_proper_type_queryset_values_list(ctx: MethodContext, django_context: DjangoContext) -> MypyType: # called on the Instance, returns QuerySet of something assert isinstance(ctx.type, Instance) assert isinstance(ctx.default_return_type, Instance) model_type = _extract_model_type_from_queryset(ctx.type) if model_type is None: return AnyType(TypeOfAny.from_omitted_generics) model_cls = django_context.get_model_class_by_fullname(model_type.type.fullname) if model_cls is None: return ctx.default_return_type flat_expr = helpers.get_call_argument_by_name(ctx, 'flat') if flat_expr is not None and isinstance(flat_expr, NameExpr): flat = helpers.parse_bool(flat_expr) else: flat = False named_expr = helpers.get_call_argument_by_name(ctx, 'named') if named_expr is not None and isinstance(named_expr, NameExpr): named = helpers.parse_bool(named_expr) else: named = False if flat and named: ctx.api.fail("'flat' and 'named' can't be used together", ctx.context) return helpers.reparametrize_instance(ctx.default_return_type, [model_type, AnyType(TypeOfAny.from_error)]) # account for possible None flat = flat or False named = named or False row_type = get_values_list_row_type(ctx, django_context, model_cls, flat=flat, named=named) return helpers.reparametrize_instance(ctx.default_return_type, [model_type, row_type]) def resolve_field_lookups(lookup_exprs: Sequence[Expression], django_context: DjangoContext) -> Optional[List[str]]: field_lookups = [] for field_lookup_expr in lookup_exprs: field_lookup = helpers.resolve_string_attribute_value(field_lookup_expr, django_context) if field_lookup is None: return None field_lookups.append(field_lookup) return field_lookups def extract_proper_type_queryset_values(ctx: MethodContext, django_context: DjangoContext) -> MypyType: # called on QuerySet, return QuerySet of something assert isinstance(ctx.type, Instance) assert isinstance(ctx.default_return_type, Instance) model_type = _extract_model_type_from_queryset(ctx.type) if model_type is None: return AnyType(TypeOfAny.from_omitted_generics) model_cls = django_context.get_model_class_by_fullname(model_type.type.fullname) if model_cls is None: return ctx.default_return_type field_lookups = resolve_field_lookups(ctx.args[0], django_context) if field_lookups is None: return AnyType(TypeOfAny.from_error) if len(field_lookups) == 0: for field in django_context.get_model_fields(model_cls): field_lookups.append(field.attname) column_types: 'OrderedDict[str, MypyType]' = OrderedDict() for field_lookup in field_lookups: field_lookup_type = get_field_type_from_lookup(ctx, django_context, model_cls, lookup=field_lookup, method='values') if field_lookup_type is None: return helpers.reparametrize_instance(ctx.default_return_type, [model_type, AnyType(TypeOfAny.from_error)]) column_types[field_lookup] = field_lookup_type row_type = helpers.make_typeddict(ctx.api, column_types, set(column_types.keys())) return helpers.reparametrize_instance(ctx.default_return_type, [model_type, row_type])
8,440
Python
.py
153
45.79085
119
0.683317
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,878
fields.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/fields.py
from typing import Optional, Tuple, cast from django.db.models.fields import Field from django.db.models.fields.related import RelatedField from mypy.nodes import AssignmentStmt, NameExpr, TypeInfo from mypy.plugin import FunctionContext from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny from mypy_django_plugin.django.context import DjangoContext from mypy_django_plugin.lib import fullnames, helpers def _get_current_field_from_assignment(ctx: FunctionContext, django_context: DjangoContext) -> Optional[Field]: outer_model_info = helpers.get_typechecker_api(ctx).scope.active_class() if (outer_model_info is None or not helpers.is_model_subclass_info(outer_model_info, django_context)): return None field_name = None for stmt in outer_model_info.defn.defs.body: if isinstance(stmt, AssignmentStmt): if stmt.rvalue == ctx.context: if not isinstance(stmt.lvalues[0], NameExpr): return None field_name = stmt.lvalues[0].name break if field_name is None: return None model_cls = django_context.get_model_class_by_fullname(outer_model_info.fullname) if model_cls is None: return None current_field = model_cls._meta.get_field(field_name) return current_field def reparametrize_related_field_type(related_field_type: Instance, set_type, get_type) -> Instance: args = [ helpers.convert_any_to_type(related_field_type.args[0], set_type), helpers.convert_any_to_type(related_field_type.args[1], get_type), ] return helpers.reparametrize_instance(related_field_type, new_args=args) def fill_descriptor_types_for_related_field(ctx: FunctionContext, django_context: DjangoContext) -> MypyType: current_field = _get_current_field_from_assignment(ctx, django_context) if current_field is None: return AnyType(TypeOfAny.from_error) assert isinstance(current_field, RelatedField) related_model_cls = django_context.get_field_related_model_cls(current_field) if related_model_cls is None: return AnyType(TypeOfAny.from_error) default_related_field_type = set_descriptor_types_for_field(ctx) # self reference with abstract=True on the model where ForeignKey is defined current_model_cls = current_field.model if (current_model_cls._meta.abstract and current_model_cls == related_model_cls): # for all derived non-abstract classes, set variable with this name to # __get__/__set__ of ForeignKey of derived model for model_cls in django_context.all_registered_model_classes: if issubclass(model_cls, current_model_cls) and not model_cls._meta.abstract: derived_model_info = helpers.lookup_class_typeinfo(helpers.get_typechecker_api(ctx), model_cls) if derived_model_info is not None: fk_ref_type = Instance(derived_model_info, []) derived_fk_type = reparametrize_related_field_type(default_related_field_type, set_type=fk_ref_type, get_type=fk_ref_type) helpers.add_new_sym_for_info(derived_model_info, name=current_field.name, sym_type=derived_fk_type) related_model = related_model_cls related_model_to_set = related_model_cls if related_model_to_set._meta.proxy_for_model is not None: related_model_to_set = related_model_to_set._meta.proxy_for_model typechecker_api = helpers.get_typechecker_api(ctx) related_model_info = helpers.lookup_class_typeinfo(typechecker_api, related_model) if related_model_info is None: # maybe no type stub related_model_type = AnyType(TypeOfAny.unannotated) else: related_model_type = Instance(related_model_info, []) # type: ignore related_model_to_set_info = helpers.lookup_class_typeinfo(typechecker_api, related_model_to_set) if related_model_to_set_info is None: # maybe no type stub related_model_to_set_type = AnyType(TypeOfAny.unannotated) else: related_model_to_set_type = Instance(related_model_to_set_info, []) # type: ignore # replace Any with referred_to_type return reparametrize_related_field_type(default_related_field_type, set_type=related_model_to_set_type, get_type=related_model_type) def get_field_descriptor_types(field_info: TypeInfo, is_nullable: bool) -> Tuple[MypyType, MypyType]: set_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_set_type', is_nullable=is_nullable) get_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_get_type', is_nullable=is_nullable) return set_type, get_type def set_descriptor_types_for_field(ctx: FunctionContext) -> Instance: default_return_type = cast(Instance, ctx.default_return_type) is_nullable = False null_expr = helpers.get_call_argument_by_name(ctx, 'null') if null_expr is not None: is_nullable = helpers.parse_bool(null_expr) or False set_type, get_type = get_field_descriptor_types(default_return_type.type, is_nullable) return helpers.reparametrize_instance(default_return_type, [set_type, get_type]) def determine_type_of_array_field(ctx: FunctionContext, django_context: DjangoContext) -> MypyType: default_return_type = set_descriptor_types_for_field(ctx) base_field_arg_type = helpers.get_call_argument_type_by_name(ctx, 'base_field') if not base_field_arg_type or not isinstance(base_field_arg_type, Instance): return default_return_type base_type = base_field_arg_type.args[1] # extract __get__ type args = [] for default_arg in default_return_type.args: args.append(helpers.convert_any_to_type(default_arg, base_type)) return helpers.reparametrize_instance(default_return_type, args) def transform_into_proper_return_type(ctx: FunctionContext, django_context: DjangoContext) -> MypyType: default_return_type = ctx.default_return_type assert isinstance(default_return_type, Instance) outer_model_info = helpers.get_typechecker_api(ctx).scope.active_class() if (outer_model_info is None or not helpers.is_model_subclass_info(outer_model_info, django_context)): return ctx.default_return_type assert isinstance(outer_model_info, TypeInfo) if helpers.has_any_of_bases(default_return_type.type, fullnames.RELATED_FIELDS_CLASSES): return fill_descriptor_types_for_related_field(ctx, django_context) if default_return_type.type.has_base(fullnames.ARRAY_FIELD_FULLNAME): return determine_type_of_array_field(ctx, django_context) return set_descriptor_types_for_field(ctx)
7,101
Python
.py
119
49.957983
114
0.688796
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,879
forms.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/forms.py
from typing import Optional from mypy.plugin import ClassDefContext, MethodContext from mypy.types import CallableType, Instance, NoneTyp from mypy.types import Type as MypyType from mypy.types import TypeType from mypy_django_plugin.lib import helpers def make_meta_nested_class_inherit_from_any(ctx: ClassDefContext) -> None: meta_node = helpers.get_nested_meta_node_for_current_class(ctx.cls.info) if meta_node is None: if not ctx.api.final_iteration: ctx.api.defer() else: meta_node.fallback_to_any = True def get_specified_form_class(object_type: Instance) -> Optional[TypeType]: form_class_sym = object_type.type.get('form_class') if form_class_sym and isinstance(form_class_sym.type, CallableType): return TypeType(form_class_sym.type.ret_type) return None def extract_proper_type_for_get_form(ctx: MethodContext) -> MypyType: object_type = ctx.type assert isinstance(object_type, Instance) form_class_type = helpers.get_call_argument_type_by_name(ctx, 'form_class') if form_class_type is None or isinstance(form_class_type, NoneTyp): form_class_type = get_specified_form_class(object_type) if isinstance(form_class_type, TypeType) and isinstance(form_class_type.item, Instance): return form_class_type.item if isinstance(form_class_type, CallableType) and isinstance(form_class_type.ret_type, Instance): return form_class_type.ret_type return ctx.default_return_type def extract_proper_type_for_get_form_class(ctx: MethodContext) -> MypyType: object_type = ctx.type assert isinstance(object_type, Instance) form_class_type = get_specified_form_class(object_type) if form_class_type is None: return ctx.default_return_type return form_class_type
1,809
Python
.py
36
44.916667
100
0.746158
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,880
managers.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/transformers/managers.py
from mypy.nodes import ( GDEF, FuncDef, MemberExpr, NameExpr, RefExpr, StrExpr, SymbolTableNode, TypeInfo, ) from mypy.plugin import ClassDefContext, DynamicClassDefContext from mypy.types import AnyType, Instance, TypeOfAny from mypy_django_plugin.lib import fullnames, helpers def create_new_manager_class_from_from_queryset_method(ctx: DynamicClassDefContext) -> None: semanal_api = helpers.get_semanal_api(ctx) callee = ctx.call.callee assert isinstance(callee, MemberExpr) assert isinstance(callee.expr, RefExpr) base_manager_info = callee.expr.node if base_manager_info is None: if not semanal_api.final_iteration: semanal_api.defer() return assert isinstance(base_manager_info, TypeInfo) new_manager_info = semanal_api.basic_new_typeinfo(ctx.name, basetype_or_fallback=Instance(base_manager_info, [AnyType(TypeOfAny.unannotated)])) new_manager_info.line = ctx.call.line new_manager_info.defn.line = ctx.call.line new_manager_info.metaclass_type = new_manager_info.calculate_metaclass_type() current_module = semanal_api.cur_mod_node current_module.names[ctx.name] = SymbolTableNode(GDEF, new_manager_info, plugin_generated=True) passed_queryset = ctx.call.args[0] assert isinstance(passed_queryset, NameExpr) derived_queryset_fullname = passed_queryset.fullname assert derived_queryset_fullname is not None sym = semanal_api.lookup_fully_qualified_or_none(derived_queryset_fullname) assert sym is not None if sym.node is None: if not semanal_api.final_iteration: semanal_api.defer() else: # inherit from Any to prevent false-positives, if queryset class cannot be resolved new_manager_info.fallback_to_any = True return derived_queryset_info = sym.node assert isinstance(derived_queryset_info, TypeInfo) if len(ctx.call.args) > 1: expr = ctx.call.args[1] assert isinstance(expr, StrExpr) custom_manager_generated_name = expr.value else: custom_manager_generated_name = base_manager_info.name + 'From' + derived_queryset_info.name custom_manager_generated_fullname = '.'.join(['django.db.models.manager', custom_manager_generated_name]) if 'from_queryset_managers' not in base_manager_info.metadata: base_manager_info.metadata['from_queryset_managers'] = {} base_manager_info.metadata['from_queryset_managers'][custom_manager_generated_fullname] = new_manager_info.fullname class_def_context = ClassDefContext(cls=new_manager_info.defn, reason=ctx.call, api=semanal_api) self_type = Instance(new_manager_info, []) # we need to copy all methods in MRO before django.db.models.query.QuerySet for class_mro_info in derived_queryset_info.mro: if class_mro_info.fullname == fullnames.QUERYSET_CLASS_FULLNAME: break for name, sym in class_mro_info.names.items(): if isinstance(sym.node, FuncDef): helpers.copy_method_to_another_class(class_def_context, self_type, new_method_name=name, method_node=sym.node)
3,523
Python
.py
64
42.875
119
0.646547
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,881
context.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/mypy_django_plugin/django/context.py
import os import sys from collections import defaultdict from contextlib import contextmanager from typing import ( TYPE_CHECKING, Dict, Iterable, Iterator, Optional, Set, Tuple, Type, Union, ) from django.core.exceptions import FieldError from django.db import models from django.db.models.base import Model from django.db.models.fields import AutoField, CharField, Field from django.db.models.fields.related import ForeignKey, RelatedField from django.db.models.fields.reverse_related import ForeignObjectRel from django.db.models.lookups import Exact from django.db.models.sql.query import Query from django.utils.functional import cached_property from mypy.checker import TypeChecker from mypy.plugin import MethodContext from mypy.types import AnyType, Instance from mypy.types import Type as MypyType from mypy.types import TypeOfAny, UnionType from mypy_django_plugin.lib import fullnames, helpers try: from django.contrib.postgres.fields import ArrayField except ImportError: class ArrayField: # type: ignore pass if TYPE_CHECKING: from django.apps.registry import Apps # noqa: F401 from django.conf import LazySettings # noqa: F401 @contextmanager def temp_environ(): """Allow the ability to set os.environ temporarily""" environ = dict(os.environ) try: yield finally: os.environ.clear() os.environ.update(environ) def initialize_django(settings_module: str) -> Tuple['Apps', 'LazySettings']: with temp_environ(): os.environ['DJANGO_SETTINGS_MODULE'] = settings_module # add current directory to sys.path sys.path.append(os.getcwd()) def noop_class_getitem(cls, key): return cls from django.db import models models.QuerySet.__class_getitem__ = classmethod(noop_class_getitem) # type: ignore models.Manager.__class_getitem__ = classmethod(noop_class_getitem) # type: ignore from django.conf import settings from django.apps import apps apps.get_models.cache_clear() # type: ignore apps.get_swappable_settings_name.cache_clear() # type: ignore if not settings.configured: settings._setup() apps.populate(settings.INSTALLED_APPS) assert apps.apps_ready assert settings.configured return apps, settings class LookupsAreUnsupported(Exception): pass class DjangoContext: def __init__(self, django_settings_module: str) -> None: self.django_settings_module = django_settings_module apps, settings = initialize_django(self.django_settings_module) self.apps_registry = apps self.settings = settings @cached_property def model_modules(self) -> Dict[str, Set[Type[Model]]]: """ All modules that contain Django models. """ if self.apps_registry is None: return {} modules: Dict[str, Set[Type[Model]]] = defaultdict(set) for concrete_model_cls in self.apps_registry.get_models(): modules[concrete_model_cls.__module__].add(concrete_model_cls) # collect abstract=True models for model_cls in concrete_model_cls.mro()[1:]: if (issubclass(model_cls, Model) and hasattr(model_cls, '_meta') and model_cls._meta.abstract): modules[model_cls.__module__].add(model_cls) return modules def get_model_class_by_fullname(self, fullname: str) -> Optional[Type[Model]]: # Returns None if Model is abstract module, _, model_cls_name = fullname.rpartition('.') for model_cls in self.model_modules.get(module, set()): if model_cls.__name__ == model_cls_name: return model_cls return None def get_model_fields(self, model_cls: Type[Model]) -> Iterator[Field]: for field in model_cls._meta.get_fields(): if isinstance(field, Field): yield field def get_model_relations(self, model_cls: Type[Model]) -> Iterator[ForeignObjectRel]: for field in model_cls._meta.get_fields(): if isinstance(field, ForeignObjectRel): yield field def get_field_lookup_exact_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel]) -> MypyType: if isinstance(field, (RelatedField, ForeignObjectRel)): related_model_cls = field.related_model primary_key_field = self.get_primary_key_field(related_model_cls) primary_key_type = self.get_field_get_type(api, primary_key_field, method='init') rel_model_info = helpers.lookup_class_typeinfo(api, related_model_cls) if rel_model_info is None: return AnyType(TypeOfAny.explicit) model_and_primary_key_type = UnionType.make_union([Instance(rel_model_info, []), primary_key_type]) return helpers.make_optional(model_and_primary_key_type) field_info = helpers.lookup_class_typeinfo(api, field.__class__) if field_info is None: return AnyType(TypeOfAny.explicit) return helpers.get_private_descriptor_type(field_info, '_pyi_lookup_exact_type', is_nullable=field.null) def get_primary_key_field(self, model_cls: Type[Model]) -> Field: for field in model_cls._meta.get_fields(): if isinstance(field, Field): if field.primary_key: return field raise ValueError('No primary key defined') def get_expected_types(self, api: TypeChecker, model_cls: Type[Model], *, method: str) -> Dict[str, MypyType]: from django.contrib.contenttypes.fields import GenericForeignKey expected_types = {} # add pk if not abstract=True if not model_cls._meta.abstract: primary_key_field = self.get_primary_key_field(model_cls) field_set_type = self.get_field_set_type(api, primary_key_field, method=method) expected_types['pk'] = field_set_type for field in model_cls._meta.get_fields(): if isinstance(field, Field): field_name = field.attname field_set_type = self.get_field_set_type(api, field, method=method) expected_types[field_name] = field_set_type if isinstance(field, ForeignKey): field_name = field.name foreign_key_info = helpers.lookup_class_typeinfo(api, field.__class__) if foreign_key_info is None: # maybe there's no type annotation for the field expected_types[field_name] = AnyType(TypeOfAny.unannotated) continue related_model = self.get_field_related_model_cls(field) if related_model is None: expected_types[field_name] = AnyType(TypeOfAny.from_error) continue if related_model._meta.proxy_for_model is not None: related_model = related_model._meta.proxy_for_model related_model_info = helpers.lookup_class_typeinfo(api, related_model) if related_model_info is None: expected_types[field_name] = AnyType(TypeOfAny.unannotated) continue is_nullable = self.get_field_nullability(field, method) foreign_key_set_type = helpers.get_private_descriptor_type(foreign_key_info, '_pyi_private_set_type', is_nullable=is_nullable) model_set_type = helpers.convert_any_to_type(foreign_key_set_type, Instance(related_model_info, [])) expected_types[field_name] = model_set_type elif isinstance(field, GenericForeignKey): # it's generic, so cannot set specific model field_name = field.name gfk_info = helpers.lookup_class_typeinfo(api, field.__class__) gfk_set_type = helpers.get_private_descriptor_type(gfk_info, '_pyi_private_set_type', is_nullable=True) expected_types[field_name] = gfk_set_type return expected_types @cached_property def all_registered_model_classes(self) -> Set[Type[models.Model]]: model_classes = self.apps_registry.get_models() all_model_bases = set() for model_cls in model_classes: for base_cls in model_cls.mro(): if issubclass(base_cls, models.Model): all_model_bases.add(base_cls) return all_model_bases @cached_property def all_registered_model_class_fullnames(self) -> Set[str]: return {helpers.get_class_fullname(cls) for cls in self.all_registered_model_classes} def get_attname(self, field: Field) -> str: attname = field.attname return attname def get_field_nullability(self, field: Union[Field, ForeignObjectRel], method: Optional[str]) -> bool: nullable = field.null if not nullable and isinstance(field, CharField) and field.blank: return True if method == '__init__': if ((isinstance(field, Field) and field.primary_key) or isinstance(field, ForeignKey)): return True if method == 'create': if isinstance(field, AutoField): return True if isinstance(field, Field) and field.has_default(): return True return nullable def get_field_set_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType: """ Get a type of __set__ for this specific Django field. """ target_field = field if isinstance(field, ForeignKey): target_field = field.target_field field_info = helpers.lookup_class_typeinfo(api, target_field.__class__) if field_info is None: return AnyType(TypeOfAny.from_error) field_set_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_set_type', is_nullable=self.get_field_nullability(field, method)) if isinstance(target_field, ArrayField): argument_field_type = self.get_field_set_type(api, target_field.base_field, method=method) field_set_type = helpers.convert_any_to_type(field_set_type, argument_field_type) return field_set_type def get_field_get_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType: """ Get a type of __get__ for this specific Django field. """ field_info = helpers.lookup_class_typeinfo(api, field.__class__) if field_info is None: return AnyType(TypeOfAny.unannotated) is_nullable = self.get_field_nullability(field, method) if isinstance(field, RelatedField): related_model_cls = self.get_field_related_model_cls(field) if related_model_cls is None: return AnyType(TypeOfAny.from_error) if method == 'values': primary_key_field = self.get_primary_key_field(related_model_cls) return self.get_field_get_type(api, primary_key_field, method=method) model_info = helpers.lookup_class_typeinfo(api, related_model_cls) if model_info is None: return AnyType(TypeOfAny.unannotated) return Instance(model_info, []) else: return helpers.get_private_descriptor_type(field_info, '_pyi_private_get_type', is_nullable=is_nullable) def get_field_related_model_cls(self, field: Union[RelatedField, ForeignObjectRel]) -> Optional[Type[Model]]: if isinstance(field, RelatedField): related_model_cls = field.remote_field.model else: related_model_cls = field.field.model if isinstance(related_model_cls, str): if related_model_cls == 'self': # same model related_model_cls = field.model elif '.' not in related_model_cls: # same file model related_model_fullname = field.model.__module__ + '.' + related_model_cls related_model_cls = self.get_model_class_by_fullname(related_model_fullname) else: related_model_cls = self.apps_registry.get_model(related_model_cls) return related_model_cls def _resolve_field_from_parts(self, field_parts: Iterable[str], model_cls: Type[Model] ) -> Union[Field, ForeignObjectRel]: currently_observed_model = model_cls field = None for field_part in field_parts: if field_part == 'pk': field = self.get_primary_key_field(currently_observed_model) continue field = currently_observed_model._meta.get_field(field_part) if isinstance(field, RelatedField): currently_observed_model = field.related_model model_name = currently_observed_model._meta.model_name if (model_name is not None and field_part == (model_name + '_id')): field = self.get_primary_key_field(currently_observed_model) if isinstance(field, ForeignObjectRel): currently_observed_model = field.related_model assert field is not None return field def resolve_lookup_into_field(self, model_cls: Type[Model], lookup: str) -> Union[Field, ForeignObjectRel]: query = Query(model_cls) lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup) if lookup_parts: raise LookupsAreUnsupported() return self._resolve_field_from_parts(field_parts, model_cls) def resolve_lookup_expected_type(self, ctx: MethodContext, model_cls: Type[Model], lookup: str) -> MypyType: query = Query(model_cls) try: lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup) if is_expression: return AnyType(TypeOfAny.explicit) except FieldError as exc: ctx.api.fail(exc.args[0], ctx.context) return AnyType(TypeOfAny.from_error) field = self._resolve_field_from_parts(field_parts, model_cls) lookup_cls = None if lookup_parts: lookup = lookup_parts[-1] lookup_cls = field.get_lookup(lookup) if lookup_cls is None: # unknown lookup return AnyType(TypeOfAny.explicit) if lookup_cls is None or isinstance(lookup_cls, Exact): return self.get_field_lookup_exact_type(helpers.get_typechecker_api(ctx), field) assert lookup_cls is not None lookup_info = helpers.lookup_class_typeinfo(helpers.get_typechecker_api(ctx), lookup_cls) if lookup_info is None: return AnyType(TypeOfAny.explicit) for lookup_base in helpers.iter_bases(lookup_info): if lookup_base.args and isinstance(lookup_base.args[0], Instance): lookup_type: MypyType = lookup_base.args[0] # if it's Field, consider lookup_type a __get__ of current field if (isinstance(lookup_type, Instance) and lookup_type.type.fullname == fullnames.FIELD_FULLNAME): field_info = helpers.lookup_class_typeinfo(helpers.get_typechecker_api(ctx), field.__class__) if field_info is None: return AnyType(TypeOfAny.explicit) lookup_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_get_type', is_nullable=field.null) return lookup_type return AnyType(TypeOfAny.explicit) def resolve_f_expression_type(self, f_expression_type: Instance) -> MypyType: return AnyType(TypeOfAny.explicit)
16,593
Python
.py
307
40.954397
118
0.61425
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,882
django_tests_settings.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/django_tests_settings.py
import django SECRET_KEY = '1' SITE_ID = 1 INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.staticfiles', ] test_modules = [ 'absolute_url_overrides', 'admin_autodiscover', 'admin_changelist', 'admin_checks', 'admin_custom_urls', 'admin_default_site', 'admin_docs', 'admin_filters', 'admin_inlines', 'admin_ordering', 'admin_registration', 'admin_scripts', 'admin_utils', 'admin_views', 'admin_widgets', 'aggregation', 'aggregation_regress', 'annotations', 'app_loading', 'apps', 'auth_tests', 'backends', 'base', 'bash_completion', 'basic', 'builtin_server', 'bulk_create', 'cache', 'check_framework', 'conditional_processing', 'constraints', 'contenttypes_tests', 'context_processors', 'csrf_tests', 'custom_columns', 'custom_lookups', 'custom_managers', 'custom_methods', 'custom_migration_operations', 'custom_pk', 'datatypes', 'dates', 'datetimes', 'db_functions', 'db_typecasts', 'db_utils', 'dbshell', 'decorators', 'defer', 'defer_regress', 'delete', 'delete_regress', 'deprecation', 'dispatch', 'distinct_on_fields', 'empty', 'expressions', 'expressions_case', 'expressions_window', 'extra_regress', 'field_deconstruction', 'field_defaults', 'field_subclassing', 'file_storage', 'file_uploads', 'files', 'filtered_relation', 'fixtures', 'fixtures_model_package', 'fixtures_regress', 'flatpages_tests', 'force_insert_update', 'foreign_object', 'forms_tests', 'from_db_value', 'generic_inline_admin', 'generic_relations', 'generic_relations_regress', 'generic_views', 'get_earliest_or_latest', 'get_object_or_404', 'get_or_create', 'gis_tests', 'handlers', 'httpwrappers', 'humanize_tests', 'i18n', 'import_error_package', 'indexes', 'inline_formsets', 'inspectdb', 'introspection', 'invalid_models_tests', 'known_related_objects', 'logging_tests', 'lookup', 'm2m_and_m2o', 'm2m_intermediary', 'm2m_multiple', 'm2m_recursive', 'm2m_regress', 'm2m_signals', 'm2m_through', 'm2m_through_regress', 'm2o_recursive', 'mail', 'managers_regress', 'many_to_many', 'many_to_one', 'many_to_one_null', 'max_lengths', 'messages_tests', 'middleware', 'middleware_exceptions', 'migrate_signals', 'migration_test_data_persistence', 'migrations', 'migrations2', 'model_fields', 'model_forms', 'model_formsets', 'model_formsets_regress', 'model_indexes', 'model_inheritance', 'model_inheritance_regress', 'model_meta', 'model_options', 'model_package', 'model_regress', 'modeladmin', 'multiple_database', 'mutually_referential', 'nested_foreign_keys', 'no_models', 'null_fk', 'null_fk_ordering', 'null_queries', 'one_to_one', 'or_lookups', 'order_with_respect_to', 'ordering', 'pagination', 'postgres_tests', 'prefetch_related', 'project_template', 'properties', 'proxy_model_inheritance', 'proxy_models', 'queries', 'queryset_pickle', 'raw_query', 'redirects_tests', 'requests', 'reserved_names', 'resolve_url', 'responses', 'reverse_lookup', 'save_delete_hooks', 'schema', 'select_for_update', 'select_related', 'select_related_onetoone', 'select_related_regress', 'serializers', 'servers', 'sessions_tests', 'settings_tests', 'shell', 'shortcuts', 'signals', 'signed_cookies_tests', 'signing', 'sitemaps_tests', 'sites_framework', 'sites_tests', 'staticfiles_tests', 'str', 'string_lookup', 'swappable_models', 'syndication_tests', 'template_backends', 'template_loader', 'template_tests', 'test_client', 'test_client_regress', 'test_exceptions', 'test_runner', 'test_runner_apps', 'test_utils', 'timezones', 'transaction_hooks', 'transactions', 'unmanaged_models', 'update', 'update_only_fields', 'urlpatterns', 'urlpatterns_reverse', 'user_commands', 'utils_tests', 'validation', 'validators', 'version', 'view_tests', 'wsgi', ] if django.VERSION[0] == 2: test_modules += ['choices'] invalid_apps = { 'import_error_package', } for app in invalid_apps: test_modules.remove(app) INSTALLED_APPS += test_modules
4,831
Python
.py
226
16.557522
50
0.616572
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,883
build_import_all_test.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/build_import_all_test.py
import os from pathlib import Path from typing import List STUBS_ROOT = Path(__file__).parent.parent / 'django-stubs' def build_package_name(path: str) -> str: return '.'.join(['django'] + list(Path(path).relative_to(STUBS_ROOT).with_suffix('').parts)) packages: List[str] = [] for dirpath, dirnames, filenames in os.walk(STUBS_ROOT): if not dirnames: package = build_package_name(dirpath) packages.append(package) for filename in filenames: if filename != '__init__.pyi': package = build_package_name(os.path.join(dirpath, filename)) packages.append(package) test_lines: List[str] = [] for package in packages: test_lines.append('import ' + package) test_contents = '\n'.join(sorted(test_lines)) print(test_contents)
790
Python
.py
20
34.9
96
0.687664
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,884
tests_extension_hook.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/tests_extension_hook.py
from pytest_mypy_plugins.collect import File from pytest_mypy_plugins.item import YamlTestItem def django_plugin_hook(test_item: YamlTestItem) -> None: custom_settings = test_item.parsed_test_data.get('custom_settings', '') installed_apps = test_item.parsed_test_data.get('installed_apps', None) if installed_apps and custom_settings: raise ValueError('"installed_apps" and "custom_settings" are not compatible, please use one or the other') if installed_apps is not None: # custom_settings is empty, add INSTALLED_APPS installed_apps += ['django.contrib.contenttypes'] installed_apps_as_str = '(' + ','.join([repr(app) for app in installed_apps]) + ',)' custom_settings += 'INSTALLED_APPS = ' + installed_apps_as_str if 'SECRET_KEY' not in custom_settings: custom_settings = 'SECRET_KEY = "1"\n' + custom_settings django_settings_section = "\n[mypy.plugins.django-stubs]\n" \ "django_settings_module = mysettings" if not test_item.additional_mypy_config: test_item.additional_mypy_config = django_settings_section else: if '[mypy.plugins.django-stubs]' not in test_item.additional_mypy_config: test_item.additional_mypy_config += django_settings_section mysettings_file = File(path='mysettings.py', content=custom_settings) test_item.files.append(mysettings_file)
1,418
Python
.py
23
54
114
0.695245
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,885
mypy.ini
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/mypy.ini
[mypy] strict_optional = True ignore_missing_imports = True check_untyped_defs = True warn_no_return = False show_traceback = True allow_redefinition = True incremental = True plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = 'scripts.django_tests_settings'
301
Python
.py
12
23.583333
56
0.804878
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,886
catch_non_abstract_annotation.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/catch_non_abstract_annotation.py
import os from typing import Optional import libcst from libcst import Annotation, BaseExpression, FunctionDef, Name, Subscript from libcst.metadata import SyntacticPositionProvider BASE_DIR = 'django-stubs' fpath = os.path.join(BASE_DIR, 'core', 'checks', 'model_checks.pyi') with open(fpath, 'r') as f: contents = f.read() tree = libcst.parse_module(contents) class TypeAnnotationsAnalyzer(libcst.CSTVisitor): METADATA_DEPENDENCIES = (SyntacticPositionProvider,) def __init__(self, fpath: str): super().__init__() self.fpath = fpath def get_node_location(self, node: FunctionDef) -> str: start_line = self.get_metadata(SyntacticPositionProvider, node).start.line return f'{self.fpath}:{start_line}' def show_error_for_node(self, node: FunctionDef, error_message: str): print(self.get_node_location(node), error_message) def check_subscripted_annotation(self, annotation: BaseExpression) -> Optional[str]: if isinstance(annotation, Subscript): if isinstance(annotation.value, Name): error_message = self.check_concrete_class_usage(annotation.value) if error_message: return error_message if annotation.value.value == 'Union': for slice_param in annotation.slice: if isinstance(slice_param.slice.value, Name): error_message = self.check_concrete_class_usage(annotation.value) if error_message: return error_message def check_concrete_class_usage(self, name_node: Name) -> Optional[str]: if name_node.value == 'List': return (f'Concrete class {name_node.value!r} used for an iterable annotation. ' f'Use abstract collection (Iterable, Collection, Sequence) instead') def visit_FunctionDef(self, node: FunctionDef) -> Optional[bool]: params_node = node.params for param_node in [*params_node.params, *params_node.default_params]: param_name = param_node.name.value annotation_node = param_node.annotation # type: Annotation if annotation_node is not None: annotation = annotation_node.annotation if annotation.value == 'None': self.show_error_for_node(node, f'"None" type annotation used for parameter {param_name!r}') continue error_message = self.check_subscripted_annotation(annotation) if error_message is not None: self.show_error_for_node(node, error_message) continue if node.returns is not None: return_annotation = node.returns.annotation if isinstance(return_annotation, Subscript) and return_annotation.value.value == 'Union': self.show_error_for_node(node, 'Union is return type annotation') return False for dirpath, dirnames, filenames in os.walk(BASE_DIR): for filename in filenames: fpath = os.path.join(dirpath, filename) # skip all other checks for now, low priority if not fpath.startswith(('django-stubs/db', 'django-stubs/views', 'django-stubs/apps', 'django-stubs/http', 'django-stubs/contrib/postgres')): continue with open(fpath, 'r') as f: contents = f.read() tree = libcst.MetadataWrapper(libcst.parse_module(contents)) analyzer = TypeAnnotationsAnalyzer(fpath) tree.visit(analyzer)
3,606
Python
.py
67
42.402985
111
0.640705
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,887
typecheck_tests.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/typecheck_tests.py
import itertools import shutil import subprocess import sys from argparse import ArgumentParser from collections import defaultdict from pathlib import Path from typing import Dict, List, Pattern, Tuple, Union from git import RemoteProgress, Repo from scripts.enabled_test_modules import ( EXTERNAL_MODULES, IGNORED_ERRORS, IGNORED_MODULES, MOCK_OBJECTS, ) DJANGO_COMMIT_REFS: Dict[str, Tuple[str, str]] = { '2.2': ('stable/2.2.x', '996be04c3ceb456754d9d527d4d708f30727f07e'), '3.0': ('stable/3.0.x', 'd9f1792c7649e9f946f4a3a35a76bddf5a412b8b') } PROJECT_DIRECTORY = Path(__file__).parent.parent DJANGO_SOURCE_DIRECTORY = PROJECT_DIRECTORY / 'django-sources' # type: Path def get_unused_ignores(ignored_message_freq: Dict[str, Dict[Union[str, Pattern], int]]) -> List[str]: unused_ignores = [] for root_key, patterns in IGNORED_ERRORS.items(): for pattern in patterns: if (ignored_message_freq[root_key][pattern] == 0 and pattern not in itertools.chain(EXTERNAL_MODULES, MOCK_OBJECTS)): unused_ignores.append(f'{root_key}: {pattern}') return unused_ignores def is_pattern_fits(pattern: Union[Pattern, str], line: str): if isinstance(pattern, Pattern): if pattern.search(line): return True else: if pattern in line: return True return False def is_ignored(line: str, test_folder_name: str, *, ignored_message_freqs: Dict[str, Dict[str, int]]) -> bool: if 'runtests' in line: return True if test_folder_name in IGNORED_MODULES: return True for pattern in IGNORED_ERRORS.get(test_folder_name, []): if is_pattern_fits(pattern, line): ignored_message_freqs[test_folder_name][pattern] += 1 return True for pattern in IGNORED_ERRORS['__common__']: if is_pattern_fits(pattern, line): ignored_message_freqs['__common__'][pattern] += 1 return True return False def replace_with_clickable_location(error: str, abs_test_folder: Path) -> str: raw_path, _, error_line = error.partition(': ') fname, _, line_number = raw_path.partition(':') try: path = abs_test_folder.joinpath(fname).relative_to(PROJECT_DIRECTORY) except ValueError: # fail on travis, just show an error return error clickable_location = f'./{path}:{line_number or 1}' return error.replace(raw_path, clickable_location) class ProgressPrinter(RemoteProgress): def line_dropped(self, line: str) -> None: print(line) def update(self, op_code, cur_count, max_count=None, message=''): print(self._cur_line) def get_django_repo_object(branch: str) -> Repo: if not DJANGO_SOURCE_DIRECTORY.exists(): DJANGO_SOURCE_DIRECTORY.mkdir(exist_ok=True, parents=False) return Repo.clone_from('https://github.com/django/django.git', DJANGO_SOURCE_DIRECTORY, progress=ProgressPrinter(), branch=branch, depth=100) else: repo = Repo(DJANGO_SOURCE_DIRECTORY) return repo if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--django_version', choices=['2.2', '3.0'], required=True) args = parser.parse_args() # install proper Django version subprocess.check_call([sys.executable, '-m', 'pip', 'install', f'Django=={args.django_version}.*']) branch, commit_sha = DJANGO_COMMIT_REFS[args.django_version] repo = get_django_repo_object(branch) if repo.head.commit.hexsha != commit_sha: repo.remote('origin').fetch(branch, progress=ProgressPrinter(), depth=100) repo.git.checkout(commit_sha) mypy_config_file = (PROJECT_DIRECTORY / 'scripts' / 'mypy.ini').absolute() mypy_cache_dir = Path(__file__).parent / '.mypy_cache' tests_root = DJANGO_SOURCE_DIRECTORY / 'tests' global_rc = 0 try: mypy_options = ['--cache-dir', str(mypy_config_file.parent / '.mypy_cache'), '--config-file', str(mypy_config_file), '--show-traceback', '--no-error-summary', '--hide-error-context' ] mypy_options += [str(tests_root)] import distutils.spawn mypy_executable = distutils.spawn.find_executable('mypy') mypy_argv = [mypy_executable, *mypy_options] completed = subprocess.run( mypy_argv, env={'PYTHONPATH': str(tests_root)}, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) output = completed.stdout.decode() ignored_message_freqs = defaultdict(lambda: defaultdict(int)) sorted_lines = sorted(output.splitlines()) for line in sorted_lines: try: path_to_error = line.split(':')[0] test_folder_name = path_to_error.split('/')[2] except IndexError: test_folder_name = 'unknown' if not is_ignored(line, test_folder_name, ignored_message_freqs=ignored_message_freqs): global_rc = 1 print(line) unused_ignores = get_unused_ignores(ignored_message_freqs) if unused_ignores: print('UNUSED IGNORES ------------------------------------------------') print('\n'.join(unused_ignores)) sys.exit(global_rc) except BaseException as exc: shutil.rmtree(mypy_cache_dir, ignore_errors=True) raise exc
5,627
Python
.py
126
35.634921
110
0.62269
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,888
enabled_test_modules.py
DamnWidget_anaconda/anaconda_lib/jedi/third_party/django-stubs/scripts/enabled_test_modules.py
# Some errors occur for the test suite itself, and cannot be addressed via django-stubs. They should be ignored # using this constant. import re IGNORED_MODULES = {'schema', 'gis_tests', 'admin_widgets', 'admin_filters', 'sitemaps_tests', 'staticfiles_tests', 'modeladmin', 'generic_views', 'forms_tests', 'flatpages_tests', 'admin_ordering', 'admin_changelist', 'admin_views', 'invalid_models_tests', 'i18n', 'model_formsets', 'template_tests', 'template_backends', 'test_runner', 'admin_scripts', 'inline_formsets', 'foreign_object', 'cache'} MOCK_OBJECTS = ['MockRequest', 'MockCompiler', 'MockModelAdmin', 'modelz', 'call_count', 'call_args_list', 'call_args', 'MockUser', 'Xtemplate', 'DummyRequest', 'DummyUser', 'MinimalUser', 'DummyNode'] EXTERNAL_MODULES = ['psycopg2', 'PIL', 'selenium', 'oracle', 'mysql', 'sqlparse', 'tblib', 'numpy', 'bcrypt', 'argon2', 'xml.dom'] IGNORED_ERRORS = { '__common__': [ *MOCK_OBJECTS, *EXTERNAL_MODULES, 'Need type annotation for', 'has no attribute "getvalue"', 'Cannot assign to a method', 'already defined', 'Cannot assign to a type', '"HttpResponseBase" has no attribute', '"object" has no attribute', re.compile(r'"Callable\[.+, Any\]" has no attribute'), 'has no attribute "deconstruct"', # private members re.compile(r'has no attribute ("|\')_[a-zA-Z_]+("|\')'), "'Settings' object has no attribute", '**Dict', 'has incompatible type "object"', 'undefined in superclass', 'Argument after ** must be a mapping', 'note:', re.compile(r'Item "None" of "[a-zA-Z_ ,\[\]]+" has no attribute'), '"Callable[..., None]" has no attribute', 'does not return a value', 'has no attribute "alternatives"', 'gets multiple values for keyword argument', '"Handler" has no attribute', 'Module has no attribute', 'namedtuple', # TODO: see test in managers/test_managers.yml "Cannot determine type of", 'cache_clear', 'cache_info', 'Incompatible types in assignment (expression has type "None", variable has type Module)', "Module 'django.contrib.messages.storage.fallback' has no attribute 'CookieStorage'", # TODO: not supported yet 'GenericRelation', 'RelatedObjectDoesNotExist', re.compile(r'"Field\[Any, Any\]" has no attribute ' r'"(through|field_name|field|get_related_field|related_model|related_name' r'|get_accessor_name|empty_strings_allowed|many_to_many)"'), # TODO: multitable inheritance 'ptr', 'Incompatible types in assignment (expression has type "Callable[', 'SimpleLazyObject', 'Test', 'Mixin" has no attribute', 'Incompatible types in string interpolation', '"None" has no attribute', 'has no attribute "assert', 'Unsupported dynamic base class', 'error: "HttpResponse" has no attribute "streaming_content"', 'error: "HttpResponse" has no attribute "context_data"', ], 'admin_inlines': [ 'error: "HttpResponse" has no attribute "rendered_content"', ], 'admin_utils': [ '"Article" has no attribute "non_field"', ], 'aggregation': [ re.compile(r'got "Optional\[(Author|Publisher)\]", expected "Union\[(Author|Publisher), Combinable\]"'), 'Argument 2 for "super" not an instance of argument 1', ], 'annotations': [ 'Incompatible type for "store" of "Employee" (got "Optional[Store]", expected "Union[Store, Combinable]")' ], 'apps': [ 'Incompatible types in assignment (expression has type "str", target has type "type")', ], 'auth_tests': [ '"PasswordValidator" has no attribute "min_length"', 'AbstractBaseUser', 'Argument "password_validators" to "password_changed" has incompatible type "Tuple[Validator]"; ' + 'expected "Optional[Sequence[PasswordValidator]]"', 'Unsupported right operand type for in ("object")', 'mock_getpass', 'Unsupported left operand type for + ("Sequence[str]")', 'AuthenticationFormWithInactiveUsersOkay', 'Incompatible types in assignment (expression has type "Dict[str, Any]", variable has type "QueryDict")', 'No overload variant of "int" matches argument type "AnonymousUser"', 'expression has type "AnonymousUser", variable has type "User"', ], 'basic': [ 'Unexpected keyword argument "unknown_kwarg" for "refresh_from_db" of "Model"', 'Unexpected attribute "foo" for model "Article"', 'has no attribute "touched"', 'Incompatible types in assignment (expression has type "Type[CustomQuerySet]"', '"Manager[Article]" has no attribute "do_something"', ], 'backends': [ '"DatabaseError" has no attribute "pgcode"' ], 'builtin_server': [ '"ServerHandler" has no attribute', 'Incompatible types in assignment (expression has type "Tuple[BytesIO, BytesIO]"', ], 'bulk_create': [ 'has incompatible type "List[Country]"; expected "Iterable[TwoFields]"', 'List item 1 has incompatible type "Country"; expected "ProxyCountry"', ], 'check_framework': [ 'base class "Model" defined the type as "Callable', 'Value of type "Collection[str]" is not indexable', 'Unsupported target for indexed assignment', ], 'constraints': [ 'Argument "condition" to "UniqueConstraint" has incompatible type "str"; expected "Optional[Q]"' ], 'contenttypes_tests': [ '"FooWithBrokenAbsoluteUrl" has no attribute "unknown_field"', 'contenttypes_tests.models.Site', 'Argument 1 to "set" of "RelatedManager" has incompatible type "SiteManager[Site]"', ], 'custom_lookups': [ 'in base class "SQLFuncMixin"', 'has no attribute "name"', ], 'custom_columns': [ "Cannot resolve keyword 'firstname' into field", ], 'custom_pk': [ '"Employee" has no attribute "id"', ], 'custom_managers': [ 'Incompatible types in assignment (expression has type "CharField', 'Item "Book" of "Optional[Book]" has no attribute "favorite_avg"', ], 'csrf_tests': [ 'expression has type "property", base class "HttpRequest" defined the type as "QueryDict"', 'expression has type "Dict[<nothing>, <nothing>]", variable has type "SessionBase"', ], 'dates': [ 'Too few arguments for "dates" of', ], 'dbshell': [ 'Incompatible types in assignment (expression has type "None"', ], 'defer': [ 'Too many arguments for "refresh_from_db" of "Model"' ], 'delete': [ 'Incompatible type for lookup \'pk\': (got "Optional[int]", expected "Union[str, int]")', ], 'dispatch': [ 'Item "str" of "Union[ValueError, str]" has no attribute "args"' ], 'deprecation': [ '"Manager" has no attribute "old"', '"Manager" has no attribute "new"' ], 'db_functions': [ '"FloatModel" has no attribute', 'Incompatible types in assignment (expression has type "Optional[Any]", variable has type "FloatModel")' ], 'decorators': [ '"Type[object]" has no attribute "method"', 'Value of type variable "_T" of function cannot be "descriptor_wrapper"' ], 'expressions_window': [ 'has incompatible type "str"' ], 'file_uploads': [ 'has no attribute "content_type"', ], 'file_storage': [ 'Incompatible types in assignment (expression has type "None", variable has type "str")', 'Property "base_url" defined in "FileSystemStorage" is read-only', ], 'files': [ 'Incompatible types in assignment (expression has type "IOBase", variable has type "File")', 'Argument 1 to "TextIOWrapper" has incompatible type "File"; expected "BinaryIO"', 'Incompatible types in assignment (expression has type "BinaryIO", variable has type "File")', ], 'filtered_relation': [ 'has no attribute "name"', ], 'fixtures': [ 'Incompatible types in assignment (expression has type "int", target has type "Iterable[str]")', 'Incompatible types in assignment (expression has type "SpyManager[Spy]"', ], 'fixtures_regress': [ 'Unsupported left operand type for + ("None")', ], 'from_db_value': [ '"Cash" has no attribute', '"__str__" of "Decimal"', ], 'get_object_or_404': [ 'Argument 1 to "get_object_or_404" has incompatible type "str"; ' + 'expected "Union[Type[<nothing>], QuerySet[<nothing>]]"', 'Argument 1 to "get_list_or_404" has incompatible type "List[Type[Article]]"; ' + 'expected "Union[Type[<nothing>], QuerySet[<nothing>]]"', 'CustomClass', ], 'generic_relations': [ "Cannot resolve keyword 'vegetable' into field", ], 'generic_relations_regress': [ '"Link" has no attribute', ], 'httpwrappers': [ 'Argument 2 to "appendlist" of "QueryDict"', 'Incompatible types in assignment (expression has type "int", target has type "Union[str, List[str]]")', 'Argument 1 to "fromkeys" of "QueryDict" has incompatible type "int"', ], 'humanize_tests': [ 'Argument 1 to "append" of "list" has incompatible type "None"; expected "str"', ], 'lookup': [ 'Unexpected keyword argument "headline__startswith" for "in_bulk" of', 'is called with more than one field', "Cannot resolve keyword 'pub_date_year' into field", "Cannot resolve keyword 'blahblah' into field", ], 'logging_tests': [ re.compile(r'Argument [0-9] to "makeRecord" of "Logger"'), '"LogRecord" has no attribute "request"', ], 'm2m_regress': [ "Cannot resolve keyword 'porcupine' into field", 'Argument 1 to "set" of "RelatedManager" has incompatible type "int"', ], 'mail': [ 'List item 1 has incompatible type "None"; expected "str"', 'Incompatible types in assignment ' + '(expression has type "bool", variable has type "Union[SMTP_SSL, SMTP, None]")', ], 'messages_tests': [ 'List item 0 has incompatible type "Dict[str, Message]"; expected "Message"', 'Too many arguments', 'CustomRequest', ], 'middleware': [ re.compile(r'"(HttpRequest|WSGIRequest)" has no attribute'), 'Incompatible types in assignment (expression has type "HttpResponseBase", variable has type "HttpResponse")', ], 'many_to_many': [ '(expression has type "List[Article]", variable has type "Article_RelatedManager2', '"add" of "RelatedManager" has incompatible type "Article"; expected "Union[Publication, int]"', ], 'many_to_one': [ 'Incompatible type for "parent" of "Child" (got "None", expected "Union[Parent, Combinable]")', 'Incompatible type for "parent" of "Child" (got "Child", expected "Union[Parent, Combinable]")', 'expression has type "List[<nothing>]", variable has type "RelatedManager[Article]"', '"Reporter" has no attribute "cached_query"', 'to "add" of "RelatedManager" has incompatible type "Reporter"; expected "Union[Article, int]"', ], 'middleware_exceptions': [ 'Argument 1 to "append" of "list" has incompatible type "Tuple[Any, Any]"; expected "str"' ], 'migrate_signals': [ 'Value of type "Optional[Any]" is not indexable', 'Argument 1 to "set" has incompatible type "Optional[Any]"; expected "Iterable[Any]"', ], 'migrations': [ 'FakeMigration', 'FakeLoader', '"Manager[Any]" has no attribute "args"', 'Dict entry 0 has incompatible type "Any"', 'Argument 1 to "append" of "list" has incompatible type', 'base class "Model" defined the type as "BaseManager[Any]"', 'Argument 1 to "RunPython" has incompatible type "str"', ], 'model_fields': [ 'Item "Field[Any, Any]" of "Union[Field[Any, Any], ForeignObjectRel]" has no attribute', 'Incompatible types in assignment (expression has type "Type[Person', 'Incompatible types in assignment (expression has type "FloatModel", variable has type', '"ImageFile" has no attribute "was_opened"', 'Incompatible type for "size" of "FloatModel" (got "object", expected "Union[float, int, str, Combinable]")', 'Incompatible type for "value" of "IntegerModel" (got "object", expected', '"Child" has no attribute "get_foo_display"', ], 'model_forms': [ '"render" of "Widget"', "Module 'django.core.validators' has no attribute 'ValidationError'", 'Incompatible types in assignment', 'NewForm', '"type" has no attribute "base_fields"', 'Argument "instance" to "InvalidModelForm" has incompatible type "Type[Category]"', ], 'model_indexes': [ 'Argument "condition" to "Index" has incompatible type "str"; expected "Optional[Q]"' ], 'model_inheritance': [ 'base class "AbstractBase" defined', 'base class "AbstractModel" defined', 'Definition of "name" in base class "ConcreteParent"', ' Definition of "name" in base class "AbstractParent"', 'referent_references', "Cannot resolve keyword 'attached_comment_set' into field" ], 'model_meta': [ 'List item 0 has incompatible type "str"; expected "Union[Field[Any, Any], ForeignObjectRel]"' ], 'model_regress': [ 'Incompatible type for "department" of "Worker"', '"PickledModel" has no attribute', '"Department" has no attribute "evaluate"', 'Unsupported target for indexed assignment', ], 'model_formsets_regress': [ 'Incompatible types in assignment (expression has type "int", target has type "str")', ], 'model_options': [ 'expression has type "Dict[str, Type[Model]]", target has type "OrderedDict', ], 'model_enums': [ "'bool' is not a valid base class", ], 'null_queries': [ "Cannot resolve keyword 'foo' into field" ], 'order_with_respect_to': [ '"Dimension" has no attribute "set_component_order"', ], 'one_to_one': [ 'expression has type "None", variable has type "UndergroundBar"', 'Item "OneToOneField[Union[Place, Combinable], Place]" ' + 'of "Union[OneToOneField[Union[Place, Combinable], Place], Any]"', ], 'pagination': [ '"int" not callable', ], 'postgres_tests': [ 'DummyArrayField', 'DummyJSONField', 'Incompatible types in assignment (expression has type "Type[Field[Any, Any]]', 'Argument "encoder" to "JSONField" has incompatible type "DjangoJSONEncoder";', '("None" and "SearchQuery")', ], 'properties': [ re.compile('Unexpected attribute "(full_name|full_name_2)" for model "Person"') ], 'prefetch_related': [ '"Person" has no attribute "houses_lst"', '"Book" has no attribute "first_authors"', '"Book" has no attribute "the_authors"', 'Incompatible types in assignment (expression has type "List[Room]", variable has type "Manager[Room]")', 'Item "Room" of "Optional[Room]" has no attribute "house_attr"', 'Item "Room" of "Optional[Room]" has no attribute "main_room_of_attr"', 'Argument 2 to "Prefetch" has incompatible type "ValuesQuerySet' ], 'proxy_models': [ 'Incompatible types in assignment', 'in base class "User"' ], 'queries': [ 'Incompatible types in assignment (expression has type "None", variable has type "str")', 'Invalid index type "Optional[str]" for "Dict[str, int]"; expected type "str"', 'Unsupported operand types for & ("Manager[Author]" and "Manager[Tag]")', 'Unsupported operand types for | ("Manager[Author]" and "Manager[Tag]")', 'ObjectA', "'flat' and 'named' can't be used together", '"Collection[Any]" has no attribute "explain"', "Cannot resolve keyword 'unknown_field' into field", 'Incompatible type for lookup \'tag\': (got "str", expected "Union[Tag, int, None]")', 'No overload variant of "__getitem__" of "QuerySet" matches argument type "str"', ], 'requests': [ 'Incompatible types in assignment (expression has type "Dict[str, str]", variable has type "QueryDict")' ], 'responses': [ 'Argument 1 to "TextIOWrapper" has incompatible type "HttpResponse"; expected "IO[bytes]"', '"FileLike" has no attribute "closed"', 'Argument 1 to "TextIOWrapper" has incompatible type "HttpResponse"; expected "BinaryIO"', ], 'reverse_lookup': [ "Cannot resolve keyword 'choice' into field" ], 'settings_tests': [ 'Argument 1 to "Settings" has incompatible type "Optional[str]"; expected "str"' ], 'shortcuts': [ 'error: "Context" has no attribute "request"', ], 'signals': [ 'Argument 1 to "append" of "list" has incompatible type "Tuple[Any, Any, Optional[Any], Any]";' ], 'sites_framework': [ 'expression has type "CurrentSiteManager[CustomArticle]", base class "AbstractArticle"', "Name 'Optional' is not defined", ], 'sites_tests': [ '"RequestSite" of "Union[Site, RequestSite]" has no attribute "id"', ], 'syndication_tests': [ 'Argument 1 to "add_domain" has incompatible type "*Tuple[object, ...]"', ], 'sessions_tests': [ 'Incompatible types in assignment (expression has type "None", variable has type "int")', '"AbstractBaseSession" has no attribute', '"None" not callable', ], 'select_related': [ 'Item "ForeignKey[Union[Genus, Combinable], Genus]" ' + 'of "Union[ForeignKey[Union[Genus, Combinable], Genus], Any]"' ], 'select_related_onetoone': [ 'Incompatible types in assignment (expression has type "Parent2", variable has type "Parent1")', '"Parent1" has no attribute' ], 'servers': [ re.compile('Argument [0-9] to "WSGIRequestHandler"'), '"HTTPResponse" has no attribute', '"type" has no attribute', '"WSGIRequest" has no attribute "makefile"', 'LiveServerAddress', '"Stub" has no attribute "makefile"', ], 'serializers': [ '"Model" has no attribute "data"', '"Iterable[Any]" has no attribute "content"', re.compile(r'Argument 1 to "(serialize|deserialize)" has incompatible type "None"; expected "str"') ], 'string_lookup': [ '"Bar" has no attribute "place"', ], 'test_utils': [ '"PossessedCar" has no attribute "color"', 'expression has type "None", variable has type "List[str]"', ], 'test_client': [ '(expression has type "HttpResponse", variable has type "StreamingHttpResponse")' ], 'test_client_regress': [ '(expression has type "Dict[<nothing>, <nothing>]", variable has type "SessionBase")', 'Unsupported left operand type for + ("None")', 'Argument 1 to "len" has incompatible type "Context"; expected "Sized"', ], 'transactions': [ 'Incompatible types in assignment (expression has type "Thread", variable has type "Callable[[], Any]")' ], 'urlpatterns': [ '"object" not callable', '"None" not callable', ], 'urlpatterns_reverse': [ 'List or tuple expected as variable arguments', 'No overload variant of "zip" matches argument types "Any", "object"', 'Argument 1 to "get_callable" has incompatible type "int"' ], 'utils_tests': [ 'Argument 1 to "activate" has incompatible type "None"; expected "Union[tzinfo, str]"', 'Argument 1 to "activate" has incompatible type "Optional[str]"; expected "str"', 'Incompatible types in assignment (expression has type "None", base class "object" defined the type as', 'Class', 'has no attribute "cp"', 'Argument "name" to "cached_property" has incompatible type "int"; expected "Optional[str]"', 'has no attribute "sort"', 'Unsupported target for indexed assignment', 'defined the type as "None"', 'Argument 1 to "Path" has incompatible type "Optional[str]"', '"None" not callable', '"WSGIRequest" has no attribute "process_response_content"', 'No overload variant of "join" matches argument types "str", "None"', 'Argument 1 to "Archive" has incompatible type "None"; expected "str"', 'Argument 1 to "to_path" has incompatible type "int"; expected "Union[Path, str]"', 'Cannot infer type argument 1 of "cached_property"', ], 'view_tests': [ "Module 'django.views.debug' has no attribute 'Path'", 'Value of type "Optional[List[str]]" is not indexable', 'ExceptionUser', 'view_tests.tests.test_debug.User', 'Exception must be derived from BaseException', "No binding for nonlocal 'tb_frames' found", ], 'validation': [ 'has no attribute "name"', ], 'wsgi': [ '"HttpResponse" has no attribute "block_size"', ], } def check_if_custom_ignores_are_covered_by_common() -> None: from scripts.typecheck_tests import is_pattern_fits common_ignore_patterns = IGNORED_ERRORS['__common__'] for module_name, patterns in IGNORED_ERRORS.items(): if module_name == '__common__': continue for pattern in patterns: for common_pattern in common_ignore_patterns: if isinstance(pattern, str) and is_pattern_fits(common_pattern, pattern): print(f'pattern "{module_name}: {pattern!r}" is covered by pattern {common_pattern!r}') check_if_custom_ignores_are_covered_by_common()
22,259
Python
.py
500
36.918
118
0.620799
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,889
dynamic_params.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/dynamic_params.py
""" One of the really important features of |jedi| is to have an option to understand code like this:: def foo(bar): bar. # completion here foo(1) There's no doubt wheter bar is an ``int`` or not, but if there's also a call like ``foo('str')``, what would happen? Well, we'll just show both. Because that's what a human would expect. It works as follows: - |Jedi| sees a param - search for function calls named ``foo`` - execute these calls and check the input. """ from jedi import settings from jedi import debug from jedi.parser_utils import get_parent_scope from jedi.inference.cache import inference_state_method_cache from jedi.inference.arguments import TreeArguments from jedi.inference.param import get_executed_param_names from jedi.inference.helpers import is_stdlib_path from jedi.inference.utils import to_list from jedi.inference.value import instance from jedi.inference.base_value import ValueSet, NO_VALUES from jedi.inference.references import get_module_contexts_containing_name from jedi.inference import recursion MAX_PARAM_SEARCHES = 20 def _avoid_recursions(func): def wrapper(function_value, param_index): inf = function_value.inference_state with recursion.execution_allowed(inf, function_value.tree_node) as allowed: # We need to catch recursions that may occur, because an # anonymous functions can create an anonymous parameter that is # more or less self referencing. if allowed: inf.dynamic_params_depth += 1 try: return func(function_value, param_index) finally: inf.dynamic_params_depth -= 1 return NO_VALUES return wrapper @debug.increase_indent @_avoid_recursions def dynamic_param_lookup(function_value, param_index): """ A dynamic search for param values. If you try to complete a type: >>> def func(foo): ... foo >>> func(1) >>> func("") It is not known what the type ``foo`` without analysing the whole code. You have to look for all calls to ``func`` to find out what ``foo`` possibly is. """ funcdef = function_value.tree_node if not settings.dynamic_params: return NO_VALUES path = function_value.get_root_context().py__file__() if path is not None and is_stdlib_path(path): # We don't want to search for references in the stdlib. Usually people # don't work with it (except if you are a core maintainer, sorry). # This makes everything slower. Just disable it and run the tests, # you will see the slowdown, especially in 3.6. return NO_VALUES if funcdef.type == 'lambdef': string_name = _get_lambda_name(funcdef) if string_name is None: return NO_VALUES else: string_name = funcdef.name.value debug.dbg('Dynamic param search in %s.', string_name, color='MAGENTA') module_context = function_value.get_root_context() arguments_list = _search_function_arguments(module_context, funcdef, string_name) values = ValueSet.from_sets( get_executed_param_names( function_value, arguments )[param_index].infer() for arguments in arguments_list ) debug.dbg('Dynamic param result finished', color='MAGENTA') return values @inference_state_method_cache(default=None) @to_list def _search_function_arguments(module_context, funcdef, string_name): """ Returns a list of param names. """ compare_node = funcdef if string_name == '__init__': cls = get_parent_scope(funcdef) if cls.type == 'classdef': string_name = cls.name.value compare_node = cls found_arguments = False i = 0 inference_state = module_context.inference_state if settings.dynamic_params_for_other_modules: module_contexts = get_module_contexts_containing_name( inference_state, [module_context], string_name, # Limit the amounts of files to be opened massively. limit_reduction=5, ) else: module_contexts = [module_context] for for_mod_context in module_contexts: for name, trailer in _get_potential_nodes(for_mod_context, string_name): i += 1 # This is a simple way to stop Jedi's dynamic param recursion # from going wild: The deeper Jedi's in the recursion, the less # code should be inferred. if i * inference_state.dynamic_params_depth > MAX_PARAM_SEARCHES: return random_context = for_mod_context.create_context(name) for arguments in _check_name_for_execution( inference_state, random_context, compare_node, name, trailer): found_arguments = True yield arguments # If there are results after processing a module, we're probably # good to process. This is a speed optimization. if found_arguments: return def _get_lambda_name(node): stmt = node.parent if stmt.type == 'expr_stmt': first_operator = next(stmt.yield_operators(), None) if first_operator == '=': first = stmt.children[0] if first.type == 'name': return first.value return None def _get_potential_nodes(module_value, func_string_name): try: names = module_value.tree_node.get_used_names()[func_string_name] except KeyError: return for name in names: bracket = name.get_next_leaf() trailer = bracket.parent if trailer.type == 'trailer' and bracket == '(': yield name, trailer def _check_name_for_execution(inference_state, context, compare_node, name, trailer): from jedi.inference.value.function import BaseFunctionExecutionContext def create_args(value): arglist = trailer.children[1] if arglist == ')': arglist = None args = TreeArguments(inference_state, context, arglist, trailer) from jedi.inference.value.instance import InstanceArguments if value.tree_node.type == 'classdef': created_instance = instance.TreeInstance( inference_state, value.parent_context, value, args ) return InstanceArguments(created_instance, args) else: if value.is_bound_method(): args = InstanceArguments(value.instance, args) return args for value in inference_state.infer(context, name): value_node = value.tree_node if compare_node == value_node: yield create_args(value) elif isinstance(value.parent_context, BaseFunctionExecutionContext) \ and compare_node.type == 'funcdef': # Here we're trying to find decorators by checking the first # parameter. It's not very generic though. Should find a better # solution that also applies to nested decorators. param_names = value.parent_context.get_param_names() if len(param_names) != 1: continue values = param_names[0].infer() if [v.tree_node for v in values] == [compare_node]: # Found a decorator. module_context = context.get_root_context() execution_context = value.as_context(create_args(value)) potential_nodes = _get_potential_nodes(module_context, param_names[0].string_name) for name, trailer in potential_nodes: if value_node.start_pos < name.start_pos < value_node.end_pos: random_context = execution_context.create_context(name) yield from _check_name_for_execution( inference_state, random_context, compare_node, name, trailer )
8,122
Python
.py
189
33.597884
98
0.633578
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,890
filters.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/filters.py
""" Filters are objects that you can use to filter names in different scopes. They are needed for name resolution. """ from abc import abstractmethod from typing import List, MutableMapping, Type import weakref from parso.tree import search_ancestor from parso.python.tree import Name, UsedNamesMapping from jedi.inference import flow_analysis from jedi.inference.base_value import ValueSet, ValueWrapper, \ LazyValueWrapper from jedi.parser_utils import get_cached_parent_scope, get_parso_cache_node from jedi.inference.utils import to_list from jedi.inference.names import TreeNameDefinition, ParamName, \ AnonymousParamName, AbstractNameDefinition, NameWrapper _definition_name_cache: MutableMapping[UsedNamesMapping, List[Name]] _definition_name_cache = weakref.WeakKeyDictionary() class AbstractFilter: _until_position = None def _filter(self, names): if self._until_position is not None: return [n for n in names if n.start_pos < self._until_position] return names @abstractmethod def get(self, name): raise NotImplementedError @abstractmethod def values(self): raise NotImplementedError class FilterWrapper: name_wrapper_class: Type[NameWrapper] def __init__(self, wrapped_filter): self._wrapped_filter = wrapped_filter def wrap_names(self, names): return [self.name_wrapper_class(name) for name in names] def get(self, name): return self.wrap_names(self._wrapped_filter.get(name)) def values(self): return self.wrap_names(self._wrapped_filter.values()) def _get_definition_names(parso_cache_node, used_names, name_key): if parso_cache_node is None: names = used_names.get(name_key, ()) return tuple(name for name in names if name.is_definition(include_setitem=True)) try: for_module = _definition_name_cache[parso_cache_node] except KeyError: for_module = _definition_name_cache[parso_cache_node] = {} try: return for_module[name_key] except KeyError: names = used_names.get(name_key, ()) result = for_module[name_key] = tuple( name for name in names if name.is_definition(include_setitem=True) ) return result class _AbstractUsedNamesFilter(AbstractFilter): name_class = TreeNameDefinition def __init__(self, parent_context, node_context=None): if node_context is None: node_context = parent_context self._node_context = node_context self._parser_scope = node_context.tree_node module_context = node_context.get_root_context() # It is quite hacky that we have to use that. This is for caching # certain things with a WeakKeyDictionary. However, parso intentionally # uses slots (to save memory) and therefore we end up with having to # have a weak reference to the object that caches the tree. # # Previously we have tried to solve this by using a weak reference onto # used_names. However that also does not work, because it has a # reference from the module, which itself is referenced by any node # through parents. path = module_context.py__file__() if path is None: # If the path is None, there is no guarantee that parso caches it. self._parso_cache_node = None else: self._parso_cache_node = get_parso_cache_node( module_context.inference_state.latest_grammar if module_context.is_stub() else module_context.inference_state.grammar, path ) self._used_names = module_context.tree_node.get_used_names() self.parent_context = parent_context def get(self, name): return self._convert_names(self._filter( _get_definition_names(self._parso_cache_node, self._used_names, name), )) def _convert_names(self, names): return [self.name_class(self.parent_context, name) for name in names] def values(self): return self._convert_names( name for name_key in self._used_names for name in self._filter( _get_definition_names(self._parso_cache_node, self._used_names, name_key), ) ) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.parent_context) class ParserTreeFilter(_AbstractUsedNamesFilter): def __init__(self, parent_context, node_context=None, until_position=None, origin_scope=None): """ node_context is an option to specify a second value for use cases like the class mro where the parent class of a new name would be the value, but for some type inference it's important to have a local value of the other classes. """ super().__init__(parent_context, node_context) self._origin_scope = origin_scope self._until_position = until_position def _filter(self, names): names = super()._filter(names) names = [n for n in names if self._is_name_reachable(n)] return list(self._check_flows(names)) def _is_name_reachable(self, name): parent = name.parent if parent.type == 'trailer': return False base_node = parent if parent.type in ('classdef', 'funcdef') else name return get_cached_parent_scope(self._parso_cache_node, base_node) == self._parser_scope def _check_flows(self, names): for name in sorted(names, key=lambda name: name.start_pos, reverse=True): check = flow_analysis.reachability_check( context=self._node_context, value_scope=self._parser_scope, node=name, origin_scope=self._origin_scope ) if check is not flow_analysis.UNREACHABLE: yield name if check is flow_analysis.REACHABLE: break class _FunctionExecutionFilter(ParserTreeFilter): def __init__(self, parent_context, function_value, until_position, origin_scope): super().__init__( parent_context, until_position=until_position, origin_scope=origin_scope, ) self._function_value = function_value def _convert_param(self, param, name): raise NotImplementedError @to_list def _convert_names(self, names): for name in names: param = search_ancestor(name, 'param') # Here we don't need to check if the param is a default/annotation, # because those are not definitions and never make it to this # point. if param: yield self._convert_param(param, name) else: yield TreeNameDefinition(self.parent_context, name) class FunctionExecutionFilter(_FunctionExecutionFilter): def __init__(self, *args, arguments, **kwargs): super().__init__(*args, **kwargs) self._arguments = arguments def _convert_param(self, param, name): return ParamName(self._function_value, name, self._arguments) class AnonymousFunctionExecutionFilter(_FunctionExecutionFilter): def _convert_param(self, param, name): return AnonymousParamName(self._function_value, name) class GlobalNameFilter(_AbstractUsedNamesFilter): def get(self, name): try: names = self._used_names[name] except KeyError: return [] return self._convert_names(self._filter(names)) @to_list def _filter(self, names): for name in names: if name.parent.type == 'global_stmt': yield name def values(self): return self._convert_names( name for name_list in self._used_names.values() for name in self._filter(name_list) ) class DictFilter(AbstractFilter): def __init__(self, dct): self._dct = dct def get(self, name): try: value = self._convert(name, self._dct[name]) except KeyError: return [] else: return list(self._filter([value])) def values(self): def yielder(): for item in self._dct.items(): try: yield self._convert(*item) except KeyError: pass return self._filter(yielder()) def _convert(self, name, value): return value def __repr__(self): keys = ', '.join(self._dct.keys()) return '<%s: for {%s}>' % (self.__class__.__name__, keys) class MergedFilter: def __init__(self, *filters): self._filters = filters def get(self, name): return [n for filter in self._filters for n in filter.get(name)] def values(self): return [n for filter in self._filters for n in filter.values()] def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(str(f) for f in self._filters)) class _BuiltinMappedMethod(ValueWrapper): """``Generator.__next__`` ``dict.values`` methods and so on.""" api_type = 'function' def __init__(self, value, method, builtin_func): super().__init__(builtin_func) self._value = value self._method = method def py__call__(self, arguments): # TODO add TypeError if params are given/or not correct. return self._method(self._value, arguments) class SpecialMethodFilter(DictFilter): """ A filter for methods that are defined in this module on the corresponding classes like Generator (for __next__, etc). """ class SpecialMethodName(AbstractNameDefinition): api_type = 'function' def __init__(self, parent_context, string_name, callable_, builtin_value): self.parent_context = parent_context self.string_name = string_name self._callable = callable_ self._builtin_value = builtin_value def infer(self): for filter in self._builtin_value.get_filters(): # We can take the first index, because on builtin methods there's # always only going to be one name. The same is true for the # inferred values. for name in filter.get(self.string_name): builtin_func = next(iter(name.infer())) break else: continue break return ValueSet([ _BuiltinMappedMethod(self.parent_context, self._callable, builtin_func) ]) def __init__(self, value, dct, builtin_value): super().__init__(dct) self.value = value self._builtin_value = builtin_value """ This value is what will be used to introspect the name, where as the other value will be used to execute the function. We distinguish, because we have to. """ def _convert(self, name, value): return self.SpecialMethodName(self.value, name, value, self._builtin_value) class _OverwriteMeta(type): def __init__(cls, name, bases, dct): super().__init__(name, bases, dct) base_dct = {} for base_cls in reversed(cls.__bases__): try: base_dct.update(base_cls.overwritten_methods) except AttributeError: pass for func in cls.__dict__.values(): try: base_dct.update(func.registered_overwritten_methods) except AttributeError: pass cls.overwritten_methods = base_dct class _AttributeOverwriteMixin: def get_filters(self, *args, **kwargs): yield SpecialMethodFilter(self, self.overwritten_methods, self._wrapped_value) yield from self._wrapped_value.get_filters(*args, **kwargs) class LazyAttributeOverwrite(_AttributeOverwriteMixin, LazyValueWrapper, metaclass=_OverwriteMeta): def __init__(self, inference_state): self.inference_state = inference_state class AttributeOverwrite(_AttributeOverwriteMixin, ValueWrapper, metaclass=_OverwriteMeta): pass def publish_method(method_name): def decorator(func): dct = func.__dict__.setdefault('registered_overwritten_methods', {}) dct[method_name] = func return func return decorator
12,493
Python
.py
293
33.484642
95
0.630259
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,891
analysis.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/analysis.py
""" Module for statical analysis. """ from parso.python import tree from jedi import debug from jedi.inference.helpers import is_string CODES = { 'attribute-error': (1, AttributeError, 'Potential AttributeError.'), 'name-error': (2, NameError, 'Potential NameError.'), 'import-error': (3, ImportError, 'Potential ImportError.'), 'type-error-too-many-arguments': (4, TypeError, None), 'type-error-too-few-arguments': (5, TypeError, None), 'type-error-keyword-argument': (6, TypeError, None), 'type-error-multiple-values': (7, TypeError, None), 'type-error-star-star': (8, TypeError, None), 'type-error-star': (9, TypeError, None), 'type-error-operation': (10, TypeError, None), 'type-error-not-iterable': (11, TypeError, None), 'type-error-isinstance': (12, TypeError, None), 'type-error-not-subscriptable': (13, TypeError, None), 'value-error-too-many-values': (14, ValueError, None), 'value-error-too-few-values': (15, ValueError, None), } class Error: def __init__(self, name, module_path, start_pos, message=None): self.path = module_path self._start_pos = start_pos self.name = name if message is None: message = CODES[self.name][2] self.message = message @property def line(self): return self._start_pos[0] @property def column(self): return self._start_pos[1] @property def code(self): # The class name start first = self.__class__.__name__[0] return first + str(CODES[self.name][0]) def __str__(self): return '%s:%s:%s: %s %s' % (self.path, self.line, self.column, self.code, self.message) def __eq__(self, other): return (self.path == other.path and self.name == other.name and self._start_pos == other._start_pos) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.path, self._start_pos, self.name)) def __repr__(self): return '<%s %s: %s@%s,%s>' % (self.__class__.__name__, self.name, self.path, self._start_pos[0], self._start_pos[1]) class Warning(Error): pass def add(node_context, error_name, node, message=None, typ=Error, payload=None): exception = CODES[error_name][1] if _check_for_exception_catch(node_context, node, exception, payload): return # TODO this path is probably not right module_context = node_context.get_root_context() module_path = module_context.py__file__() issue_instance = typ(error_name, module_path, node.start_pos, message) debug.warning(str(issue_instance), format=False) node_context.inference_state.analysis.append(issue_instance) return issue_instance def _check_for_setattr(instance): """ Check if there's any setattr method inside an instance. If so, return True. """ module = instance.get_root_context() node = module.tree_node if node is None: # If it's a compiled module or doesn't have a tree_node return False try: stmt_names = node.get_used_names()['setattr'] except KeyError: return False return any(node.start_pos < n.start_pos < node.end_pos # Check if it's a function called setattr. and not (n.parent.type == 'funcdef' and n.parent.name == n) for n in stmt_names) def add_attribute_error(name_context, lookup_value, name): message = ('AttributeError: %s has no attribute %s.' % (lookup_value, name)) # Check for __getattr__/__getattribute__ existance and issue a warning # instead of an error, if that happens. typ = Error if lookup_value.is_instance() and not lookup_value.is_compiled(): # TODO maybe make a warning for __getattr__/__getattribute__ if _check_for_setattr(lookup_value): typ = Warning payload = lookup_value, name add(name_context, 'attribute-error', name, message, typ, payload) def _check_for_exception_catch(node_context, jedi_name, exception, payload=None): """ Checks if a jedi object (e.g. `Statement`) sits inside a try/catch and doesn't count as an error (if equal to `exception`). Also checks `hasattr` for AttributeErrors and uses the `payload` to compare it. Returns True if the exception was catched. """ def check_match(cls, exception): if not cls.is_class(): return False for python_cls in exception.mro(): if cls.py__name__() == python_cls.__name__ \ and cls.parent_context.is_builtins_module(): return True return False def check_try_for_except(obj, exception): # Only nodes in try iterator = iter(obj.children) for branch_type in iterator: next(iterator) # The colon suite = next(iterator) if branch_type == 'try' \ and not (branch_type.start_pos < jedi_name.start_pos <= suite.end_pos): return False for node in obj.get_except_clause_tests(): if node is None: return True # An exception block that catches everything. else: except_classes = node_context.infer_node(node) for cls in except_classes: from jedi.inference.value import iterable if isinstance(cls, iterable.Sequence) and \ cls.array_type == 'tuple': # multiple exceptions for lazy_value in cls.py__iter__(): for typ in lazy_value.infer(): if check_match(typ, exception): return True else: if check_match(cls, exception): return True def check_hasattr(node, suite): try: assert suite.start_pos <= jedi_name.start_pos < suite.end_pos assert node.type in ('power', 'atom_expr') base = node.children[0] assert base.type == 'name' and base.value == 'hasattr' trailer = node.children[1] assert trailer.type == 'trailer' arglist = trailer.children[1] assert arglist.type == 'arglist' from jedi.inference.arguments import TreeArguments args = TreeArguments(node_context.inference_state, node_context, arglist) unpacked_args = list(args.unpack()) # Arguments should be very simple assert len(unpacked_args) == 2 # Check name key, lazy_value = unpacked_args[1] names = list(lazy_value.infer()) assert len(names) == 1 and is_string(names[0]) assert names[0].get_safe_value() == payload[1].value # Check objects key, lazy_value = unpacked_args[0] objects = lazy_value.infer() return payload[0] in objects except AssertionError: return False obj = jedi_name while obj is not None and not isinstance(obj, (tree.Function, tree.Class)): if isinstance(obj, tree.Flow): # try/except catch check if obj.type == 'try_stmt' and check_try_for_except(obj, exception): return True # hasattr check if exception == AttributeError and obj.type in ('if_stmt', 'while_stmt'): if check_hasattr(obj.children[1], obj.children[3]): return True obj = obj.parent return False
7,763
Python
.py
177
33.677966
91
0.590464
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,892
context.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/context.py
from abc import abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Optional from parso.tree import search_ancestor from parso.python.tree import Name from jedi.inference.filters import ParserTreeFilter, MergedFilter, \ GlobalNameFilter from jedi.inference.names import AnonymousParamName, TreeNameDefinition from jedi.inference.base_value import NO_VALUES, ValueSet from jedi.parser_utils import get_parent_scope from jedi import debug from jedi import parser_utils class AbstractContext: # Must be defined: inference_state and tree_node and parent_context as an attribute/property def __init__(self, inference_state): self.inference_state = inference_state self.predefined_names = {} @abstractmethod def get_filters(self, until_position=None, origin_scope=None): raise NotImplementedError def goto(self, name_or_str, position): from jedi.inference import finder filters = _get_global_filters_for_name( self, name_or_str if isinstance(name_or_str, Name) else None, position, ) names = finder.filter_name(filters, name_or_str) debug.dbg('context.goto %s in (%s): %s', name_or_str, self, names) return names def py__getattribute__(self, name_or_str, name_context=None, position=None, analysis_errors=True): """ :param position: Position of the last statement -> tuple of line, column """ if name_context is None: name_context = self names = self.goto(name_or_str, position) string_name = name_or_str.value if isinstance(name_or_str, Name) else name_or_str # This paragraph is currently needed for proper branch type inference # (static analysis). found_predefined_types = None if self.predefined_names and isinstance(name_or_str, Name): node = name_or_str while node is not None and not parser_utils.is_scope(node): node = node.parent if node.type in ("if_stmt", "for_stmt", "comp_for", 'sync_comp_for'): try: name_dict = self.predefined_names[node] types = name_dict[string_name] except KeyError: continue else: found_predefined_types = types break if found_predefined_types is not None and names: from jedi.inference import flow_analysis check = flow_analysis.reachability_check( context=self, value_scope=self.tree_node, node=name_or_str, ) if check is flow_analysis.UNREACHABLE: values = NO_VALUES else: values = found_predefined_types else: values = ValueSet.from_sets(name.infer() for name in names) if not names and not values and analysis_errors: if isinstance(name_or_str, Name): from jedi.inference import analysis message = ("NameError: name '%s' is not defined." % string_name) analysis.add(name_context, 'name-error', name_or_str, message) debug.dbg('context.names_to_types: %s -> %s', names, values) if values: return values return self._check_for_additional_knowledge(name_or_str, name_context, position) def _check_for_additional_knowledge(self, name_or_str, name_context, position): name_context = name_context or self # Add isinstance and other if/assert knowledge. if isinstance(name_or_str, Name) and not name_context.is_instance(): flow_scope = name_or_str base_nodes = [name_context.tree_node] if any(b.type in ('comp_for', 'sync_comp_for') for b in base_nodes): return NO_VALUES from jedi.inference.finder import check_flow_information while True: flow_scope = get_parent_scope(flow_scope, include_flows=True) n = check_flow_information(name_context, flow_scope, name_or_str, position) if n is not None: return n if flow_scope in base_nodes: break return NO_VALUES def get_root_context(self): parent_context = self.parent_context if parent_context is None: return self return parent_context.get_root_context() def is_module(self): return False def is_builtins_module(self): return False def is_class(self): return False def is_stub(self): return False def is_instance(self): return False def is_compiled(self): return False def is_bound_method(self): return False @abstractmethod def py__name__(self): raise NotImplementedError def get_value(self): raise NotImplementedError @property def name(self): return None def get_qualified_names(self): return () def py__doc__(self): return '' @contextmanager def predefine_names(self, flow_scope, dct): predefined = self.predefined_names predefined[flow_scope] = dct try: yield finally: del predefined[flow_scope] class ValueContext(AbstractContext): """ Should be defined, otherwise the API returns empty types. """ def __init__(self, value): super().__init__(value.inference_state) self._value = value @property def tree_node(self): return self._value.tree_node @property def parent_context(self): return self._value.parent_context def is_module(self): return self._value.is_module() def is_builtins_module(self): return self._value == self.inference_state.builtins_module def is_class(self): return self._value.is_class() def is_stub(self): return self._value.is_stub() def is_instance(self): return self._value.is_instance() def is_compiled(self): return self._value.is_compiled() def is_bound_method(self): return self._value.is_bound_method() def py__name__(self): return self._value.py__name__() @property def name(self): return self._value.name def get_qualified_names(self): return self._value.get_qualified_names() def py__doc__(self): return self._value.py__doc__() def get_value(self): return self._value def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self._value) class TreeContextMixin: def infer_node(self, node): from jedi.inference.syntax_tree import infer_node return infer_node(self, node) def create_value(self, node): from jedi.inference import value if node == self.tree_node: assert self.is_module() return self.get_value() parent_context = self.create_context(node) if node.type in ('funcdef', 'lambdef'): func = value.FunctionValue.from_context(parent_context, node) if parent_context.is_class(): class_value = parent_context.parent_context.create_value(parent_context.tree_node) instance = value.AnonymousInstance( self.inference_state, parent_context.parent_context, class_value) func = value.BoundMethod( instance=instance, class_context=class_value.as_context(), function=func ) return func elif node.type == 'classdef': return value.ClassValue(self.inference_state, parent_context, node) else: raise NotImplementedError("Probably shouldn't happen: %s" % node) def create_context(self, node): def from_scope_node(scope_node, is_nested=True): if scope_node == self.tree_node: return self if scope_node.type in ('funcdef', 'lambdef', 'classdef'): return self.create_value(scope_node).as_context() elif scope_node.type in ('comp_for', 'sync_comp_for'): parent_context = from_scope_node(parent_scope(scope_node.parent)) if node.start_pos >= scope_node.children[-1].start_pos: return parent_context return CompForContext(parent_context, scope_node) raise Exception("There's a scope that was not managed: %s" % scope_node) def parent_scope(node): while True: node = node.parent if parser_utils.is_scope(node): return node elif node.type in ('argument', 'testlist_comp'): if node.children[1].type in ('comp_for', 'sync_comp_for'): return node.children[1] elif node.type == 'dictorsetmaker': for n in node.children[1:4]: # In dictionaries it can be pretty much anything. if n.type in ('comp_for', 'sync_comp_for'): return n scope_node = parent_scope(node) if scope_node.type in ('funcdef', 'classdef'): colon = scope_node.children[scope_node.children.index(':')] if node.start_pos < colon.start_pos: parent = node.parent if not (parent.type == 'param' and parent.name == node): scope_node = parent_scope(scope_node) return from_scope_node(scope_node, is_nested=True) def create_name(self, tree_name): definition = tree_name.get_definition() if definition and definition.type == 'param' and definition.name == tree_name: funcdef = search_ancestor(definition, 'funcdef', 'lambdef') func = self.create_value(funcdef) return AnonymousParamName(func, tree_name) else: context = self.create_context(tree_name) return TreeNameDefinition(context, tree_name) class FunctionContext(TreeContextMixin, ValueContext): def get_filters(self, until_position=None, origin_scope=None): yield ParserTreeFilter( self.inference_state, parent_context=self, until_position=until_position, origin_scope=origin_scope ) class ModuleContext(TreeContextMixin, ValueContext): def py__file__(self) -> Optional[Path]: return self._value.py__file__() # type: ignore[no-any-return] def get_filters(self, until_position=None, origin_scope=None): filters = self._value.get_filters(origin_scope) # Skip the first filter and replace it. next(filters, None) yield MergedFilter( ParserTreeFilter( parent_context=self, until_position=until_position, origin_scope=origin_scope ), self.get_global_filter(), ) yield from filters def get_global_filter(self): return GlobalNameFilter(self) @property def string_names(self): return self._value.string_names @property def code_lines(self): return self._value.code_lines def get_value(self): """ This is the only function that converts a context back to a value. This is necessary for stub -> python conversion and vice versa. However this method shouldn't be moved to AbstractContext. """ return self._value class NamespaceContext(TreeContextMixin, ValueContext): def get_filters(self, until_position=None, origin_scope=None): return self._value.get_filters() def get_value(self): return self._value @property def string_names(self): return self._value.string_names def py__file__(self) -> Optional[Path]: return self._value.py__file__() # type: ignore[no-any-return] class ClassContext(TreeContextMixin, ValueContext): def get_filters(self, until_position=None, origin_scope=None): yield self.get_global_filter(until_position, origin_scope) def get_global_filter(self, until_position=None, origin_scope=None): return ParserTreeFilter( parent_context=self, until_position=until_position, origin_scope=origin_scope ) class CompForContext(TreeContextMixin, AbstractContext): def __init__(self, parent_context, comp_for): super().__init__(parent_context.inference_state) self.tree_node = comp_for self.parent_context = parent_context def get_filters(self, until_position=None, origin_scope=None): yield ParserTreeFilter(self) def get_value(self): return None def py__name__(self): return '<comprehension context>' def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self.tree_node) class CompiledContext(ValueContext): def get_filters(self, until_position=None, origin_scope=None): return self._value.get_filters() class CompiledModuleContext(CompiledContext): code_lines = None def get_value(self): return self._value @property def string_names(self): return self._value.string_names def py__file__(self) -> Optional[Path]: return self._value.py__file__() # type: ignore[no-any-return] def _get_global_filters_for_name(context, name_or_none, position): # For functions and classes the defaults don't belong to the # function and get inferred in the value before the function. So # make sure to exclude the function/class name. if name_or_none is not None: ancestor = search_ancestor(name_or_none, 'funcdef', 'classdef', 'lambdef') lambdef = None if ancestor == 'lambdef': # For lambdas it's even more complicated since parts will # be inferred later. lambdef = ancestor ancestor = search_ancestor(name_or_none, 'funcdef', 'classdef') if ancestor is not None: colon = ancestor.children[-2] if position is not None and position < colon.start_pos: if lambdef is None or position < lambdef.children[-2].start_pos: position = ancestor.start_pos return get_global_filters(context, position, name_or_none) def get_global_filters(context, until_position, origin_scope): """ Returns all filters in order of priority for name resolution. For global name lookups. The filters will handle name resolution themselves, but here we gather possible filters downwards. >>> from jedi import Script >>> script = Script(''' ... x = ['a', 'b', 'c'] ... def func(): ... y = None ... ''') >>> module_node = script._module_node >>> scope = next(module_node.iter_funcdefs()) >>> scope <Function: func@3-5> >>> context = script._get_module_context().create_context(scope) >>> filters = list(get_global_filters(context, (4, 0), None)) First we get the names from the function scope. >>> print(filters[0]) # doctest: +ELLIPSIS MergedFilter(<ParserTreeFilter: ...>, <GlobalNameFilter: ...>) >>> sorted(str(n) for n in filters[0].values()) # doctest: +NORMALIZE_WHITESPACE ['<TreeNameDefinition: string_name=func start_pos=(3, 4)>', '<TreeNameDefinition: string_name=x start_pos=(2, 0)>'] >>> filters[0]._filters[0]._until_position (4, 0) >>> filters[0]._filters[1]._until_position Then it yields the names from one level "lower". In this example, this is the module scope (including globals). As a side note, you can see, that the position in the filter is None on the globals filter, because there the whole module is searched. >>> list(filters[1].values()) # package modules -> Also empty. [] >>> sorted(name.string_name for name in filters[2].values()) # Module attributes ['__doc__', '__name__', '__package__'] Finally, it yields the builtin filter, if `include_builtin` is true (default). >>> list(filters[3].values()) # doctest: +ELLIPSIS [...] """ base_context = context from jedi.inference.value.function import BaseFunctionExecutionContext while context is not None: # Names in methods cannot be resolved within the class. yield from context.get_filters( until_position=until_position, origin_scope=origin_scope ) if isinstance(context, (BaseFunctionExecutionContext, ModuleContext)): # The position should be reset if the current scope is a function. until_position = None context = context.parent_context b = next(base_context.inference_state.builtins_module.get_filters(), None) assert b is not None # Add builtins to the global scope. yield b
17,164
Python
.py
397
33.506297
98
0.621002
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,893
arguments.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/arguments.py
import re from itertools import zip_longest from parso.python import tree from jedi import debug from jedi.inference.utils import PushBackIterator from jedi.inference import analysis from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \ LazyTreeValue, get_merged_lazy_value from jedi.inference.names import ParamName, TreeNameDefinition, AnonymousParamName from jedi.inference.base_value import NO_VALUES, ValueSet, ContextualizedNode from jedi.inference.value import iterable from jedi.inference.cache import inference_state_as_method_param_cache def try_iter_content(types, depth=0): """Helper method for static analysis.""" if depth > 10: # It's possible that a loop has references on itself (especially with # CompiledValue). Therefore don't loop infinitely. return for typ in types: try: f = typ.py__iter__ except AttributeError: pass else: for lazy_value in f(): try_iter_content(lazy_value.infer(), depth + 1) class ParamIssue(Exception): pass def repack_with_argument_clinic(clinic_string): """ Transforms a function or method with arguments to the signature that is given as an argument clinic notation. Argument clinic is part of CPython and used for all the functions that are implemented in C (Python 3.7): str.split.__text_signature__ # Results in: '($self, /, sep=None, maxsplit=-1)' """ def decorator(func): def wrapper(value, arguments): try: args = tuple(iterate_argument_clinic( value.inference_state, arguments, clinic_string, )) except ParamIssue: return NO_VALUES else: return func(value, *args) return wrapper return decorator def iterate_argument_clinic(inference_state, arguments, clinic_string): """Uses a list with argument clinic information (see PEP 436).""" clinic_args = list(_parse_argument_clinic(clinic_string)) iterator = PushBackIterator(arguments.unpack()) for i, (name, optional, allow_kwargs, stars) in enumerate(clinic_args): if stars == 1: lazy_values = [] for key, argument in iterator: if key is not None: iterator.push_back((key, argument)) break lazy_values.append(argument) yield ValueSet([iterable.FakeTuple(inference_state, lazy_values)]) lazy_values continue elif stars == 2: raise NotImplementedError() key, argument = next(iterator, (None, None)) if key is not None: debug.warning('Keyword arguments in argument clinic are currently not supported.') raise ParamIssue if argument is None and not optional: debug.warning('TypeError: %s expected at least %s arguments, got %s', name, len(clinic_args), i) raise ParamIssue value_set = NO_VALUES if argument is None else argument.infer() if not value_set and not optional: # For the stdlib we always want values. If we don't get them, # that's ok, maybe something is too hard to resolve, however, # we will not proceed with the type inference of that function. debug.warning('argument_clinic "%s" not resolvable.', name) raise ParamIssue yield value_set def _parse_argument_clinic(string): allow_kwargs = False optional = False while string: # Optional arguments have to begin with a bracket. And should always be # at the end of the arguments. This is therefore not a proper argument # clinic implementation. `range()` for exmple allows an optional start # value at the beginning. match = re.match(r'(?:(?:(\[),? ?|, ?|)(\**\w+)|, ?/)\]*', string) string = string[len(match.group(0)):] if not match.group(2): # A slash -> allow named arguments allow_kwargs = True continue optional = optional or bool(match.group(1)) word = match.group(2) stars = word.count('*') word = word[stars:] yield (word, optional, allow_kwargs, stars) if stars: allow_kwargs = True class _AbstractArgumentsMixin: def unpack(self, funcdef=None): raise NotImplementedError def get_calling_nodes(self): return [] class AbstractArguments(_AbstractArgumentsMixin): context = None argument_node = None trailer = None def unpack_arglist(arglist): if arglist is None: return if arglist.type != 'arglist' and not ( arglist.type == 'argument' and arglist.children[0] in ('*', '**')): yield 0, arglist return iterator = iter(arglist.children) for child in iterator: if child == ',': continue elif child in ('*', '**'): c = next(iterator, None) assert c is not None yield len(child.value), c elif child.type == 'argument' and \ child.children[0] in ('*', '**'): assert len(child.children) == 2 yield len(child.children[0].value), child.children[1] else: yield 0, child class TreeArguments(AbstractArguments): def __init__(self, inference_state, context, argument_node, trailer=None): """ :param argument_node: May be an argument_node or a list of nodes. """ self.argument_node = argument_node self.context = context self._inference_state = inference_state self.trailer = trailer # Can be None, e.g. in a class definition. @classmethod @inference_state_as_method_param_cache() def create_cached(cls, *args, **kwargs): return cls(*args, **kwargs) def unpack(self, funcdef=None): named_args = [] for star_count, el in unpack_arglist(self.argument_node): if star_count == 1: arrays = self.context.infer_node(el) iterators = [_iterate_star_args(self.context, a, el, funcdef) for a in arrays] for values in list(zip_longest(*iterators)): yield None, get_merged_lazy_value( [v for v in values if v is not None] ) elif star_count == 2: arrays = self.context.infer_node(el) for dct in arrays: yield from _star_star_dict(self.context, dct, el, funcdef) else: if el.type == 'argument': c = el.children if len(c) == 3: # Keyword argument. named_args.append((c[0].value, LazyTreeValue(self.context, c[2]),)) else: # Generator comprehension. # Include the brackets with the parent. sync_comp_for = el.children[1] if sync_comp_for.type == 'comp_for': sync_comp_for = sync_comp_for.children[1] comp = iterable.GeneratorComprehension( self._inference_state, defining_context=self.context, sync_comp_for_node=sync_comp_for, entry_node=el.children[0], ) yield None, LazyKnownValue(comp) else: yield None, LazyTreeValue(self.context, el) # Reordering arguments is necessary, because star args sometimes appear # after named argument, but in the actual order it's prepended. yield from named_args def _as_tree_tuple_objects(self): for star_count, argument in unpack_arglist(self.argument_node): default = None if argument.type == 'argument': if len(argument.children) == 3: # Keyword argument. argument, default = argument.children[::2] yield argument, default, star_count def iter_calling_names_with_star(self): for name, default, star_count in self._as_tree_tuple_objects(): # TODO this function is a bit strange. probably refactor? if not star_count or not isinstance(name, tree.Name): continue yield TreeNameDefinition(self.context, name) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.argument_node) def get_calling_nodes(self): old_arguments_list = [] arguments = self while arguments not in old_arguments_list: if not isinstance(arguments, TreeArguments): break old_arguments_list.append(arguments) for calling_name in reversed(list(arguments.iter_calling_names_with_star())): names = calling_name.goto() if len(names) != 1: break if isinstance(names[0], AnonymousParamName): # Dynamic parameters should not have calling nodes, because # they are dynamic and extremely random. return [] if not isinstance(names[0], ParamName): break executed_param_name = names[0].get_executed_param_name() arguments = executed_param_name.arguments break if arguments.argument_node is not None: return [ContextualizedNode(arguments.context, arguments.argument_node)] if arguments.trailer is not None: return [ContextualizedNode(arguments.context, arguments.trailer)] return [] class ValuesArguments(AbstractArguments): def __init__(self, values_list): self._values_list = values_list def unpack(self, funcdef=None): for values in self._values_list: yield None, LazyKnownValues(values) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self._values_list) class TreeArgumentsWrapper(_AbstractArgumentsMixin): def __init__(self, arguments): self._wrapped_arguments = arguments @property def context(self): return self._wrapped_arguments.context @property def argument_node(self): return self._wrapped_arguments.argument_node @property def trailer(self): return self._wrapped_arguments.trailer def unpack(self, func=None): raise NotImplementedError def get_calling_nodes(self): return self._wrapped_arguments.get_calling_nodes() def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self._wrapped_arguments) def _iterate_star_args(context, array, input_node, funcdef=None): if not array.py__getattribute__('__iter__'): if funcdef is not None: # TODO this funcdef should not be needed. m = "TypeError: %s() argument after * must be a sequence, not %s" \ % (funcdef.name.value, array) analysis.add(context, 'type-error-star', input_node, message=m) try: iter_ = array.py__iter__ except AttributeError: pass else: yield from iter_() def _star_star_dict(context, array, input_node, funcdef): from jedi.inference.value.instance import CompiledInstance if isinstance(array, CompiledInstance) and array.name.string_name == 'dict': # For now ignore this case. In the future add proper iterators and just # make one call without crazy isinstance checks. return {} elif isinstance(array, iterable.Sequence) and array.array_type == 'dict': return array.exact_key_items() else: if funcdef is not None: m = "TypeError: %s argument after ** must be a mapping, not %s" \ % (funcdef.name.value, array) analysis.add(context, 'type-error-star-star', input_node, message=m) return {}
12,218
Python
.py
277
33.169675
94
0.598081
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,894
references.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/references.py
import os import re from parso import python_bytes_to_unicode from jedi.debug import dbg from jedi.file_io import KnownContentFileIO, FolderIO from jedi.inference.names import SubModuleName from jedi.inference.imports import load_module_from_path from jedi.inference.filters import ParserTreeFilter from jedi.inference.gradual.conversion import convert_names _IGNORE_FOLDERS = ('.tox', '.venv', '.mypy_cache', 'venv', '__pycache__') _OPENED_FILE_LIMIT = 2000 """ Stats from a 2016 Lenovo Notebook running Linux: With os.walk, it takes about 10s to scan 11'000 files (without filesystem caching). Once cached it only takes 5s. So it is expected that reading all those files might take a few seconds, but not a lot more. """ _PARSED_FILE_LIMIT = 30 """ For now we keep the amount of parsed files really low, since parsing might take easily 100ms for bigger files. """ def _resolve_names(definition_names, avoid_names=()): for name in definition_names: if name in avoid_names: # Avoiding recursions here, because goto on a module name lands # on the same module. continue if not isinstance(name, SubModuleName): # SubModuleNames are not actually existing names but created # names when importing something like `import foo.bar.baz`. yield name if name.api_type == 'module': yield from _resolve_names(name.goto(), definition_names) def _dictionarize(names): return dict( (n if n.tree_name is None else n.tree_name, n) for n in names ) def _find_defining_names(module_context, tree_name): found_names = _find_names(module_context, tree_name) for name in list(found_names): # Convert from/to stubs, because those might also be usages. found_names |= set(convert_names( [name], only_stubs=not name.get_root_context().is_stub(), prefer_stub_to_compiled=False )) found_names |= set(_find_global_variables(found_names, tree_name.value)) for name in list(found_names): if name.api_type == 'param' or name.tree_name is None \ or name.tree_name.parent.type == 'trailer': continue found_names |= set(_add_names_in_same_context(name.parent_context, name.string_name)) return set(_resolve_names(found_names)) def _find_names(module_context, tree_name): name = module_context.create_name(tree_name) found_names = set(name.goto()) found_names.add(name) return set(_resolve_names(found_names)) def _add_names_in_same_context(context, string_name): if context.tree_node is None: return until_position = None while True: filter_ = ParserTreeFilter( parent_context=context, until_position=until_position, ) names = set(filter_.get(string_name)) if not names: break yield from names ordered = sorted(names, key=lambda x: x.start_pos) until_position = ordered[0].start_pos def _find_global_variables(names, search_name): for name in names: if name.tree_name is None: continue module_context = name.get_root_context() try: method = module_context.get_global_filter except AttributeError: continue else: for global_name in method().get(search_name): yield global_name c = module_context.create_context(global_name.tree_name) yield from _add_names_in_same_context(c, global_name.string_name) def find_references(module_context, tree_name, only_in_module=False): inf = module_context.inference_state search_name = tree_name.value # We disable flow analysis, because if we have ifs that are only true in # certain cases, we want both sides. try: inf.flow_analysis_enabled = False found_names = _find_defining_names(module_context, tree_name) finally: inf.flow_analysis_enabled = True found_names_dct = _dictionarize(found_names) module_contexts = [module_context] if not only_in_module: for m in set(d.get_root_context() for d in found_names): if m != module_context and m.tree_node is not None \ and inf.project.path in m.py__file__().parents: module_contexts.append(m) # For param no search for other modules is necessary. if only_in_module or any(n.api_type == 'param' for n in found_names): potential_modules = module_contexts else: potential_modules = get_module_contexts_containing_name( inf, module_contexts, search_name, ) non_matching_reference_maps = {} for module_context in potential_modules: for name_leaf in module_context.tree_node.get_used_names().get(search_name, []): new = _dictionarize(_find_names(module_context, name_leaf)) if any(tree_name in found_names_dct for tree_name in new): found_names_dct.update(new) for tree_name in new: for dct in non_matching_reference_maps.get(tree_name, []): # A reference that was previously searched for matches # with a now found name. Merge. found_names_dct.update(dct) try: del non_matching_reference_maps[tree_name] except KeyError: pass else: for name in new: non_matching_reference_maps.setdefault(name, []).append(new) result = found_names_dct.values() if only_in_module: return [n for n in result if n.get_root_context() == module_context] return result def _check_fs(inference_state, file_io, regex): try: code = file_io.read() except FileNotFoundError: return None code = python_bytes_to_unicode(code, errors='replace') if not regex.search(code): return None new_file_io = KnownContentFileIO(file_io.path, code) m = load_module_from_path(inference_state, new_file_io) if m.is_compiled(): return None return m.as_context() def gitignored_lines(folder_io, file_io): ignored_paths = set() ignored_names = set() for l in file_io.read().splitlines(): if not l or l.startswith(b'#'): continue p = l.decode('utf-8', 'ignore') if p.startswith('/'): name = p[1:] if name.endswith(os.path.sep): name = name[:-1] ignored_paths.add(os.path.join(folder_io.path, name)) else: ignored_names.add(p) return ignored_paths, ignored_names def recurse_find_python_folders_and_files(folder_io, except_paths=()): except_paths = set(except_paths) for root_folder_io, folder_ios, file_ios in folder_io.walk(): # Delete folders that we don't want to iterate over. for file_io in file_ios: path = file_io.path if path.suffix in ('.py', '.pyi'): if path not in except_paths: yield None, file_io if path.name == '.gitignore': ignored_paths, ignored_names = \ gitignored_lines(root_folder_io, file_io) except_paths |= ignored_paths folder_ios[:] = [ folder_io for folder_io in folder_ios if folder_io.path not in except_paths and folder_io.get_base_name() not in _IGNORE_FOLDERS ] for folder_io in folder_ios: yield folder_io, None def recurse_find_python_files(folder_io, except_paths=()): for folder_io, file_io in recurse_find_python_folders_and_files(folder_io, except_paths): if file_io is not None: yield file_io def _find_python_files_in_sys_path(inference_state, module_contexts): sys_path = inference_state.get_sys_path() except_paths = set() yielded_paths = [m.py__file__() for m in module_contexts] for module_context in module_contexts: file_io = module_context.get_value().file_io if file_io is None: continue folder_io = file_io.get_parent_folder() while True: path = folder_io.path if not any(path.startswith(p) for p in sys_path) or path in except_paths: break for file_io in recurse_find_python_files(folder_io, except_paths): if file_io.path not in yielded_paths: yield file_io except_paths.add(path) folder_io = folder_io.get_parent_folder() def _find_project_modules(inference_state, module_contexts): except_ = [m.py__file__() for m in module_contexts] yield from recurse_find_python_files(FolderIO(inference_state.project.path), except_) def get_module_contexts_containing_name(inference_state, module_contexts, name, limit_reduction=1): """ Search a name in the directories of modules. :param limit_reduction: Divides the limits on opening/parsing files by this factor. """ # Skip non python modules for module_context in module_contexts: if module_context.is_compiled(): continue yield module_context # Very short names are not searched in other modules for now to avoid lots # of file lookups. if len(name) <= 2: return # Currently not used, because there's only `scope=project` and `scope=file` # At the moment there is no such thing as `scope=sys.path`. # file_io_iterator = _find_python_files_in_sys_path(inference_state, module_contexts) file_io_iterator = _find_project_modules(inference_state, module_contexts) yield from search_in_file_ios(inference_state, file_io_iterator, name, limit_reduction=limit_reduction) def search_in_file_ios(inference_state, file_io_iterator, name, limit_reduction=1, complete=False): parse_limit = _PARSED_FILE_LIMIT / limit_reduction open_limit = _OPENED_FILE_LIMIT / limit_reduction file_io_count = 0 parsed_file_count = 0 regex = re.compile(r'\b' + re.escape(name) + (r'' if complete else r'\b')) for file_io in file_io_iterator: file_io_count += 1 m = _check_fs(inference_state, file_io, regex) if m is not None: parsed_file_count += 1 yield m if parsed_file_count >= parse_limit: dbg('Hit limit of parsed files: %s', parse_limit) break if file_io_count >= open_limit: dbg('Hit limit of opened files: %s', open_limit) break
10,855
Python
.py
252
33.912698
93
0.627334
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,895
finder.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/finder.py
""" Searching for names with given scope and name. This is very central in Jedi and Python. The name resolution is quite complicated with descripter, ``__getattribute__``, ``__getattr__``, ``global``, etc. If you want to understand name resolution, please read the first few chapters in http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/. Flow checks +++++++++++ Flow checks are not really mature. There's only a check for ``isinstance``. It would check whether a flow has the form of ``if isinstance(a, type_or_tuple)``. Unfortunately every other thing is being ignored (e.g. a == '' would be easy to check for -> a is a string). There's big potential in these checks. """ from parso.tree import search_ancestor from parso.python.tree import Name from jedi import settings from jedi.inference.arguments import TreeArguments from jedi.inference.value import iterable from jedi.inference.base_value import NO_VALUES from jedi.parser_utils import is_scope def filter_name(filters, name_or_str): """ Searches names that are defined in a scope (the different ``filters``), until a name fits. """ string_name = name_or_str.value if isinstance(name_or_str, Name) else name_or_str names = [] for filter in filters: names = filter.get(string_name) if names: break return list(_remove_del_stmt(names)) def _remove_del_stmt(names): # Catch del statements and remove them from results. for name in names: if name.tree_name is not None: definition = name.tree_name.get_definition() if definition is not None and definition.type == 'del_stmt': continue yield name def check_flow_information(value, flow, search_name, pos): """ Try to find out the type of a variable just with the information that is given by the flows: e.g. It is also responsible for assert checks.:: if isinstance(k, str): k. # <- completion here ensures that `k` is a string. """ if not settings.dynamic_flow_information: return None result = None if is_scope(flow): # Check for asserts. module_node = flow.get_root_node() try: names = module_node.get_used_names()[search_name.value] except KeyError: return None names = reversed([ n for n in names if flow.start_pos <= n.start_pos < (pos or flow.end_pos) ]) for name in names: ass = search_ancestor(name, 'assert_stmt') if ass is not None: result = _check_isinstance_type(value, ass.assertion, search_name) if result is not None: return result if flow.type in ('if_stmt', 'while_stmt'): potential_ifs = [c for c in flow.children[1::4] if c != ':'] for if_test in reversed(potential_ifs): if search_name.start_pos > if_test.end_pos: return _check_isinstance_type(value, if_test, search_name) return result def _get_isinstance_trailer_arglist(node): if node.type in ('power', 'atom_expr') and len(node.children) == 2: # This might be removed if we analyze and, etc first, trailer = node.children if first.type == 'name' and first.value == 'isinstance' \ and trailer.type == 'trailer' and trailer.children[0] == '(': return trailer return None def _check_isinstance_type(value, node, search_name): lazy_cls = None trailer = _get_isinstance_trailer_arglist(node) if trailer is not None and len(trailer.children) == 3: arglist = trailer.children[1] args = TreeArguments(value.inference_state, value, arglist, trailer) param_list = list(args.unpack()) # Disallow keyword arguments if len(param_list) == 2 and len(arglist.children) == 3: (key1, _), (key2, lazy_value_cls) = param_list if key1 is None and key2 is None: call = _get_call_string(search_name) is_instance_call = _get_call_string(arglist.children[0]) # Do a simple get_code comparison of the strings . They should # just have the same code, and everything will be all right. # There are ways that this is not correct, if some stuff is # redefined in between. However here we don't care, because # it's a heuristic that works pretty well. if call == is_instance_call: lazy_cls = lazy_value_cls if lazy_cls is None: return None value_set = NO_VALUES for cls_or_tup in lazy_cls.infer(): if isinstance(cls_or_tup, iterable.Sequence) and cls_or_tup.array_type == 'tuple': for lazy_value in cls_or_tup.py__iter__(): value_set |= lazy_value.infer().execute_with_values() else: value_set |= cls_or_tup.execute_with_values() return value_set def _get_call_string(node): if node.parent.type == 'atom_expr': return _get_call_string(node.parent) code = '' leaf = node.get_first_leaf() end = node.get_last_leaf().end_pos while leaf.start_pos < end: code += leaf.value leaf = leaf.get_next_leaf() return code
5,326
Python
.py
121
36
90
0.635135
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,896
param.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/param.py
from collections import defaultdict from inspect import Parameter from jedi import debug from jedi.inference.utils import PushBackIterator from jedi.inference import analysis from jedi.inference.lazy_value import LazyKnownValue, \ LazyTreeValue, LazyUnknownValue from jedi.inference.value import iterable from jedi.inference.names import ParamName def _add_argument_issue(error_name, lazy_value, message): if isinstance(lazy_value, LazyTreeValue): node = lazy_value.data if node.parent.type == 'argument': node = node.parent return analysis.add(lazy_value.context, error_name, node, message) class ExecutedParamName(ParamName): def __init__(self, function_value, arguments, param_node, lazy_value, is_default=False): super().__init__(function_value, param_node.name, arguments=arguments) self._lazy_value = lazy_value self._is_default = is_default def infer(self): return self._lazy_value.infer() def matches_signature(self): if self._is_default: return True argument_values = self.infer().py__class__() if self.get_kind() in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): return True annotations = self.infer_annotation(execute_annotation=False) if not annotations: # If we cannot infer annotations - or there aren't any - pretend # that the signature matches. return True matches = any(c1.is_sub_class_of(c2) for c1 in argument_values for c2 in annotations.gather_annotation_classes()) debug.dbg("param compare %s: %s <=> %s", matches, argument_values, annotations, color='BLUE') return matches def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.string_name) def get_executed_param_names_and_issues(function_value, arguments): """ Return a tuple of: - a list of `ExecutedParamName`s corresponding to the arguments of the function execution `function_value`, containing the inferred value of those arguments (whether explicit or default) - a list of the issues encountered while building that list For example, given: ``` def foo(a, b, c=None, d='d'): ... foo(42, c='c') ``` Then for the execution of `foo`, this will return a tuple containing: - a list with entries for each parameter a, b, c & d; the entries for a, c, & d will have their values (42, 'c' and 'd' respectively) included. - a list with a single entry about the lack of a value for `b` """ def too_many_args(argument): m = _error_argument_count(funcdef, len(unpacked_va)) # Just report an error for the first param that is not needed (like # cPython). if arguments.get_calling_nodes(): # There might not be a valid calling node so check for that first. issues.append( _add_argument_issue( 'type-error-too-many-arguments', argument, message=m ) ) else: issues.append(None) debug.warning('non-public warning: %s', m) issues = [] # List[Optional[analysis issue]] result_params = [] param_dict = {} funcdef = function_value.tree_node # Default params are part of the value where the function was defined. # This means that they might have access on class variables that the # function itself doesn't have. default_param_context = function_value.get_default_param_context() for param in funcdef.get_params(): param_dict[param.name.value] = param unpacked_va = list(arguments.unpack(funcdef)) var_arg_iterator = PushBackIterator(iter(unpacked_va)) non_matching_keys = defaultdict(lambda: []) keys_used = {} keys_only = False had_multiple_value_error = False for param in funcdef.get_params(): # The value and key can both be null. There, the defaults apply. # args / kwargs will just be empty arrays / dicts, respectively. # Wrong value count is just ignored. If you try to test cases that are # not allowed in Python, Jedi will maybe not show any completions. is_default = False key, argument = next(var_arg_iterator, (None, None)) while key is not None: keys_only = True try: key_param = param_dict[key] except KeyError: non_matching_keys[key] = argument else: if key in keys_used: had_multiple_value_error = True m = ("TypeError: %s() got multiple values for keyword argument '%s'." % (funcdef.name, key)) for contextualized_node in arguments.get_calling_nodes(): issues.append( analysis.add(contextualized_node.context, 'type-error-multiple-values', contextualized_node.node, message=m) ) else: keys_used[key] = ExecutedParamName( function_value, arguments, key_param, argument) key, argument = next(var_arg_iterator, (None, None)) try: result_params.append(keys_used[param.name.value]) continue except KeyError: pass if param.star_count == 1: # *args param lazy_value_list = [] if argument is not None: lazy_value_list.append(argument) for key, argument in var_arg_iterator: # Iterate until a key argument is found. if key: var_arg_iterator.push_back((key, argument)) break lazy_value_list.append(argument) seq = iterable.FakeTuple(function_value.inference_state, lazy_value_list) result_arg = LazyKnownValue(seq) elif param.star_count == 2: if argument is not None: too_many_args(argument) # **kwargs param dct = iterable.FakeDict(function_value.inference_state, dict(non_matching_keys)) result_arg = LazyKnownValue(dct) non_matching_keys = {} else: # normal param if argument is None: # No value: Return an empty container if param.default is None: result_arg = LazyUnknownValue() if not keys_only: for contextualized_node in arguments.get_calling_nodes(): m = _error_argument_count(funcdef, len(unpacked_va)) issues.append( analysis.add( contextualized_node.context, 'type-error-too-few-arguments', contextualized_node.node, message=m, ) ) else: result_arg = LazyTreeValue(default_param_context, param.default) is_default = True else: result_arg = argument result_params.append(ExecutedParamName( function_value, arguments, param, result_arg, is_default=is_default )) if not isinstance(result_arg, LazyUnknownValue): keys_used[param.name.value] = result_params[-1] if keys_only: # All arguments should be handed over to the next function. It's not # about the values inside, it's about the names. Jedi needs to now that # there's nothing to find for certain names. for k in set(param_dict) - set(keys_used): param = param_dict[k] if not (non_matching_keys or had_multiple_value_error or param.star_count or param.default): # add a warning only if there's not another one. for contextualized_node in arguments.get_calling_nodes(): m = _error_argument_count(funcdef, len(unpacked_va)) issues.append( analysis.add(contextualized_node.context, 'type-error-too-few-arguments', contextualized_node.node, message=m) ) for key, lazy_value in non_matching_keys.items(): m = "TypeError: %s() got an unexpected keyword argument '%s'." \ % (funcdef.name, key) issues.append( _add_argument_issue( 'type-error-keyword-argument', lazy_value, message=m ) ) remaining_arguments = list(var_arg_iterator) if remaining_arguments: first_key, lazy_value = remaining_arguments[0] too_many_args(lazy_value) return result_params, issues def get_executed_param_names(function_value, arguments): """ Return a list of `ExecutedParamName`s corresponding to the arguments of the function execution `function_value`, containing the inferred value of those arguments (whether explicit or default). Any issues building this list (for example required arguments which are missing in the invocation) are ignored. For example, given: ``` def foo(a, b, c=None, d='d'): ... foo(42, c='c') ``` Then for the execution of `foo`, this will return a list containing entries for each parameter a, b, c & d; the entries for a, c, & d will have their values (42, 'c' and 'd' respectively) included. """ return get_executed_param_names_and_issues(function_value, arguments)[0] def _error_argument_count(funcdef, actual_count): params = funcdef.get_params() default_arguments = sum(1 for p in params if p.default or p.star_count) if default_arguments == 0: before = 'exactly ' else: before = 'from %s to ' % (len(params) - default_arguments) return ('TypeError: %s() takes %s%s arguments (%s given).' % (funcdef.name, before, len(params), actual_count))
10,450
Python
.py
226
33.955752
92
0.58344
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,897
names.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/names.py
from abc import abstractmethod from inspect import Parameter from typing import Optional, Tuple from parso.tree import search_ancestor from jedi.parser_utils import find_statement_documentation, clean_scope_docstring from jedi.inference.utils import unite from jedi.inference.base_value import ValueSet, NO_VALUES from jedi.inference.cache import inference_state_method_cache from jedi.inference import docstrings from jedi.cache import memoize_method from jedi.inference.helpers import deep_ast_copy, infer_call_of_leaf from jedi.plugins import plugin_manager def _merge_name_docs(names): doc = '' for name in names: if doc: # In case we have multiple values, just return all of them # separated by a few dashes. doc += '\n' + '-' * 30 + '\n' doc += name.py__doc__() return doc class AbstractNameDefinition: start_pos: Optional[Tuple[int, int]] = None string_name: str parent_context = None tree_name = None is_value_name = True """ Used for the Jedi API to know if it's a keyword or an actual name. """ @abstractmethod def infer(self): raise NotImplementedError @abstractmethod def goto(self): # Typically names are already definitions and therefore a goto on that # name will always result on itself. return {self} def get_qualified_names(self, include_module_names=False): qualified_names = self._get_qualified_names() if qualified_names is None or not include_module_names: return qualified_names module_names = self.get_root_context().string_names if module_names is None: return None return module_names + qualified_names def _get_qualified_names(self): # By default, a name has no qualified names. return None def get_root_context(self): return self.parent_context.get_root_context() def get_public_name(self): return self.string_name def __repr__(self): if self.start_pos is None: return '<%s: string_name=%s>' % (self.__class__.__name__, self.string_name) return '<%s: string_name=%s start_pos=%s>' % (self.__class__.__name__, self.string_name, self.start_pos) def is_import(self): return False def py__doc__(self): return '' @property def api_type(self): return self.parent_context.api_type def get_defining_qualified_value(self): """ Returns either None or the value that is public and qualified. Won't return a function, because a name in a function is never public. """ return None class AbstractArbitraryName(AbstractNameDefinition): """ When you e.g. want to complete dicts keys, you probably want to complete string literals, which is not really a name, but for Jedi we use this concept of Name for completions as well. """ is_value_name = False def __init__(self, inference_state, string): self.inference_state = inference_state self.string_name = string self.parent_context = inference_state.builtins_module def infer(self): return NO_VALUES class AbstractTreeName(AbstractNameDefinition): def __init__(self, parent_context, tree_name): self.parent_context = parent_context self.tree_name = tree_name def get_qualified_names(self, include_module_names=False): import_node = search_ancestor(self.tree_name, 'import_name', 'import_from') # For import nodes we cannot just have names, because it's very unclear # how they would look like. For now we just ignore them in most cases. # In case of level == 1, it works always, because it's like a submodule # lookup. if import_node is not None and not (import_node.level == 1 and self.get_root_context().get_value().is_package()): # TODO improve the situation for when level is present. if include_module_names and not import_node.level: return tuple(n.value for n in import_node.get_path_for_name(self.tree_name)) else: return None return super().get_qualified_names(include_module_names) def _get_qualified_names(self): parent_names = self.parent_context.get_qualified_names() if parent_names is None: return None return parent_names + (self.tree_name.value,) def get_defining_qualified_value(self): if self.is_import(): raise NotImplementedError("Shouldn't really happen, please report") elif self.parent_context: return self.parent_context.get_value() # Might be None return None def goto(self): context = self.parent_context name = self.tree_name definition = name.get_definition(import_name_always=True) if definition is not None: type_ = definition.type if type_ == 'expr_stmt': # Only take the parent, because if it's more complicated than just # a name it's something you can "goto" again. is_simple_name = name.parent.type not in ('power', 'trailer') if is_simple_name: return [self] elif type_ in ('import_from', 'import_name'): from jedi.inference.imports import goto_import module_names = goto_import(context, name) return module_names else: return [self] else: from jedi.inference.imports import follow_error_node_imports_if_possible values = follow_error_node_imports_if_possible(context, name) if values is not None: return [value.name for value in values] par = name.parent node_type = par.type if node_type == 'argument' and par.children[1] == '=' and par.children[0] == name: # Named param goto. trailer = par.parent if trailer.type == 'arglist': trailer = trailer.parent if trailer.type != 'classdef': if trailer.type == 'decorator': value_set = context.infer_node(trailer.children[1]) else: i = trailer.parent.children.index(trailer) to_infer = trailer.parent.children[:i] if to_infer[0] == 'await': to_infer.pop(0) value_set = context.infer_node(to_infer[0]) from jedi.inference.syntax_tree import infer_trailer for trailer in to_infer[1:]: value_set = infer_trailer(context, value_set, trailer) param_names = [] for value in value_set: for signature in value.get_signatures(): for param_name in signature.get_param_names(): if param_name.string_name == name.value: param_names.append(param_name) return param_names elif node_type == 'dotted_name': # Is a decorator. index = par.children.index(name) if index > 0: new_dotted = deep_ast_copy(par) new_dotted.children[index - 1:] = [] values = context.infer_node(new_dotted) return unite( value.goto(name, name_context=context) for value in values ) if node_type == 'trailer' and par.children[0] == '.': values = infer_call_of_leaf(context, name, cut_own_trailer=True) return values.goto(name, name_context=context) else: stmt = search_ancestor( name, 'expr_stmt', 'lambdef' ) or name if stmt.type == 'lambdef': stmt = name return context.goto(name, position=stmt.start_pos) def is_import(self): imp = search_ancestor(self.tree_name, 'import_from', 'import_name') return imp is not None @property def string_name(self): return self.tree_name.value @property def start_pos(self): return self.tree_name.start_pos class ValueNameMixin: def infer(self): return ValueSet([self._value]) def py__doc__(self): doc = self._value.py__doc__() if not doc and self._value.is_stub(): from jedi.inference.gradual.conversion import convert_names names = convert_names([self], prefer_stub_to_compiled=False) if self not in names: return _merge_name_docs(names) return doc def _get_qualified_names(self): return self._value.get_qualified_names() def get_root_context(self): if self.parent_context is None: # A module return self._value.as_context() return super().get_root_context() def get_defining_qualified_value(self): context = self.parent_context if context.is_module() or context.is_class(): return self.parent_context.get_value() # Might be None return None @property def api_type(self): return self._value.api_type class ValueName(ValueNameMixin, AbstractTreeName): def __init__(self, value, tree_name): super().__init__(value.parent_context, tree_name) self._value = value def goto(self): return ValueSet([self._value.name]) class TreeNameDefinition(AbstractTreeName): _API_TYPES = dict( import_name='module', import_from='module', funcdef='function', param='param', classdef='class', ) def infer(self): # Refactor this, should probably be here. from jedi.inference.syntax_tree import tree_name_to_values return tree_name_to_values( self.parent_context.inference_state, self.parent_context, self.tree_name ) @property def api_type(self): definition = self.tree_name.get_definition(import_name_always=True) if definition is None: return 'statement' return self._API_TYPES.get(definition.type, 'statement') def assignment_indexes(self): """ Returns an array of tuple(int, node) of the indexes that are used in tuple assignments. For example if the name is ``y`` in the following code:: x, (y, z) = 2, '' would result in ``[(1, xyz_node), (0, yz_node)]``. When searching for b in the case ``a, *b, c = [...]`` it will return:: [(slice(1, -1), abc_node)] """ indexes = [] is_star_expr = False node = self.tree_name.parent compare = self.tree_name while node is not None: if node.type in ('testlist', 'testlist_comp', 'testlist_star_expr', 'exprlist'): for i, child in enumerate(node.children): if child == compare: index = int(i / 2) if is_star_expr: from_end = int((len(node.children) - i) / 2) index = slice(index, -from_end) indexes.insert(0, (index, node)) break else: raise LookupError("Couldn't find the assignment.") is_star_expr = False elif node.type == 'star_expr': is_star_expr = True elif node.type in ('expr_stmt', 'sync_comp_for'): break compare = node node = node.parent return indexes @property def inference_state(self): # Used by the cache function below return self.parent_context.inference_state @inference_state_method_cache(default='') def py__doc__(self): api_type = self.api_type if api_type in ('function', 'class', 'property'): if self.parent_context.get_root_context().is_stub(): from jedi.inference.gradual.conversion import convert_names names = convert_names([self], prefer_stub_to_compiled=False) if self not in names: return _merge_name_docs(names) # Make sure the names are not TreeNameDefinitions anymore. return clean_scope_docstring(self.tree_name.get_definition()) if api_type == 'module': names = self.goto() if self not in names: return _merge_name_docs(names) if api_type == 'statement' and self.tree_name.is_definition(): return find_statement_documentation(self.tree_name.get_definition()) return '' class _ParamMixin: def maybe_positional_argument(self, include_star=True): options = [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD] if include_star: options.append(Parameter.VAR_POSITIONAL) return self.get_kind() in options def maybe_keyword_argument(self, include_stars=True): options = [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD] if include_stars: options.append(Parameter.VAR_KEYWORD) return self.get_kind() in options def _kind_string(self): kind = self.get_kind() if kind == Parameter.VAR_POSITIONAL: # *args return '*' if kind == Parameter.VAR_KEYWORD: # **kwargs return '**' return '' def get_qualified_names(self, include_module_names=False): return None class ParamNameInterface(_ParamMixin): api_type = 'param' def get_kind(self): raise NotImplementedError def to_string(self): raise NotImplementedError def get_executed_param_name(self): """ For dealing with type inference and working around the graph, we sometimes want to have the param name of the execution. This feels a bit strange and we might have to refactor at some point. For now however it exists to avoid infering params when we don't really need them (e.g. when we can just instead use annotations. """ return None @property def star_count(self): kind = self.get_kind() if kind == Parameter.VAR_POSITIONAL: return 1 if kind == Parameter.VAR_KEYWORD: return 2 return 0 def infer_default(self): return NO_VALUES class BaseTreeParamName(ParamNameInterface, AbstractTreeName): annotation_node = None default_node = None def to_string(self): output = self._kind_string() + self.get_public_name() annotation = self.annotation_node default = self.default_node if annotation is not None: output += ': ' + annotation.get_code(include_prefix=False) if default is not None: output += '=' + default.get_code(include_prefix=False) return output def get_public_name(self): name = self.string_name if name.startswith('__'): # Params starting with __ are an equivalent to positional only # variables in typeshed. name = name[2:] return name def goto(self, **kwargs): return [self] class _ActualTreeParamName(BaseTreeParamName): def __init__(self, function_value, tree_name): super().__init__( function_value.get_default_param_context(), tree_name) self.function_value = function_value def _get_param_node(self): return search_ancestor(self.tree_name, 'param') @property def annotation_node(self): return self._get_param_node().annotation def infer_annotation(self, execute_annotation=True, ignore_stars=False): from jedi.inference.gradual.annotation import infer_param values = infer_param( self.function_value, self._get_param_node(), ignore_stars=ignore_stars) if execute_annotation: values = values.execute_annotation() return values def infer_default(self): node = self.default_node if node is None: return NO_VALUES return self.parent_context.infer_node(node) @property def default_node(self): return self._get_param_node().default def get_kind(self): tree_param = self._get_param_node() if tree_param.star_count == 1: # *args return Parameter.VAR_POSITIONAL if tree_param.star_count == 2: # **kwargs return Parameter.VAR_KEYWORD # Params starting with __ are an equivalent to positional only # variables in typeshed. if tree_param.name.value.startswith('__'): return Parameter.POSITIONAL_ONLY parent = tree_param.parent param_appeared = False for p in parent.children: if param_appeared: if p == '/': return Parameter.POSITIONAL_ONLY else: if p == '*': return Parameter.KEYWORD_ONLY if p.type == 'param': if p.star_count: return Parameter.KEYWORD_ONLY if p == tree_param: param_appeared = True return Parameter.POSITIONAL_OR_KEYWORD def infer(self): values = self.infer_annotation() if values: return values doc_params = docstrings.infer_param(self.function_value, self._get_param_node()) return doc_params class AnonymousParamName(_ActualTreeParamName): @plugin_manager.decorate(name='goto_anonymous_param') def goto(self): return super().goto() @plugin_manager.decorate(name='infer_anonymous_param') def infer(self): values = super().infer() if values: return values from jedi.inference.dynamic_params import dynamic_param_lookup param = self._get_param_node() values = dynamic_param_lookup(self.function_value, param.position_index) if values: return values if param.star_count == 1: from jedi.inference.value.iterable import FakeTuple value = FakeTuple(self.function_value.inference_state, []) elif param.star_count == 2: from jedi.inference.value.iterable import FakeDict value = FakeDict(self.function_value.inference_state, {}) elif param.default is None: return NO_VALUES else: return self.function_value.parent_context.infer_node(param.default) return ValueSet({value}) class ParamName(_ActualTreeParamName): def __init__(self, function_value, tree_name, arguments): super().__init__(function_value, tree_name) self.arguments = arguments def infer(self): values = super().infer() if values: return values return self.get_executed_param_name().infer() def get_executed_param_name(self): from jedi.inference.param import get_executed_param_names params_names = get_executed_param_names(self.function_value, self.arguments) return params_names[self._get_param_node().position_index] class ParamNameWrapper(_ParamMixin): def __init__(self, param_name): self._wrapped_param_name = param_name def __getattr__(self, name): return getattr(self._wrapped_param_name, name) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self._wrapped_param_name) class ImportName(AbstractNameDefinition): start_pos = (1, 0) _level = 0 def __init__(self, parent_context, string_name): self._from_module_context = parent_context self.string_name = string_name def get_qualified_names(self, include_module_names=False): if include_module_names: if self._level: assert self._level == 1, "Everything else is not supported for now" module_names = self._from_module_context.string_names if module_names is None: return module_names return module_names + (self.string_name,) return (self.string_name,) return () @property def parent_context(self): m = self._from_module_context import_values = self.infer() if not import_values: return m # It's almost always possible to find the import or to not find it. The # importing returns only one value, pretty much always. return next(iter(import_values)).as_context() @memoize_method def infer(self): from jedi.inference.imports import Importer m = self._from_module_context return Importer(m.inference_state, [self.string_name], m, level=self._level).follow() def goto(self): return [m.name for m in self.infer()] @property def api_type(self): return 'module' def py__doc__(self): return _merge_name_docs(self.goto()) class SubModuleName(ImportName): _level = 1 class NameWrapper: def __init__(self, wrapped_name): self._wrapped_name = wrapped_name def __getattr__(self, name): return getattr(self._wrapped_name, name) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self._wrapped_name) class StubNameMixin: def py__doc__(self): from jedi.inference.gradual.conversion import convert_names # Stubs are not complicated and we can just follow simple statements # that have an equals in them, because they typically make something # else public. See e.g. stubs for `requests`. names = [self] if self.api_type == 'statement' and '=' in self.tree_name.get_definition().children: names = [v.name for v in self.infer()] names = convert_names(names, prefer_stub_to_compiled=False) if self in names: return super().py__doc__() else: # We have signatures ourselves in stubs, so don't use signatures # from the implementation. return _merge_name_docs(names) # From here on down we make looking up the sys.version_info fast. class StubName(StubNameMixin, TreeNameDefinition): def infer(self): inferred = super().infer() if self.string_name == 'version_info' and self.get_root_context().py__name__() == 'sys': from jedi.inference.gradual.stub_value import VersionInfo return ValueSet(VersionInfo(c) for c in inferred) return inferred class ModuleName(ValueNameMixin, AbstractNameDefinition): start_pos = 1, 0 def __init__(self, value, name): self._value = value self._name = name @property def string_name(self): return self._name class StubModuleName(StubNameMixin, ModuleName): pass
23,188
Python
.py
548
32.191606
98
0.607836
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,898
lazy_value.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/lazy_value.py
from jedi.inference.base_value import ValueSet, NO_VALUES from jedi.common import monkeypatch class AbstractLazyValue: def __init__(self, data, min=1, max=1): self.data = data self.min = min self.max = max def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.data) def infer(self): raise NotImplementedError class LazyKnownValue(AbstractLazyValue): """data is a Value.""" def infer(self): return ValueSet([self.data]) class LazyKnownValues(AbstractLazyValue): """data is a ValueSet.""" def infer(self): return self.data class LazyUnknownValue(AbstractLazyValue): def __init__(self, min=1, max=1): super().__init__(None, min, max) def infer(self): return NO_VALUES class LazyTreeValue(AbstractLazyValue): def __init__(self, context, node, min=1, max=1): super().__init__(node, min, max) self.context = context # We need to save the predefined names. It's an unfortunate side effect # that needs to be tracked otherwise results will be wrong. self._predefined_names = dict(context.predefined_names) def infer(self): with monkeypatch(self.context, 'predefined_names', self._predefined_names): return self.context.infer_node(self.data) def get_merged_lazy_value(lazy_values): if len(lazy_values) > 1: return MergedLazyValues(lazy_values) else: return lazy_values[0] class MergedLazyValues(AbstractLazyValue): """data is a list of lazy values.""" def infer(self): return ValueSet.from_sets(l.infer() for l in self.data)
1,667
Python
.py
43
32.325581
83
0.663138
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)
29,899
flow_analysis.py
DamnWidget_anaconda/anaconda_lib/jedi/inference/flow_analysis.py
from typing import Dict, Optional from jedi.parser_utils import get_flow_branch_keyword, is_scope, get_parent_scope from jedi.inference.recursion import execution_allowed from jedi.inference.helpers import is_big_annoying_library class Status: lookup_table: Dict[Optional[bool], 'Status'] = {} def __init__(self, value: Optional[bool], name: str) -> None: self._value = value self._name = name Status.lookup_table[value] = self def invert(self): if self is REACHABLE: return UNREACHABLE elif self is UNREACHABLE: return REACHABLE else: return UNSURE def __and__(self, other): if UNSURE in (self, other): return UNSURE else: return REACHABLE if self._value and other._value else UNREACHABLE def __repr__(self): return '<%s: %s>' % (type(self).__name__, self._name) REACHABLE = Status(True, 'reachable') UNREACHABLE = Status(False, 'unreachable') UNSURE = Status(None, 'unsure') def _get_flow_scopes(node): while True: node = get_parent_scope(node, include_flows=True) if node is None or is_scope(node): return yield node def reachability_check(context, value_scope, node, origin_scope=None): if is_big_annoying_library(context) \ or not context.inference_state.flow_analysis_enabled: return UNSURE first_flow_scope = get_parent_scope(node, include_flows=True) if origin_scope is not None: origin_flow_scopes = list(_get_flow_scopes(origin_scope)) node_flow_scopes = list(_get_flow_scopes(node)) branch_matches = True for flow_scope in origin_flow_scopes: if flow_scope in node_flow_scopes: node_keyword = get_flow_branch_keyword(flow_scope, node) origin_keyword = get_flow_branch_keyword(flow_scope, origin_scope) branch_matches = node_keyword == origin_keyword if flow_scope.type == 'if_stmt': if not branch_matches: return UNREACHABLE elif flow_scope.type == 'try_stmt': if not branch_matches and origin_keyword == 'else' \ and node_keyword == 'except': return UNREACHABLE if branch_matches: break # Direct parents get resolved, we filter scopes that are separate # branches. This makes sense for autocompletion and static analysis. # For actual Python it doesn't matter, because we're talking about # potentially unreachable code. # e.g. `if 0:` would cause all name lookup within the flow make # unaccessible. This is not a "problem" in Python, because the code is # never called. In Jedi though, we still want to infer types. while origin_scope is not None: if first_flow_scope == origin_scope and branch_matches: return REACHABLE origin_scope = origin_scope.parent return _break_check(context, value_scope, first_flow_scope, node) def _break_check(context, value_scope, flow_scope, node): reachable = REACHABLE if flow_scope.type == 'if_stmt': if flow_scope.is_node_after_else(node): for check_node in flow_scope.get_test_nodes(): reachable = _check_if(context, check_node) if reachable in (REACHABLE, UNSURE): break reachable = reachable.invert() else: flow_node = flow_scope.get_corresponding_test_node(node) if flow_node is not None: reachable = _check_if(context, flow_node) elif flow_scope.type in ('try_stmt', 'while_stmt'): return UNSURE # Only reachable branches need to be examined further. if reachable in (UNREACHABLE, UNSURE): return reachable if value_scope != flow_scope and value_scope != flow_scope.parent: flow_scope = get_parent_scope(flow_scope, include_flows=True) return reachable & _break_check(context, value_scope, flow_scope, node) else: return reachable def _check_if(context, node): with execution_allowed(context.inference_state, node) as allowed: if not allowed: return UNSURE types = context.infer_node(node) values = set(x.py__bool__() for x in types) if len(values) == 1: return Status.lookup_table[values.pop()] else: return UNSURE
4,583
Python
.py
101
35.346535
82
0.623374
DamnWidget/anaconda
2,213
260
184
GPL-3.0
9/5/2024, 5:14:06 PM (Europe/Amsterdam)