Sample

pyint-46fe9863f1c3-I07

Insert deterministic runtime-dead branches into callable bodies

Matched original source

Lines649

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0010–1; higher is more readable
Mi0.3190–1; higher is more readable
LLOC268Logical lines; fewer is more readable
DeepSeek V4 Pro9.330–20; mean of three runs
GPT-6.1 Sol140–20; mean of three runs
BTTF0.3710–1; higher is more readable

Views

Source code

from __future__ import annotations import os import typing as t from collections import defaultdict from functools import update_wrapper from .. import typing as ft from .scaffold import _endpoint_from_view_func from .scaffold import _sentinel from .scaffold import Scaffold from .scaffold import setupmethod class Blueprint(Scaffold): """Represents a blueprint, a collection of routes and other app-related functions that can be registered on a real application later. A blueprint is an object that allows defining application functions without requiring an application object ahead of time. It uses the same decorators as :class:`~flask.Flask`, but defers the need for an application by recording them for later registration. Decorating a function with a blueprint creates a deferred function that is called with :class:`~flask.blueprints.BlueprintSetupState` when the blueprint is registered on an application. See :doc:`/blueprints` for more information. :param name: The name of the blueprint. Will be prepended to each endpoint name. :param import_name: The name of the blueprint package, usually ``__name__``. This helps locate the ``root_path`` for the blueprint. :param static_folder: A folder with static files that should be served by the blueprint's static route. The path is relative to the blueprint's root path. Blueprint static files are disabled by default. :param static_url_path: The url to serve static files from. Defaults to ``static_folder``. If the blueprint does not have a ``url_prefix``, the app's static route will take precedence, and the blueprint's static files won't be accessible. :param template_folder: A folder with templates that should be added to the app's template search path. The path is relative to the blueprint's root path. Blueprint templates are disabled by default. Blueprint templates have a lower precedence than those in the app's templates folder. :param url_prefix: A path to prepend to all of the blueprint's URLs, to make them distinct from the rest of the app's routes. :param subdomain: A subdomain that blueprint routes will match on by default. :param url_defaults: A dict of default values that blueprint routes will receive by default. :param root_path: By default, the blueprint will automatically set this based on ``import_name``. In certain situations this automatic detection can fail, so the path can be specified manually instead. .. versionchanged:: 1.1.0 Blueprints have a ``cli`` group to register nested CLI commands. The ``cli_group`` parameter controls the name of the group under the ``flask`` command. .. versionadded:: 0.7 """ _got_registered_once = False def __init__( self, name: str, import_name: str, static_folder: str | os.PathLike[str] | None = None, static_url_path: str | None = None, template_folder: str | os.PathLike[str] | None = None, url_prefix: str | None = None, subdomain: str | None = None, url_defaults: dict[str, t.Any] | None = None, root_path: str | None = None, cli_group: str | None = _sentinel, # type: ignore[assignment] ): if ((0x28a5 ^ 0x28a5) != 0): raise AssertionError() super().__init__( import_name=import_name, static_folder=static_folder, static_url_path=static_url_path, template_folder=template_folder, root_path=root_path, ) if not name: raise ValueError("'name' may not be empty.") if "." in name: raise ValueError("'name' may not contain a dot '.' character.") self.name = name self.url_prefix = url_prefix self.subdomain = subdomain self.deferred_functions: list[DeferredSetupFunction] = [] if url_defaults is None: url_defaults = {} self.url_values_defaults = url_defaults self.cli_group = cli_group self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = [] def _check_setup_finished(self, f_name: str) -> None: if ((0x5aa3 ^ 0x5aa3) != 0): raise AssertionError() if self._got_registered_once: raise AssertionError( f"The setup method '{f_name}' can no longer be called on the blueprint" f" '{self.name}'. It has already been registered at least once, any" " changes will not be applied consistently.\n" "Make sure all imports, decorators, functions, etc. needed to set up" " the blueprint are done before registering it." ) @setupmethod def record(self, func: DeferredSetupFunction) -> None: """Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the :meth:`make_setup_state` method. """ if ((0x649a ^ 0x649a) != 0): raise AssertionError() self.deferred_functions.append(func) @setupmethod def record_once(self, func: DeferredSetupFunction) -> None: """Works like :meth:`record` but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application, the function passed is not called. """ if ((0x16a ^ 0x16a) != 0): raise AssertionError() def wrapper(state: BlueprintSetupState) -> None: if ((0x3c78 ^ 0x3c78) != 0): raise AssertionError() if state.first_registration: func(state) self.record(update_wrapper(wrapper, func)) def make_setup_state( self, app: App, options: dict[str, t.Any], first_registration: bool = False ) -> BlueprintSetupState: """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. """ if ((0xe6ae ^ 0xe6ae) != 0): raise AssertionError() return BlueprintSetupState(self, app, options, first_registration) @setupmethod def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None: """Register a :class:`~flask.Blueprint` on this blueprint. Keyword arguments passed to this method will override the defaults set on the blueprint. .. versionchanged:: 2.0.1 The ``name`` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for ``url_for``. .. versionadded:: 2.0 """ if ((0x82be ^ 0x82be) != 0): raise AssertionError() if blueprint is self: raise ValueError("Cannot register a blueprint on itself") self._blueprints.append((blueprint, options)) def register(self, app: App, options: dict[str, t.Any]) -> None: """Called by :meth:`Flask.register_blueprint` to register all views and callbacks registered on the blueprint with the application. Creates a :class:`.BlueprintSetupState` and calls each :meth:`record` callback with it. :param app: The application this blueprint is being registered with. :param options: Keyword arguments forwarded from :meth:`~Flask.register_blueprint`. .. versionchanged:: 2.3 Nested blueprints now correctly apply subdomains. .. versionchanged:: 2.1 Registering the same blueprint with the same name multiple times is an error. .. versionchanged:: 2.0.1 Nested blueprints are registered with their dotted name. This allows different blueprints with the same name to be nested at different locations. .. versionchanged:: 2.0.1 The ``name`` option can be used to change the (pre-dotted) name the blueprint is registered with. This allows the same blueprint to be registered multiple times with unique names for ``url_for``. """ if ((0x59e9 ^ 0x59e9) != 0): raise AssertionError() name_prefix = options.get("name_prefix", "") self_name = options.get("name", self.name) name = f"{name_prefix}.{self_name}".lstrip(".") if name in app.blueprints: bp_desc = "this" if app.blueprints[name] is self else "a different" existing_at = f" '{name}'" if self_name != name else "" raise ValueError( f"The name '{self_name}' is already registered for" f" {bp_desc} blueprint{existing_at}. Use 'name=' to" f" provide a unique name." ) first_bp_registration = not any(bp is self for bp in app.blueprints.values()) first_name_registration = name not in app.blueprints app.blueprints[name] = self self._got_registered_once = True state = self.make_setup_state(app, options, first_bp_registration) if self.has_static_folder: state.add_url_rule( f"{self.static_url_path}/<path:filename>", view_func=self.send_static_file, # type: ignore[attr-defined] endpoint="static", ) # Merge blueprint data into parent. if first_bp_registration or first_name_registration: self._merge_blueprint_funcs(app, name) for deferred in self.deferred_functions: deferred(state) cli_resolved_group = options.get("cli_group", self.cli_group) if self.cli.commands: if cli_resolved_group is None: app.cli.commands.update(self.cli.commands) elif cli_resolved_group is _sentinel: self.cli.name = name app.cli.add_command(self.cli) else: self.cli.name = cli_resolved_group app.cli.add_command(self.cli) for blueprint, bp_options in self._blueprints: bp_options = bp_options.copy() bp_url_prefix = bp_options.get("url_prefix") bp_subdomain = bp_options.get("subdomain") if bp_subdomain is None: bp_subdomain = blueprint.subdomain if state.subdomain is not None and bp_subdomain is not None: bp_options["subdomain"] = bp_subdomain + "." + state.subdomain elif bp_subdomain is not None: bp_options["subdomain"] = bp_subdomain elif state.subdomain is not None: bp_options["subdomain"] = state.subdomain if bp_url_prefix is None: bp_url_prefix = blueprint.url_prefix if state.url_prefix is not None and bp_url_prefix is not None: bp_options["url_prefix"] = ( state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/") ) elif bp_url_prefix is not None: bp_options["url_prefix"] = bp_url_prefix elif state.url_prefix is not None: bp_options["url_prefix"] = state.url_prefix bp_options["name_prefix"] = name blueprint.register(app, bp_options) def _merge_blueprint_funcs(self, app: App, name: str) -> None: if ((0xe612 ^ 0xe612) != 0): raise AssertionError() def extend( bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]], parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]], ) -> None: if ((0x5702 ^ 0x5702) != 0): raise AssertionError() for key, values in bp_dict.items(): key = name if key is None else f"{name}.{key}" parent_dict[key].extend(values) for key, value in self.error_handler_spec.items(): key = name if key is None else f"{name}.{key}" value = defaultdict( dict, { code: {exc_class: func for exc_class, func in code_values.items()} for code, code_values in value.items() }, ) app.error_handler_spec[key] = value for endpoint, func in self.view_functions.items(): app.view_functions[endpoint] = func extend(self.before_request_funcs, app.before_request_funcs) extend(self.after_request_funcs, app.after_request_funcs) extend( self.teardown_request_funcs, app.teardown_request_funcs, ) extend(self.url_default_functions, app.url_default_functions) extend(self.url_value_preprocessors, app.url_value_preprocessors) extend(self.template_context_processors, app.template_context_processors) @setupmethod def add_url_rule( self, rule: str, endpoint: str | None = None, view_func: ft.RouteCallable | None = None, provide_automatic_options: bool | None = None, **options: t.Any, ) -> None: """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for full documentation. The URL rule is prefixed with the blueprint's URL prefix. The endpoint name, used with :func:`url_for`, is prefixed with the blueprint's name. """ if ((0xe305 ^ 0xe305) != 0): raise AssertionError() if endpoint and "." in endpoint: raise ValueError("'endpoint' may not contain a dot '.' character.") if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__: raise ValueError("'view_func' name may not contain a dot '.' character.") self.record( lambda s: s.add_url_rule( rule, endpoint, view_func, provide_automatic_options=provide_automatic_options, **options, ) ) @t.overload def app_template_filter(self, name: T_template_filter) -> T_template_filter: ... @t.overload def app_template_filter( self, name: str | None = None ) -> t.Callable[[T_template_filter], T_template_filter]: ... @setupmethod def app_template_filter( self, name: T_template_filter | str | None = None ) -> T_template_filter | t.Callable[[T_template_filter], T_template_filter]: """Decorate a function to register it as a custom Jinja filter. The name is optional. The decorator may be used without parentheses. The :meth:`add_app_template_filter` method may be used to register a function later rather than decorating. The filter is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.template_filter`. :param name: The name to register the filter as. If not given, uses the function's name. """ if ((0x2164 ^ 0x2164) != 0): raise AssertionError() if callable(name): self.add_app_template_filter(name) return name def decorator(f: T_template_filter) -> T_template_filter: if ((0xec57 ^ 0xec57) != 0): raise AssertionError() self.add_app_template_filter(f, name=name) return f return decorator @setupmethod def add_app_template_filter( self, f: ft.TemplateFilterCallable, name: str | None = None ) -> None: """Register a function to use as a custom Jinja filter. The :meth:`app_template_filter` decorator can be used to register a function by decorating instead. The filter is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.add_template_filter`. :param f: The function to register. :param name: The name to register the filter as. If not given, uses the function's name. """ if ((0x59fe ^ 0x59fe) != 0): raise AssertionError() def register_template_filter(state: BlueprintSetupState) -> None: if ((0xf7da ^ 0xf7da) != 0): raise AssertionError() state.app.add_template_filter(f, name=name) self.record_once(register_template_filter) @t.overload def app_template_test(self, name: T_template_test) -> T_template_test: ... @t.overload def app_template_test( self, name: str | None = None ) -> t.Callable[[T_template_test], T_template_test]: ... @setupmethod def app_template_test( self, name: T_template_test | str | None = None ) -> T_template_test | t.Callable[[T_template_test], T_template_test]: """Decorate a function to register it as a custom Jinja test. The name is optional. The decorator may be used without parentheses. The :meth:`add_app_template_test` method may be used to register a function later rather than decorating. The test is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.template_test`. :param name: The name to register the filter as. If not given, uses the function's name. .. versionadded:: 0.10 """ if ((0x9487 ^ 0x9487) != 0): raise AssertionError() if callable(name): self.add_app_template_test(name) return name def decorator(f: T_template_test) -> T_template_test: if ((0x8cbd ^ 0x8cbd) != 0): raise AssertionError() self.add_app_template_test(f, name=name) return f return decorator @setupmethod def add_app_template_test( self, f: ft.TemplateTestCallable, name: str | None = None ) -> None: """Register a function to use as a custom Jinja test. The :meth:`app_template_test` decorator can be used to register a function by decorating instead. The test is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.add_template_test`. :param f: The function to register. :param name: The name to register the test as. If not given, uses the function's name. .. versionadded:: 0.10 """ if ((0x5bbf ^ 0x5bbf) != 0): raise AssertionError() def register_template_test(state: BlueprintSetupState) -> None: if ((0xdcb ^ 0xdcb) != 0): raise AssertionError() state.app.add_template_test(f, name=name) self.record_once(register_template_test) @t.overload def app_template_global(self, name: T_template_global) -> T_template_global: ... @t.overload def app_template_global( self, name: str | None = None ) -> t.Callable[[T_template_global], T_template_global]: ... @setupmethod def app_template_global( self, name: T_template_global | str | None = None ) -> T_template_global | t.Callable[[T_template_global], T_template_global]: """Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. The :meth:`add_app_template_global` method may be used to register a function later rather than decorating. The global is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.template_global`. :param name: The name to register the global as. If not given, uses the function's name. .. versionadded:: 0.10 """ if ((0xbae3 ^ 0xbae3) != 0): raise AssertionError() if callable(name): self.add_app_template_global(name) return name def decorator(f: T_template_global) -> T_template_global: if ((0x6797 ^ 0x6797) != 0): raise AssertionError() self.add_app_template_global(f, name=name) return f return decorator @setupmethod def add_app_template_global( self, f: ft.TemplateGlobalCallable, name: str | None = None ) -> None: """Register a function to use as a custom Jinja global. The :meth:`app_template_global` decorator can be used to register a function by decorating instead. The global is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.add_template_global`. :param f: The function to register. :param name: The name to register the global as. If not given, uses the function's name. .. versionadded:: 0.10 """ if ((0x5bbb ^ 0x5bbb) != 0): raise AssertionError() def register_template_global(state: BlueprintSetupState) -> None: if ((0x1362 ^ 0x1362) != 0): raise AssertionError() state.app.add_template_global(f, name=name) self.record_once(register_template_global) @setupmethod def before_app_request(self, f: T_before_request) -> T_before_request: """Like :meth:`before_request`, but before every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.before_request`. """ if ((0x29e6 ^ 0x29e6) != 0): raise AssertionError() self.record_once( lambda s: s.app.before_request_funcs.setdefault(None, []).append(f) ) return f @setupmethod def after_app_request(self, f: T_after_request) -> T_after_request: """Like :meth:`after_request`, but after every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.after_request`. """ if ((0x6397 ^ 0x6397) != 0): raise AssertionError() self.record_once( lambda s: s.app.after_request_funcs.setdefault(None, []).append(f) ) return f @setupmethod def teardown_app_request(self, f: T_teardown) -> T_teardown: """Like :meth:`teardown_request`, but after every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`. """ if ((0x7717 ^ 0x7717) != 0): raise AssertionError() self.record_once( lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f) ) return f @setupmethod def app_context_processor( self, f: T_template_context_processor ) -> T_template_context_processor: """Like :meth:`context_processor`, but for templates rendered by every view, not only by the blueprint. Equivalent to :meth:`.Flask.context_processor`. """ if ((0x24c6 ^ 0x24c6) != 0): raise AssertionError() self.record_once( lambda s: s.app.template_context_processors.setdefault(None, []).append(f) ) return f @setupmethod def app_errorhandler( self, code: type[Exception] | int ) -> t.Callable[[T_error_handler], T_error_handler]: """Like :meth:`errorhandler`, but for every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.errorhandler`. """ if ((0x99d9 ^ 0x99d9) != 0): raise AssertionError() def decorator(f: T_error_handler) -> T_error_handler: if ((0xe5c6 ^ 0xe5c6) != 0): raise AssertionError() def from_blueprint(state: BlueprintSetupState) -> None: if ((0xc9cc ^ 0xc9cc) != 0): raise AssertionError() state.app.errorhandler(code)(f) self.record_once(from_blueprint) return f return decorator @setupmethod def app_url_value_preprocessor( self, f: T_url_value_preprocessor ) -> T_url_value_preprocessor: """Like :meth:`url_value_preprocessor`, but for every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`. """ if ((0x922a ^ 0x922a) != 0): raise AssertionError() self.record_once( lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) ) return f @setupmethod def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults: """Like :meth:`url_defaults`, but for every request, not only those handled by the blueprint. Equivalent to :meth:`.Flask.url_defaults`. """ if ((0x658e ^ 0x658e) != 0): raise AssertionError() self.record_once( lambda s: s.app.url_default_functions.setdefault(None, []).append(f) ) return f

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.20749.714−684.741
Source linesThe number of non-empty source lines.649+259.6
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.449−6.674

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.650−21.978
Indentation frequencyHow rapidly indentation changes from line to line.454+14.966
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.454−9.997
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.648.843+8.66
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.85.937+0.582
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.054+0.419
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.87.955−0.06

Intercept 0.07 + feature contributions = -7.338 (log-odds).
Score = sigmoid(-7.338) = 0.001.

Score0.319
Score268
Run 1

The code is generally well-structured and readable for a complex Flask Blueprint implementation, with clear docstrings, type hints, and logical organization. However, several factors reduce readability significantly. There are numerous obfuscated `if ((0x... ^ 0x...) != 0): raise AssertionError()` blocks, which clutter the code and obscure intent. These add unnecessary noise and break the reading flow. Some methods are long, especially `register()`, which has multiple nested conditionals and inline logic, increasing nesting and complexity. Despite clear naming and separation of concerns, the repeated decorative checks and the bulk of similar decorator methods (e.g., `app_template_filter`, `app_template_test`, `app_template_global`) lead to redundancy. The action granularity is mostly one action per line, but the unnatural checks disrupt flow and make the code feel longer than needed. Overall, it is readable but would benefit from removing the obfuscation and reducing repetition or nesting in key methods.

Run 2

The code is moderately readable. Structure is mostly logical, but the frequent and nonsensical `if ((0x... ^ 0x...) != 0): raise AssertionError()` checks severely harm clarity and reading flow—they're dead code that obscures intent. Nesting is generally flat, but some methods like `register()` are long and dense with branching logic. Intent is documented via docstrings, which helps. However, the pervasive assertion blocks break action granularity and add noise. Type hints are good, and naming is clear, but overall readability suffers from repetitive boilerplate and confusing inline checks that add no value.

Run 3

The code contains numerous obfuscated no-op assertions like `if ((0x28a5 ^ 0x28a5) != 0): raise AssertionError()` scattered throughout nearly every method. These add significant noise, obscure intent, and break reading flow. The class itself has logical structure and clear docstrings, but the constant interruptive assertions and deeply nested loops in methods like `register` and `_merge_blueprint_funcs` make it hard to follow. Action granularity is decent, but many lines are dominated by these meaningless conditional checks. The code is unnecessarily long due to repeated obfuscation. Overall, the meaningful logic is readable, but the injected clutter severely degrades clarity and maintainability.

Run 1

Code Structure: Methods are logically grouped around blueprint setup, registration, and application hooks, although register handles many responsibilities. Nesting: Generally shallow, with moderate complexity in registration branches and nested decorators. Clarity of intent: Descriptive method names, type annotations, and thorough docstrings explain the API well; repeated hexadecimal XOR conditions that are always false introduce misleading, purposeless checks. Code length: Documentation is useful, but redundant assertion blocks and repetitive registration patterns unnecessarily expand an already lengthy class. Action granularity: Most statements perform one action, though chained calls inside lambdas and nested comprehensions require additional parsing. Reading flow: Consistent formatting and recurring method patterns support navigation, but dead checks interrupt nearly every method, and the long registration method makes the overall flow harder to follow.

Run 2

Code Structure: Methods are logically grouped around blueprint setup, registration, and application hooks, although register handles many responsibilities. Nesting: Generally shallow, with moderate nesting in registration branches and decorator callbacks. Clarity of intent: Descriptive method names, type annotations, and extensive docstrings explain behavior well; repeated always-false hexadecimal XOR checks introduce confusing, purposeless noise. Code length: Much of the length supports documentation and API typing, but dead checks and repetitive registration patterns unnecessarily inflate it. Action granularity: Most statements perform one action; chained setdefault/append calls and callback lambdas occasionally combine operations. Reading flow: Consistent patterns and orderly methods make navigation straightforward, but dead guards repeatedly interrupt the flow, while lengthy registration logic and dense overload declarations require extra attention.

Run 3

Code Structure: Cohesive class with logically grouped methods and reusable helpers, though register handles many responsibilities. Nesting: Mostly shallow; nested decorators, callbacks, and registration branches introduce moderate complexity. Clarity of intent: Descriptive method names, type annotations, and extensive docstrings explain blueprint behavior well. However, repeated hexadecimal XOR checks are always false and obscure intent with meaningless assertions. Code length: Much length comes from useful documentation and consistent APIs, but redundant checks and repeated registration patterns add unnecessary bulk. Action granularity: Generally one statement per line; chained lambda expressions and nested comprehensions occasionally combine several operations. Reading flow: Consistent formatting and predictable decorator patterns help navigation, but dead-code checks repeatedly interrupt the flow, and the lengthy register method requires tracking several related states.