Sample

pyint-ce8daa67b0cc-I02

Shorten method, parameter, and local names without collisions

Matched original source

Lines170

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.2510–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC78Logical lines; fewer is more readable
DeepSeek V4 Pro80–20; mean of three runs
GPT-6.1 Sol130–20; mean of three runs
BTTF0.4130–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, *arg: t.Any, **kwa: t.Any) -> None: super().__init__(*arg, **kwa) 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( self, *arg2: t.Any, **kwa2: 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'." ) app2 = self.application ctx2 = app2.test_request_context(*arg2, **kwa2) self._add_cookies_to_wsgi(ctx2.request.environ) with ctx2: ses = app2.session_interface.open_session(app2, ctx2.request) if ses is None: raise RuntimeError("Session backend did not open a session.") yield ses res = app2.response_class() if app2.session_interface.is_null_session(ses): return with ctx2: app2.session_interface.save_session(app2, ses, res) self._update_cookies_from_response( urlsplit(ctx2.request.host_url).hostname or "localhost", ctx2.request.path, res.headers.getlist("Set-Cookie"), ) def copy2(self, oth: WSGIEnvironment) -> WSGIEnvironment: out2 = {**self.environ_base, **oth} if self.preserve_context: out2["werkzeug.debug.preserve_context"] = self._new_contexts.append return out2 def request2( self, arg3: tuple[t.Any, ...], kwa3: dict[str, t.Any] ) -> BaseRequest: kwa3["environ_base"] = self.copy2(kwa3.get("environ_base", {})) bui = EnvironBuilder(self.application, *arg3, **kwa3) try: return bui.get_request() finally: bui.close() def ope( self, *arg4: t.Any, buf: bool = False, follow: bool = False, **kwa4: t.Any, ) -> TestResponse: if arg4 and isinstance( arg4[0], (werkzeug.test.EnvironBuilder, dict, BaseRequest) ): if isinstance(arg4[0], werkzeug.test.EnvironBuilder): bui2 = copy(arg4[0]) bui2.environ_base = self.copy2(bui2.environ_base or {}) # type: ignore[arg-type] req = bui2.get_request() elif isinstance(arg4[0], dict): req = EnvironBuilder.from_environ( arg4[0], app=self.application, environ_base=self.copy2({}) ).get_request() else: # isinstance(args[0], BaseRequest) req = copy(arg4[0]) req.environ = self.copy2(req.environ) else: # request is None req = self.request2(arg4, kwa4) # Pop any previously preserved contexts. This prevents contexts # from being preserved across redirects or multiple requests # within a single block. self._context_stack.close() res2 = super().open( req, buffered=buf, follow_redirects=follow, ) res2.json_module = self.application.json # type: ignore[assignment] # Re-push contexts that were preserved during the request. for cm2 in self._new_contexts: self._context_stack.enter_context(cm2) self._new_contexts.clear() return res2 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 | None, exc2: 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.5516.529−182.045
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.54−6.811

Intercept 8.87 + feature contributions = -111.986 (log-odds).
Score = sigmoid(-111.986) = 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.796+1.964
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.96.982+0.76
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.96.977−0.442
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.065+0.306

Intercept 0.07 + feature contributions = -1.094 (log-odds).
Score = sigmoid(-1.094) = 0.251.

Score0.425
Score78
Run 1

The code has some logical structure but suffers from poor clarity and readability issues. Variable names like 'arg2', 'kwa2', 'bui', 'ope', 'bui2', 'req', 'res2', 'cm2', 'exc2' are cryptic and make intent hard to follow. The method 'ope' is an abbreviation and does not describe its purpose. There is unnecessary numbering in names that should be descriptive. The nesting is moderate, but conditionals in 'ope' make flow harder to follow. Some lines contain multiple actions, reducing action granularity. The reading flow is uneven; comments help somewhat, but the poor naming and method structure undercut clarity. The code is also somewhat verbose in places, with repeated environment manipulation logic. While it leverages context managers and type hints, the naming choices and structural oddities make it significantly less readable.

Run 2

The code shows moderate structure with clear docstrings, but readability is severely harmed by cryptic variable names like `arg2`, `kwa3`, `arg4`, `kwa4`, `app2`, `ctx2`, `bui2`, `res2`, and `cm2`. These names obscure intent and make the code hard to follow. The `ope` and `request2` methods have confusing branching logic, and the original semantics are unclear due to the renaming. Nesting is generally acceptable (2-3 levels), but the multiple isinstance checks and copy operations create tangled flow. Action granularity is mixed; some lines perform multiple logical steps. The unnatural reading flow and pervasive placeholder-style names suggest the code was intentionally obfuscated, pulling the score down despite otherwise sound structural patterns like context managers and clear comments.

Run 3

The code suffers from poor readability due to ambiguous naming (e.g., 'arg2', 'kwa2', 'copy2', 'ope'), which obscures intent. The 'ope' method is overly long and handles multiple input types in deeply nested conditionals, violating single-responsibility and flat nesting principles. It mixes multiple actions per line in some cases and has a disorganized reading flow, jumping from argument handling to context management. While imports and class structure are logical and use type hints, the inconsistent and cryptic names, combined with poor action granularity and nesting, significantly reduce clarity.

Run 1

Code Structure: Methods logically separate session handling, environment preparation, request creation, and context management. Nesting: Mostly shallow, although ope contains a moderately nested type-dispatch branch. Clarity of intent: Type hints, documentation, and context-management comments help, but names such as ope, copy2, bui2, kwa3, and ses obscure purpose. The session docstring references session_transaction rather than the actual method name, and some comments use outdated identifiers. Code length: Generally proportionate to the functionality, with some lengthy documentation and repetitive argument handling. Action granularity: Statements mostly perform one action per line, with sensible multiline formatting for calls. Reading flow: Sequential setup, request execution, and cleanup are understandable, but inconsistent naming and undefined-in-snippet dependencies interrupt comprehension.

Run 2

Code Structure: Responsibilities are logically separated into session handling, environment preparation, request construction, and context management. Nesting: Mostly shallow, with moderate branching in ope. Clarity of intent: Type annotations, docstrings, and comments help, but cryptic names such as ope, copy2, bui, and kwa4 obscure purpose. The session docstring references session_transaction rather than the actual method name, and some comments retain outdated identifiers. Code length: Implementation is reasonably concise, though documentation occupies substantial space. Action granularity: Most lines perform one action; chained calls and dictionary unpacking remain manageable. Reading flow: Method organization and explicit cleanup provide a coherent sequence, but inconsistent naming, missing definitions for referenced types and helpers in this excerpt, and limited spacing between top-level sections interrupt readability.

Run 3

Code Structure: Responsibilities are logically separated into methods for sessions, request construction, and context management. Nesting: Mostly shallow, although ope contains a nested type-dispatch branch. Clarity of intent: Type hints, docstrings, and comments help, but names such as ope, copy2, bui, and kwa3 obscure purpose. The session docstring references session_transaction rather than the actual method name, and some comments reference different variable names. Code length: Implementation is reasonably concise, though documentation is lengthy relative to the methods. Action granularity: Statements generally perform one action per line, with a few dense expressions. Reading flow: Request preparation, execution, and cleanup follow a natural sequence, but inconsistent naming and annotation types not defined or imported in the excerpt interrupt comprehension.