Sample

pyint-8f56cb9de94d-I13

Lower every eligible synchronous for loop to a while loop

Matched original source

Lines175

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1830–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC82Logical lines; fewer is more readable
DeepSeek V4 Pro140–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.4190–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. loopIterator = __import__("builtins").iter(self._new_contexts) while True: try: cm = __import__("builtins").next(loopIterator) except __import__("builtins").StopIteration: break 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.5710.784−188.456
Source linesThe number of non-empty source lines.175+70
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.509−6.764

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.176−5.195
Indentation frequencyHow rapidly indentation changes from line to line.141+4.14
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.141−2.815
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.174.777+2.033
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.111−1.036
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.989+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.064+0.322

Intercept 0.07 + feature contributions = -1.495 (log-odds).
Score = sigmoid(-1.495) = 0.183.

Score0.425
Score82
Run 1

The code is generally well-structured with clean imports and appropriate type hints, scoring well on structure (15) and clarity of intent (16). However, there is a notable inconsistency in the `open` method where `loopIterator` uses dynamic builtins imports (`__import__('builtins')`) instead of a normal `for` loop, which hurts readability and intent. Nesting is moderate. Code length is somewhat long for the class scope, and action granularity is mostly one action per line, which is good. The reading flow is natural, but the awkward loop construct breaks flow and reduces the score.

Run 2

The code is generally readable but has some issues. Structure is adequate with clear class organization and docstrings, but the `open` method has an awkward manual iterator pattern (`__import__('builtins')` instead of a simple `for` loop or `while` with direct calls) that hurts clarity. Nesting is mostly acceptable, though the `open` method has multiple conditional branches that are somewhat deep. Intent is mostly clear due to docstrings and naming, but the iterator section is confusing. Code length is reasonable for the functionality, though some methods are long. Action granularity is mostly one action per line, but some lines combine multiple operations. Reading flow is natural in most methods, but the `open` method's context preservation logic disrupts it. The manual iterator and `__import__` calls are particularly problematic - they obscure intent and are unnecessarily verbose. Overall, it's maintainable but has localized readability problems that prevent a higher score.

Run 3

The code is generally readable with clear structure and docstrings, but some parts reduce clarity. Imports and type hints are well organized, and methods are logically grouped. However, the `open` method contains multiple nested conditionals and a convoluted manual iterator loop using `__import__('builtins')`, which is unnecessarily complex and harms readability. Some methods have clear intent and reasonable length, but `open` mixes several actions (request building, context management, response processing) and lacks separation of concerns. Nesting is moderate, but the `open` method would benefit from refactoring into helper methods. Action granularity is mostly one action per line, though a few lines combine multiple operations. Overall, the code is understandable but not maximally readable due to the awkward iterator logic and branching in `open`.

Run 1

Code Structure: Methods separate session handling, environment copying, request construction, and context management logically. Nesting: Mostly shallow, although open() contains nested type dispatch and an unnecessarily elaborate iteration loop. Clarity of intent: Descriptive method names, annotations, docstrings, and comments explain most behavior; abbreviated variables and references not defined in the snippet require external context. Code length: Generally appropriate, but repeated dynamic imports and manual iterator handling could be replaced by a simple for loop. Action granularity: Most lines perform one clear action, with a few chained calls and a long assignment reducing scanability. Reading flow: Lifecycle operations follow a coherent sequence, but the unusual loopIterator naming and __import__("builtins") calls interrupt otherwise idiomatic Python. Overall, readable and well organized with a conspicuous localized readability problem.

Run 2

Code Structure: Well-organized class with focused methods separating session handling, request construction, and context management. Nesting: Mostly shallow, though open() contains nested type-dispatch branches and an unnecessary while/try/except loop. Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments clarify behavior; dynamic builtins imports, loopIterator naming, and the misleading 'request is None' comment reduce clarity. Code length: Generally appropriate, but explicit iterator management is needlessly verbose compared with a for loop. Action granularity: Statements generally perform one action per line, with a few dense expressions and long lines. Reading flow: Methods follow a logical sequence, and guard clauses simplify execution paths. However, the unusual context iteration interrupts otherwise idiomatic Python, and referenced types or helpers not defined in the snippet limit standalone understanding.

Run 3

Code Structure: Responsibilities are logically separated into focused methods, with helpers for environment copying and request creation. Nesting: Generally shallow, although open() combines conditional branching with an unnecessarily nested iteration loop. Clarity of intent: Descriptive method names, type annotations, docstrings, and context-management comments clarify behavior; abbreviated variables and unexplained dynamic builtins imports reduce clarity. Code length: Most implementation is appropriately concise, but the manual iterator/while/try/except sequence should be a simple for loop. Action granularity: Statements generally perform one action per line, with only a few dense expressions. Reading flow: Request creation, context cleanup, execution, and restoration follow a natural sequence. However, the unusual loopIterator naming, repeated __import__ calls, misleading 'request is None' comment, and types or helpers not defined in the excerpt interrupt comprehension.