Sample

pyint-87ef585fba40-I12

Inline all eligible single-use intermediate local variables

Matched original source

Lines170

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1920–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC78Logical lines; fewer is more readable
DeepSeek V4 Pro15.330–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.4750–1; higher is more readable

Views

Source code

from __future__ import annotations import importlib.metadata import typing as t from contextlib import contextmanager from contextlib import ExitStack from copy import copy from types import TracebackType from urllib.parse import urlsplit import werkzeug.test from click.testing import CliRunner from click.testing import Result from werkzeug.test import Client from werkzeug.wrappers import Request as BaseRequest from .cli import ScriptInfo from .sessions import SessionMixin class FlaskClient(Client): """Works like a regular Werkzeug test client, with additional behavior for Flask. Can defer the cleanup of the request context until the end of a ``with`` block. For general information about how to use this class refer to :class:`werkzeug.test.Client`. .. versionchanged:: 0.12 `app.test_client()` includes preset default environment, which can be set after instantiation of the `app.test_client()` object in `client.environ_base`. Basic usage is outlined in the :doc:`/testing` chapter. """ application: Flask def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: super().__init__(*args, **kwargs) self.preserve_context = False self._new_contexts: list[t.ContextManager[t.Any]] = [] self._context_stack = ExitStack() self.environ_base = { "REMOTE_ADDR": "127.0.0.1", "HTTP_USER_AGENT": f"Werkzeug/{_get_werkzeug_version()}", } @contextmanager def session_transaction( self, *args: t.Any, **kwargs: t.Any ) -> t.Iterator[SessionMixin]: """When used in combination with a ``with`` statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the ``with`` block is left the session is stored back. :: with client.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as :meth:`~flask.Flask.test_request_context` which are directly passed through. """ if self._cookies is None: raise TypeError( "Cookies are disabled. Create a client with 'use_cookies=True'." ) app = self.application ctx = app.test_request_context(*args, **kwargs) self._add_cookies_to_wsgi(ctx.request.environ) with ctx: sess = app.session_interface.open_session(app, ctx.request) if sess is None: raise RuntimeError("Session backend did not open a session.") yield sess resp = app.response_class() if app.session_interface.is_null_session(sess): return with ctx: app.session_interface.save_session(app, sess, resp) self._update_cookies_from_response( urlsplit(ctx.request.host_url).hostname or "localhost", ctx.request.path, resp.headers.getlist("Set-Cookie"), ) def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment: out = {**self.environ_base, **other} if self.preserve_context: out["werkzeug.debug.preserve_context"] = self._new_contexts.append return out def _request_from_builder_args( self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any] ) -> BaseRequest: kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {})) builder = EnvironBuilder(self.application, *args, **kwargs) try: return builder.get_request() finally: builder.close() def open( self, *args: t.Any, buffered: bool = False, follow_redirects: bool = False, **kwargs: t.Any, ) -> TestResponse: if args and isinstance( args[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest) ): if isinstance(args[0], werkzeug.test.EnvironBuilder): builder = copy(args[0]) builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type] request = builder.get_request() elif isinstance(args[0], dict): request = EnvironBuilder.from_environ( args[0], app=self.application, environ_base=self._copy_environ({}) ).get_request() else: # isinstance(args[0], BaseRequest) request = copy(args[0]) request.environ = self._copy_environ(request.environ) else: # request is None request = self._request_from_builder_args(args, kwargs) # Pop any previously preserved contexts. This prevents contexts # from being preserved across redirects or multiple requests # within a single block. self._context_stack.close() response = super().open( request, buffered=buffered, follow_redirects=follow_redirects, ) response.json_module = self.application.json # type: ignore[assignment] # Re-push contexts that were preserved during the request. for cm in self._new_contexts: self._context_stack.enter_context(cm) self._new_contexts.clear() return response def __enter__(self) -> FlaskClient: if self.preserve_context: raise RuntimeError("Cannot nest client invocations") self.preserve_context = True return self def __exit__( self, exc_type: type | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.preserve_context = False self._context_stack.close()

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.5435.556−179.373
Source linesThe number of non-empty source lines.170+68
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.515−6.773

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.171−5.018
Indentation frequencyHow rapidly indentation changes from line to line.136+3.967
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.136−2.7
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.169.777+1.963
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.110.988−1.036
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.959+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.329

Intercept 0.07 + feature contributions = -1.439 (log-odds).
Score = sigmoid(-1.439) = 0.192.

Score0.425
Score78
Run 1

The code is moderately readable but suffers from several issues that prevent a higher score. The class structure is logical and methods are well-documented, but `open()` contains complex branching logic with multiple nested `isinstance` checks that disrupt reading flow. Nesting is most severe in `session_transaction()` where context managers, conditionals, and method calls are deeply layered. Action granularity varies - most lines contain single actions, but the `_copy_environ` method crams multiple operations into one line with method chaining and nested calls. The intent is generally clear from method names and docstrings, but some sections like the `if args and isinstance(...)` block create cognitive overhead. Code length is appropriate for the functionality, though the comments describing `isinstance` checks add noise rather than clarity. The reading flow is natural in most methods but breaks down in `open()` where the conditional branches create disjointed logic that requires careful tracking of request construction paths.

Run 2

The code is generally well-structured with clear method separation and appropriate docstrings. Key methods like `open`, `session_transaction`, and context management are readable, using flat conditional checks rather than deep nesting. Type hints improve clarity. The `open` method handles multiple input types with readable if/elif branches, though it is somewhat long. The `session_transaction` method is also understandable but could be broken into smaller helpers, slightly lowering action granularity. Comments explaining branch intent (“request is None”) help comprehension. Overall, the code maintains good readability with minor verbosity in a few methods.

Run 3

The code is generally readable with clear intent and logical structure. Class methods are well-organized, type hints improve clarity, and docstrings explain complex behavior. The main readability drawback is the open() method, which has multiple branching conditions and mixed responsibilities (building requests, managing context stacks, delegating to super), increasing cognitive load. session_transaction() also has multiple early exits and steps, but its linear flow mitigates confusion. Nesting is moderate but acceptable. Action granularity is mostly one action per line. Reading flow is natural for most methods, except open(), which jumps between conditional branches and context cleanup logic. Overall, it is understandable for someone familiar with Flask internals, but the open() method could be refactored into smaller helpers to improve separation of concerns and reduce branch complexity.

Run 1

Code Structure: Well-organized class with focused methods separating session handling, request construction, and context management. Nesting: Mostly shallow, although open() has nested type-dependent branches that slightly increase reading effort. Clarity of intent: Descriptive method names, annotations, docstrings, and lifecycle comments explain most behavior; abbreviated variables and externally defined types/helpers require some context. Code length: Generally proportionate to functionality, though extensive documentation and repeated request-construction paths add length. Action granularity: Statements typically perform one action per line, with a few chained calls and a long assignment reducing scanability. Reading flow: Methods follow coherent sequences, supported by guard clauses and explicit cleanup; context preservation and session lifecycle transitions demand careful attention, and the 'request is None' comment is misleading.

Run 2

Code Structure: Cohesive class organization and focused helper methods separate request construction, session handling, and context management. Nesting: Mostly shallow, although open() contains a moderately nested type-dispatch branch. Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments explain most behavior; abbreviated variables and types not defined or imported in the snippet add some ambiguity. Code length: Generally proportionate to the functionality, but lengthy documentation, unused imports, and a redundant comment slightly reduce concision. Action granularity: Statements generally perform one action per line, with a few dense expressions and chained calls. Reading flow: Methods follow a natural initialization-to-operation-to-cleanup progression, though framework-specific context preservation and session mechanics require careful reading.

Run 3

Code Structure: Well-organized class with focused methods separating session handling, environment preparation, request construction, and context management. Nesting: Generally shallow, though open() contains a moderately nested type-dispatch branch. Clarity of intent: Descriptive method names, type annotations, docstrings, and context-lifecycle comments make most behavior clear; abbreviated variables and externally defined symbols slightly reduce standalone clarity. Code length: Appropriate for the functionality, although documentation is lengthy and some request-building expressions are dense. Action granularity: Statements generally perform one action per line, with a few chained calls and long assignments requiring extra attention. Reading flow: Methods follow coherent sequences, and guard clauses simplify control flow. Minor distractions include the misleading 'request is None' comment, long type-ignore lines, and imports unused within the provided snippet.