Sample

pyint-2ad1a02601c8-I10

Deterministically remove some optional blank lines and bracketed line breaks

Matched original source

Lines146

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1220–1; higher is more readable
Mi0.4240–1; higher is more readable
LLOC78Logical lines; fewer is more readable
DeepSeek V4 Pro70–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.4360–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.146+58.4
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.507−6.76

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.147−4.168
Indentation frequencyHow rapidly indentation changes from line to line.113+3.171
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.140.966−2.306
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.113−2.172
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.145.824+1.629
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.140.993+1.47
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.33

Intercept 0.07 + feature contributions = -1.976 (log-odds).
Score = sigmoid(-1.976) = 0.122.

Score0.424
Score78
Run 1

The code suffers from inconsistent formatting and poor readability. Signatures are often split illogically across lines (e.g., 'open(', 'session_transaction('), with arguments scattered or misaligned. Several function calls have unusual spacing and line breaks, making them visually confusing. The `session_transaction` method is relatively clear, but the `open` method mixes builder handling, context management, and response setup in a way that is moderately tangled. Nesting is not deep, but action granularity is uneven — multiple operations are crammed into single lines in some spots. The lack of consistent indentation and alignment, combined with some overly long lines, disrupts natural reading flow. Intent is mostly understandable due to docstrings, but structural and formatting issues heavily undercut clarity.

Run 2

The code has a clear purpose as a Flask test client, but readability suffers from inconsistent formatting and poor indentation. Some function signatures and method calls are overly dense, with arguments laid out awkwardly. Vertical alignment is inconsistent, especially in methods like `session_transaction`, `open`, and `_update_cookies_from_response`. The nesting is moderate but occasionally tangled due to multiple conditionals and context managers. Docstrings are helpful but some are overly long, interfering with scanning. Several lines contain multiple actions, like constructor settings or cookie update calls. Overall structure is logical, but the formatting inconsistencies and unnecessarily verbose line breaks make the code harder to read than it should be.

Run 3

The code exhibits severe readability problems. There are multiple instances of methods with arguments split across several lines without alignment or indentation consistency, making signatures hard to parse. Unnecessary line breaks and spaces disrupt reading flow, e.g., `super().__init__(*args, **kwargs)` in `__init__`. Long method calls with arguments and closing parentheses aligned erratically further reduce clarity. Some methods are excessively long; `session_transaction` combines several actions and branches, violating action granularity. Deep indentation and nested `if` chains in `open()` complicate comprehension. The intent of certain constructs, such as `_new_contexts` and `preserve_context`, is not sufficiently documented. Type annotations exist but do not compensate for layout flaws. The code requires significant visual scanning to reconstruct logical structure, making it unfriendly to readers. No pervasive flatness or concise line discipline is evident, negatively affecting maintainability and review efficiency.

Run 1

Code Structure: Methods separate session management, request construction, environment copying, and context cleanup logically. Nesting: Mostly shallow, with manageable branching in open(). Clarity of intent: Descriptive method names, type annotations, docstrings, and context-management comments explain behavior well; types and helpers not defined in the snippet slightly reduce self-contained clarity. Code length: Reasonably concise for the functionality, although lengthy docstrings add reading overhead. Action granularity: Most lines perform one action, but a few chained calls and crowded argument lists require extra parsing. Reading flow: Execution generally follows a natural sequence, but irregular spacing, awkward line breaks, long lines, and missing blank lines between methods noticeably disrupt readability.

Run 2

Code Structure: Responsibilities are logically divided into focused methods, although missing blank lines weaken visual separation. Nesting: Mostly shallow, with manageable branching in open(). Clarity of intent: Descriptive method names, type hints, docstrings, and lifecycle comments explain behavior well; externally defined types and helpers require additional context. Code length: Generally appropriate for the functionality, though documentation is lengthy relative to some methods. Action granularity: Most lines perform one action, but compressed argument lists and a chained builder call make individual operations harder to scan. Reading flow: Execution follows a coherent request and context lifecycle, but irregular spacing, awkward line breaks, and crowded signatures noticeably interrupt readability.

Run 3

Code Structure: Responsibilities are logically separated into focused methods, though inconsistent spacing between methods weakens visual organization. Nesting: Mostly shallow, with manageable branching in open(). Clarity of intent: Descriptive names, type annotations, docstrings, and context-management comments explain behavior well; undefined names in the excerpt and a misleading 'request is None' comment introduce ambiguity. Code length: Implementation is reasonably concise, although lengthy docstrings and some long expressions increase reading effort. Action granularity: Most lines perform one action, with a few chained calls and crowded argument lists reducing clarity. Reading flow: Execution follows a natural sequence, but irregular indentation within signatures, excessive inline whitespace, awkward closing parentheses, and long lines repeatedly interrupt scanning.