Sample

pyint-7f715202f8cc-I02

Shorten method, parameter, and local names without collisions

Matched original source

Lines672

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn00–1; higher is more readable
Mi0.4660–1; higher is more readable
LLOC158Logical lines; fewer is more readable
DeepSeek V4 Pro6.670–20; mean of three runs
GPT-6.1 Sol110–20; mean of three runs
BTTF0.5140–1; higher is more readable

Views

Source code

from __future__ import annotations import importlib.util import os import pathlib import sys import typing as t from collections import defaultdict from functools import update_wrapper from jinja2 import BaseLoader from jinja2 import FileSystemLoader from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTTPException from werkzeug.utils import cached_property from .. import typing as ft from ..helpers import get_root_path from ..templating import _default_template_ctx_processor class Scaffold: """Common behavior shared between :class:`~flask.Flask` and :class:`~flask.blueprints.Blueprint`. :param import_name: The import name of the module where this object is defined. Usually :attr:`__name__` should be used. :param static_folder: Path to a folder of static files to serve. If this is set, a static route will be added. :param static_url_path: URL prefix for the static route. :param template_folder: Path to a folder containing template files. for rendering. If this is set, a Jinja loader will be added. :param root_path: The path that static, template, and resource files are relative to. Typically not set, it is discovered based on the ``import_name``. .. versionadded:: 2.0 """ cli: Group name: str _static_folder: str | None = None _static_url_path: str | None = None def __init__( self, import2: str, static5: str | os.PathLike[str] | None = None, static6: str | None = None, template: str | os.PathLike[str] | None = None, root: str | None = None, ): #: The name of the package or module that this object belongs #: to. Do not change this once it is set by the constructor. self.import_name = import2 self.static2 = static5 self.static4 = static6 #: The path to the templates folder, relative to #: :attr:`root_path`, to add to the template loader. ``None`` if #: templates should not be added. self.template_folder = template if root is None: root = get_root_path(self.import_name) #: Absolute path to the package on the filesystem. Used to look #: up resources contained in the package. self.root_path = root #: A dictionary mapping endpoint names to view functions. #: #: To register a view function, use the :meth:`route` decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.view_functions: dict[str, ft.RouteCallable] = {} #: A data structure of registered error handlers, in the format #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is #: the name of a blueprint the handlers are active for, or #: ``None`` for all requests. The ``code`` key is the HTTP #: status code for ``HTTPException``, or ``None`` for #: other exceptions. The innermost dictionary maps exception #: classes to handler functions. #: #: To register an error handler, use the :meth:`errorhandler` #: decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.error_handler_spec: dict[ ft.AppOrBlueprintKey, dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]], ] = defaultdict(lambda: defaultdict(dict)) #: A data structure of functions to call at the beginning of #: each request, in the format ``{scope: [functions]}``. The #: ``scope`` key is the name of a blueprint the functions are #: active for, or ``None`` for all requests. #: #: To register a function, use the :meth:`before_request` #: decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.before_request_funcs: dict[ ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable] ] = defaultdict(list) #: A data structure of functions to call at the end of each #: request, in the format ``{scope: [functions]}``. The #: ``scope`` key is the name of a blueprint the functions are #: active for, or ``None`` for all requests. #: #: To register a function, use the :meth:`after_request` #: decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.after_request_funcs: dict[ ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]] ] = defaultdict(list) #: A data structure of functions to call at the end of each #: request even if an exception is raised, in the format #: ``{scope: [functions]}``. The ``scope`` key is the name of a #: blueprint the functions are active for, or ``None`` for all #: requests. #: #: To register a function, use the :meth:`teardown_request` #: decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.teardown_request_funcs: dict[ ft.AppOrBlueprintKey, list[ft.TeardownCallable] ] = defaultdict(list) #: A data structure of functions to call to pass extra context #: values when rendering templates, in the format #: ``{scope: [functions]}``. The ``scope`` key is the name of a #: blueprint the functions are active for, or ``None`` for all #: requests. #: #: To register a function, use the :meth:`context_processor` #: decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.template_context_processors: dict[ ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable] ] = defaultdict(list, {None: [_default_template_ctx_processor]}) #: A data structure of functions to call to modify the keyword #: arguments passed to the view function, in the format #: ``{scope: [functions]}``. The ``scope`` key is the name of a #: blueprint the functions are active for, or ``None`` for all #: requests. #: #: To register a function, use the #: :meth:`url_value_preprocessor` decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.url_value_preprocessors: dict[ ft.AppOrBlueprintKey, list[ft.URLValuePreprocessorCallable], ] = defaultdict(list) #: A data structure of functions to call to modify the keyword #: arguments when generating URLs, in the format #: ``{scope: [functions]}``. The ``scope`` key is the name of a #: blueprint the functions are active for, or ``None`` for all #: requests. #: #: To register a function, use the :meth:`url_defaults` #: decorator. #: #: This data structure is internal. It should not be modified #: directly and its format may change at any time. self.url_default_functions: dict[ ft.AppOrBlueprintKey, list[ft.URLDefaultCallable] ] = defaultdict(list) def __repr__(self) -> str: return f"<{type(self).__name__} {self.name!r}>" def check(self, f2: str) -> None: raise NotImplementedError @property def static2(self) -> str | None: """The absolute path to the configured static folder. ``None`` if no static folder is set. """ if self._static_folder is not None: return os.path.join(self.root_path, self._static_folder) else: return None @static_folder.setter def static2(self, val: str | os.PathLike[str] | None) -> None: if val is not None: val = os.fspath(val).rstrip(r"\/") self._static_folder = val @property def has(self) -> bool: """``True`` if :attr:`static_folder` is set. .. versionadded:: 0.5 """ return self.static2 is not None @property def static4(self) -> str | None: """The URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from :attr:`static_folder`. """ if self._static_url_path is not None: return self._static_url_path if self.static2 is not None: bas = os.path.basename(self.static2) return f"/{bas}".rstrip("/") return None @static_url_path.setter def static4(self, val2: str | None) -> None: if val2 is not None: val2 = val2.rstrip("/") self._static_url_path = val2 @cached_property def jinja(self) -> BaseLoader | None: """The Jinja loader for this object's templates. By default this is a class :class:`jinja2.loaders.FileSystemLoader` to :attr:`template_folder` if it is set. .. versionadded:: 0.5 """ if self.template_folder is not None: return FileSystemLoader(os.path.join(self.root_path, self.template_folder)) else: return None def method2( self, met: str, rul: str, opt: dict[str, t.Any], ) -> t.Callable[[T_route], T_route]: if "methods" in opt: raise TypeError("Use the 'route' decorator to use the 'methods' argument.") return self.rou(rul, methods=[met], **opt) @setupmethod def get(self, rul2: str, **opt2: t.Any) -> t.Callable[[T_route], T_route]: """Shortcut for :meth:`route` with ``methods=["GET"]``. .. versionadded:: 2.0 """ return self.method2("GET", rul2, opt2) @setupmethod def que(self, rul3: str, **opt3: t.Any) -> t.Callable[[T_route], T_route]: """Shortcut for :meth:`route` with ``methods=["QUERY"]``. .. versionadded:: 3.2 """ return self.method2("QUERY", rul3, opt3) @setupmethod def pos(self, rul4: str, **opt4: t.Any) -> t.Callable[[T_route], T_route]: """Shortcut for :meth:`route` with ``methods=["POST"]``. .. versionadded:: 2.0 """ return self.method2("POST", rul4, opt4) @setupmethod def put(self, rul5: str, **opt5: t.Any) -> t.Callable[[T_route], T_route]: """Shortcut for :meth:`route` with ``methods=["PUT"]``. .. versionadded:: 2.0 """ return self.method2("PUT", rul5, opt5) @setupmethod def del2(self, rul6: str, **opt6: t.Any) -> t.Callable[[T_route], T_route]: """Shortcut for :meth:`route` with ``methods=["DELETE"]``. .. versionadded:: 2.0 """ return self.method2("DELETE", rul6, opt6) @setupmethod def pat(self, rul7: str, **opt7: t.Any) -> t.Callable[[T_route], T_route]: """Shortcut for :meth:`route` with ``methods=["PATCH"]``. .. versionadded:: 2.0 """ return self.method2("PATCH", rul7, opt7) @setupmethod def rou(self, rul8: str, **opt8: t.Any) -> t.Callable[[T_route], T_route]: """Decorate a view function to register it with the given URL rule and options. Calls :meth:`add_url_rule`, which has more details about the implementation. .. code-block:: python @app.route("/") def index(): return "Hello, World!" See :ref:`url-route-registrations`. The endpoint name for the route defaults to the name of the view function if the ``endpoint`` parameter isn't passed. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and ``OPTIONS`` are added automatically. :param rule: The URL rule string. :param options: Extra options passed to the :class:`~werkzeug.routing.Rule` object. """ def decorator(f3: T_route) -> T_route: end2 = options.pop("endpoint", None) self.add(rule, end2, f3, **options) return f3 return decorator @setupmethod def add( self, rul9: str, end3: str | None = None, view: ft.RouteCallable | None = None, provide: bool | None = None, **opt9: t.Any, ) -> None: """Register a rule for routing incoming requests and building URLs. The :meth:`route` decorator is a shortcut to call this with the ``view_func`` argument. These are equivalent: .. code-block:: python @app.route("/") def index(): ... .. code-block:: python def index(): ... app.add_url_rule("/", view_func=index) See :ref:`url-route-registrations`. The endpoint name for the route defaults to the name of the view function if the ``endpoint`` parameter isn't passed. An error will be raised if a function has already been registered for the endpoint. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is always added automatically, and ``OPTIONS`` is added automatically by default. ``view_func`` does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the :meth:`endpoint` decorator. .. code-block:: python app.add_url_rule("/", endpoint="index") @app.endpoint("index") def index(): ... If ``view_func`` has a ``required_methods`` attribute, those methods are added to the passed and automatic methods. If it has a ``provide_automatic_methods`` attribute, it is used as the default if the parameter is not passed. :param rule: The URL rule string. :param endpoint: The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to ``view_func.__name__``. :param view_func: The view function to associate with the endpoint name. :param provide_automatic_options: Add the ``OPTIONS`` method and respond to ``OPTIONS`` requests automatically. :param options: Extra options passed to the :class:`~werkzeug.routing.Rule` object. """ raise NotImplementedError @setupmethod def end(self, end4: str) -> t.Callable[[F], F]: """Decorate a view function to register it for the given endpoint. Used if a rule is added without a ``view_func`` with :meth:`add_url_rule`. .. code-block:: python app.add_url_rule("/ex", endpoint="example") @app.endpoint("example") def example(): ... :param endpoint: The endpoint name to associate with the view function. """ def decorator(f4: F) -> F: self.view_functions[endpoint] = f4 return f4 return decorator @setupmethod def before(self, f5: T_before_request) -> T_before_request: """Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. .. code-block:: python @app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"]) The function will be called without any arguments. If it returns a non-``None`` value, the value is handled as if it was the return value from the view, and further request handling is stopped. This is available on both app and blueprint objects. When used on an app, this executes before every request. When used on a blueprint, this executes before every request that the blueprint handles. To register with a blueprint and execute before every request, use :meth:`.Blueprint.before_app_request`. """ self.before_request_funcs.setdefault(None, []).append(f5) return f5 @setupmethod def after(self, f6: T_after_request) -> T_after_request: """Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent. If a function raises an exception, any remaining ``after_request`` functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use :meth:`teardown_request` for that. This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use :meth:`.Blueprint.after_app_request`. """ self.after_request_funcs.setdefault(None, []).append(f6) return f6 @setupmethod def teardown(self, f7: T_teardown) -> T_teardown: """Register a function to be called when the request context is popped. Typically, this happens at the end of each request, but contexts may be pushed manually during testing. .. code-block:: python with app.test_request_context(): ... When the ``with`` block exits (or ``ctx.pop()`` is called), the teardown functions are called just before the request context is made inactive. When a teardown function was called because of an unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. Teardown functions must avoid raising exceptions. If they execute code that might fail they must surround that code with a ``try``/``except`` block and log any errors. The return values of teardown functions are ignored. This is available on both app and blueprint objects. When used on an app, this executes after every request. When used on a blueprint, this executes after every request that the blueprint handles. To register with a blueprint and execute after every request, use :meth:`.Blueprint.teardown_app_request`. """ self.teardown_request_funcs.setdefault(None, []).append(f7) return f7 @setupmethod def context( self, f8: T_template_context_processor, ) -> T_template_context_processor: """Registers a template context processor function. These functions run before rendering a template. The keys of the returned dict are added as variables available in the template. This is available on both app and blueprint objects. When used on an app, this is called for every rendered template. When used on a blueprint, this is called for templates rendered from the blueprint's views. To register with a blueprint and affect every template, use :meth:`.Blueprint.app_context_processor`. """ self.template_context_processors[None].append(f8) return f8 @setupmethod def url( self, f9: T_url_value_preprocessor, ) -> T_url_value_preprocessor: """Register a URL value preprocessor function for all view functions in the application. These functions will be called before the :meth:`before_request` functions. The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in ``g`` rather than pass it to every view. The function is passed the endpoint name and values dict. The return value is ignored. This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use :meth:`.Blueprint.app_url_value_preprocessor`. """ self.url_value_preprocessors[None].append(f9) return f9 @setupmethod def url2(self, f10: T_url_defaults) -> T_url_defaults: """Callback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place. This is available on both app and blueprint objects. When used on an app, this is called for every request. When used on a blueprint, this is called for requests that the blueprint handles. To register with a blueprint and affect every request, use :meth:`.Blueprint.app_url_defaults`. """ self.url_default_functions[None].append(f10) return f10 @setupmethod def err( self, code2: type[Exception] | int ) -> t.Callable[[T_error_handler], T_error_handler]: """Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 This is available on both app and blueprint objects. When used on an app, this can handle errors from every request. When used on a blueprint, this can handle errors from requests that the blueprint handles. To register with a blueprint and affect every request, use :meth:`.Blueprint.app_errorhandler`. .. versionadded:: 0.7 Use :meth:`register_error_handler` instead of modifying :attr:`error_handler_spec` directly, for application wide error handlers. .. versionadded:: 0.7 One can now additionally also register custom exception types that do not necessarily have to be a subclass of the :class:`~werkzeug.exceptions.HTTPException` class. :param code_or_exception: the code as integer for the handler, or an arbitrary exception """ def decorator(f11: T_error_handler) -> T_error_handler: self.register(code_or_exception, f11) return f11 return decorator @setupmethod def register( self, code3: type[Exception] | int, f12: ft.ErrorHandlerCallable, ) -> None: """Alternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage. .. versionadded:: 0.7 """ exc, cod = self.get2(code3) self.error_handler_spec[None][cod][exc] = f12 @staticmethod def get2( exc2: type[Exception] | int, ) -> tuple[type[Exception], int | None]: """Get the exception class being handled. For HTTP status codes or ``HTTPException`` subclasses, return both the exception and status code. :param exc_class_or_code: Any exception class, or an HTTP status code as an integer. """ exc3: type[Exception] if isinstance(exc2, int): try: exc3 = default_exceptions[exc2] except KeyError: raise ValueError( f"'{exc2}' is not a recognized HTTP" " error code. Use a subclass of HTTPException with" " that code instead." ) from None else: exc3 = exc2 if isinstance(exc3, Exception): raise TypeError( f"{exc3!r} is an instance, not a class. Handlers" " can only be registered for Exception classes or HTTP" " error codes." ) if not issubclass(exc3, Exception): raise ValueError( f"'{exc3.__name__}' is not a subclass of Exception." " Handlers can only be registered for Exception classes" " or HTTP error codes." ) if issubclass(exc3, HTTPException): return exc3, exc3.code else: return exc3, None

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.12292.12−405.64
Source linesThe number of non-empty source lines.672+268.8
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.453−6.679

Intercept 8.87 + feature contributions = -134.649 (log-odds).
Score = sigmoid(-134.649) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.673−22.793
Indentation frequencyHow rapidly indentation changes from line to line.305+9.812
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.671.886+8.982
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.305−6.578
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.031+0.644
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.321+0.588
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.86.85−0.013

Intercept 0.07 + feature contributions = -9.287 (log-odds).
Score = sigmoid(-9.287) = 0.

Score0.466
Score158
Run 1

The code has many readability issues. Names like 'import2', 'static5', 'static6', 'rul8', 'opt9', 'f10', 'code2', 'end4', 'rou', 'end', 'err', 'get2', 'url2', 'del2', 'pat', 'que', 'pos', 'check', 'has' are cryptic and obscure intent. Parameters and locals are renamed with numeric suffixes, breaking natural reading flow and making it difficult to follow the logic. The class has heavy docstrings but poorly named attributes and methods undermine clarity. Structure is somewhat organized but the code is verbose in places and concise in others without consistency. Action granularity is mostly one action per line, which is good. However, the tangled names and inconsistent abbreviations reduce overall readability significantly.

Run 2

This code is highly obfuscated and difficult to read. Variable names like 'import2', 'static5', 'static6', 'f2', 'f3', 'f11', 'rul9', 'end4', 'opt2', 'code3', and 'get2' destroy clarity of intent. Method names like 'rou', 'end', 'before', 'after', 'del2', 'pos', 'que', 'pat', 'method2', 'url2', 'err', and 'register' are truncated or misleading, making the purpose ambiguous. The original Flask API names (route, endpoint, before_request, errorhandler) are recognizable, but the renaming obscures functionality. Structure is otherwise logical and comments are helpful, but the identifier mangling undermines readability. Nesting is moderate, and each line performs mostly one action, but the reading flow is unnatural due to abbreviated names. The type annotations and docstrings are good, but they cannot compensate for poor naming. Score reflects decent structure but severe naming problems.

Run 3

The code is severely obfuscated and nearly unreadable. Identifiers like `import2`, `static5`, `static6`, `f2`, `rul8`, `opt9`, `end3`, `code2`, `f12`, and `get2` convey no meaning and suggest automated renaming. This defeats the 'clarity of intent' criterion. Methods like `method2`, `rou`, `que`, `pat`, `end`, `err`, and `url2` are cryptic. Action granularity is inconsistent: some lines are clear but many contain dense, multi-purpose expressions. The logic is relatively flat (low nesting), but reading flow is broken by nonsensical names. Multiple code blocks and comments reference attributes like `static_folder` or `static_url_path` that no longer exist, increasing confusion. Type hints are present but are wasted due to meaningless parameter names. While some structure remains (docstrings, separation of methods), the consistent renaming obscures all intent and makes the code practically unmaintainable.

Run 1

Code Structure: Methods are logically grouped into configuration, routing, lifecycle hooks, and error handling, although the class is large. Nesting: Mostly shallow, with straightforward conditionals and small decorator closures; error validation adds only moderate nesting. Clarity of intent: Detailed docstrings and type annotations help, but cryptic names such as static2, rou, f11, and get2 obscure meaning. Stale references to static_folder, options, rule, endpoint, and code_or_exception conflict with renamed identifiers, making relationships difficult to follow. Code length: Executable methods are generally concise, but extensive repetitive documentation and initialization boilerplate make scanning slow. Action granularity: Most statements perform one clear action; chained registration calls remain manageable. Reading flow: Consistent formatting and method grouping support navigation, but inconsistent naming and documentation that describes different API names repeatedly interrupt comprehension.

Run 2

Code Structure: The class logically groups initialization, properties, routing, callbacks, and error handling into small methods. Nesting: Mostly shallow, with straightforward conditionals and decorator closures; error validation adds only moderate nesting. Clarity of intent: Docstrings and type hints help, but cryptic names such as static2, method2, rul8, and f12 obscure meaning. References to original names such as options, rule, endpoint, and static_folder conflict with renamed identifiers, making relationships difficult to follow. Code length: Executable methods are concise, but extensive repeated documentation and a long initializer increase scanning effort. Action granularity: Most statements perform one clear action, although chained registration calls combine lookup and mutation. Reading flow: Consistent formatting and method grouping support navigation, but naming inconsistencies, unresolved references, and documentation that does not match signatures repeatedly interrupt comprehension.

Run 3

Code Structure: Related functionality is organized into a class with small methods and consistent registration patterns, although initialization is lengthy. Nesting: Mostly shallow, with limited decorator closures and one nested try/except. Clarity of intent: Type hints and detailed documentation help, but cryptic names such as static2, rou, f12, and get2 obscure meaning. Documentation references original names that no longer match the implementation, and undefined references such as options, rule, and endpoint make relationships difficult to follow. Code length: Executable methods are concise, but extensive, repetitive documentation substantially increases scanning effort. Action granularity: Generally one statement per line; chained registration operations remain understandable. Reading flow: Consistent formatting and logical method grouping support navigation, but renamed identifiers, mismatched property setters, and stale examples repeatedly interrupt comprehension.