Sample

pyint-642dfc3fca8e-I08

Select one of ten high-readability unrelated code templates per class

Matched original source

Lines174

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1860–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC82Logical lines; fewer is more readable
DeepSeek V4 Pro11.670–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.3750–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: even_number_count = 0 for candidate_number in range(6): if candidate_number % 2 == 0: even_number_count += 1 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.5651.172−186.489
Source linesThe number of non-empty source lines.174+69.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.512−6.768

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.175−5.16
Indentation frequencyHow rapidly indentation changes from line to line.140+4.105
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.140−2.792
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.173.777+2.019
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.977−1.035
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.971+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.477 (log-odds).
Score = sigmoid(-1.477) = 0.186.

Score0.425
Score82
Run 1

The code has clear structure in parts: imports organized, class definition with typed methods, docstrings on most methods. The __init__, session_transaction, _copy_environ, and _request_from_builder_args are reasonably flat and readable. However, the evaluation criteria show significant issues: the __exit__ method contains an unnecessary hardcoded even-number counting loop with no semantic connection to the class, adding unexplained dead code that harms clarity of intent and code length. The open() method has deeply nested conditional branching with type checks and fallback paths, plus inline comments used as control-flow labels, reducing reading flow. Action granularity varies: some lines mix type assertions or comments with logic. Overall, readability is harmed by tangled branching, dead code, and inconsistent granularity, despite decent structural organization.

Run 2

The code is generally structured with clear methods and docstrings, but has several readability problems. The `open()` method is long with confusing conditional branching for different request types. The `__exit__()` method contains an unnecessary loop that calculates `even_number_count` but never uses it, which is confusing and clearly a bug or leftover code. Some lines are long, such as the type-ignored builder line. Nesting is moderate but acceptable. Action granularity is mostly one action per line. The reading flow is disrupted by the dead code and complex conditionals. Intent is reasonably clear in docstrings, but implementation details lower clarity.

Run 3

The code demonstrates clear structure with logical grouping and consistent naming. It is concise for the most part, avoids deep nesting, and each action generally maps to one line. However, an unused variable (`even_number_count`) in `__exit__` appears unrelated to surrounding logic, which slightly obscures intent. The `open` method has a multi-condition branch that requires careful reading but remains manageable, and the use of comments to clarify branches is helpful. Overall, the code is readable with minor improvements needed.

Run 1

Code Structure: Well-separated methods organize session handling, request construction, and context management, but the unrelated counting loop in __exit__ undermines cohesion. Nesting: Mostly shallow, with moderate branching in open and an unnecessary nested loop/condition in __exit__. Clarity of intent: Descriptive method names, type annotations, docstrings, and context-management comments explain most behavior; unused counting logic and externally undefined names reduce standalone clarity. Code length: Generally appropriate for the functionality, although extensive documentation and irrelevant counting code add length. Action granularity: Most lines perform one action; a few chained calls and long expressions are denser. Reading flow: Initialization, helpers, request execution, and lifecycle methods follow a natural progression, but specialized context bookkeeping requires careful reading, and the misleading 'request is None' comment interrupts understanding.

Run 2

Code Structure: Methods logically separate session management, request construction, and context cleanup, though __exit__ contains an unrelated counting loop. Nesting: Mostly shallow, with moderate branching in open and unnecessary nesting in the counting loop. Clarity of intent: Descriptive names, type annotations, docstrings, and context-management comments explain most behavior; the unused counter and misleading 'request is None' comment introduce ambiguity. Code length: Generally appropriate for the functionality, but lengthy documentation and dead counting code add bulk. Action granularity: Statements generally perform one action per line, making state changes easy to follow. Reading flow: Method boundaries and sequential operations support natural reading, although dense expressions, a long inline type-ignore comment, and types not defined or imported in this snippet interrupt comprehension.

Run 3

Code Structure: Methods logically separate session handling, request construction, and context management, but the unused even-number counting loop in __exit__ is unrelated clutter. Nesting: Mostly shallow, with moderate branching in open and unnecessary nesting in __exit__. Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments explain most behavior; abbreviated variables and externally defined types require some context. Code length: Generally appropriate, though lengthy documentation, unused imports, and the irrelevant loop add bulk. Action granularity: Statements generally perform one action per line, with a few dense builder expressions and a long assignment reducing scanability. Reading flow: Request preparation, execution, and cleanup follow a natural sequence, but the stray loop and misleading 'request is None' comment interrupt that flow.