Sample

pyint-a746c7ff54c4-I13

Lower every eligible synchronous for loop to a while loop

Matched original source

Lines120

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4730–1; higher is more readable
Mi0.3570–1; higher is more readable
LLOC53Logical lines; fewer is more readable
DeepSeek V4 Pro11.670–20; mean of three runs
GPT-6.1 Sol15.330–20; mean of three runs
BTTF0.4810–1; higher is more readable

Views

Source code

import re from urllib.parse import urlsplit from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.mail import MailerDoesNotExist, mail_managers, mailers from django.http import HttpResponsePermanentRedirect from django.middleware import MiddlewareMixin from django.urls import is_valid_path from django.utils.http import escape_leading_slashes class CommonMiddleware(MiddlewareMixin): """ "Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, form a new URL by appending a slash at the end. If this new URL is found in urlpatterns, return an HTTP redirect to this new URL; otherwise process the initial URL as usual. This behavior can be customized by subclassing CommonMiddleware and overriding the response_redirect_class attribute. """ response_redirect_class = HttpResponsePermanentRedirect def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get("HTTP_USER_AGENT") if user_agent is not None: loopIterator = __import__("builtins").iter(settings.DISALLOWED_USER_AGENTS) while True: try: user_agent_regex = __import__("builtins").next(loopIterator) except __import__("builtins").StopIteration: break if user_agent_regex.search(user_agent): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() if settings.PREPEND_WWW and host and not host.startswith("www."): # Check if we also need to append a slash so we can do it all # with a single redirect. (This check may be somewhat expensive, # so we only do it if we already know we're sending a redirect, # or in process_response if we get a 404.) if self.should_redirect_with_slash(request): path = self.get_full_path_with_slash(request) else: path = request.get_full_path() return self.response_redirect_class(f"{request.scheme}://www.{host}{path}") def should_redirect_with_slash(self, request): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not request.path_info.endswith("/"): urlconf = getattr(request, "urlconf", None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path("%s/" % request.path_info, urlconf) if match: view = match.func return getattr(view, "should_append_slash", True) return False def get_full_path_with_slash(self, request): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is DELETE, POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.method in ("DELETE", "POST", "PUT", "PATCH"): raise RuntimeError( "You called this URL via %(method)s, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { "method": request.method, "url": request.get_host() + new_path, } ) return new_path def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if response.status_code == 404 and self.should_redirect_with_slash(request): response = self.response_redirect_class( self.get_full_path_with_slash(request) ) # Add the Content-Length header to non-streaming responses if not # already set. if not response.streaming and not response.has_header("Content-Length"): response.headers["Content-Length"] = str(len(response.content)) return response

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.2935.248−96.863
Source linesThe number of non-empty source lines.120+48
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.492−6.739

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.121−3.248
Indentation frequencyHow rapidly indentation changes from line to line.79+1.995
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.79−1.392
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.119.898+1.266
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.033+0.621
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.909+0.598
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.86.992−0.019

Intercept 0.07 + feature contributions = -0.109 (log-odds).
Score = sigmoid(-0.109) = 0.473.

Score0.357
Score53
Run 1

The code is generally clear with good structure, documentation, and method separation. However, the process_request method contains unnecessarily convoluted loop logic using __import__('builtins') and manual iteration instead of a simple for loop, which severely hurts readability. This is why the score is significantly reduced. Other issues include long lines in some places, inconsistent nesting levels, and the should_redirect_with_slash method having moderate complexity. The comments are helpful for context but don't fully compensate for the confusing User-Agent filtering implementation.

Run 2

The code is generally well-structured with clear method separation and docstrings, but several issues reduce readability. The most significant problem is in process_request: the user-agent check uses a convoluted while loop with __import__('builtins') instead of a simple for loop over settings.DISALLOWED_USER_AGENTS, making the code unnecessarily complex and hard to follow. This breaks the 'action granularity' and 'clarity of intent' criteria by obscuring simple iteration logic. The method also produces 'multiple actions per line' in some spots, though most formatting is clean. The URL rewriting logic is clear and well-commented, with good method decomposition (should_redirect_with_slash, get_full_path_with_slash). Nesting is shallow and readable. However, the user-agent loop and the use of dynamic __import__ calls disrupt natural reading flow and introduce unnecessary complexity. Overall, the code has good structure but the unnatural loop construction and some verbose elements prevent higher readability.

Run 3

The code structure is logical with clear docstrings, but the 'process_request' method uses a bizarre loop construct with __import__('builtins') that is unnecessarily convoluted. It could simply iterate over settings.DISALLOWED_USER_AGENTS with a for loop. The nesting is moderate but acceptable. Clarity of intent is generally good, especially in the docstrings and method names, but the unnatural loop undermines it. Code length is reasonable, though the loop adds unnecessary verbosity. Action granularity is mostly fine, but the loop disrupts the natural reading flow. The import statements and overall organization follow Django conventions, but the loop is a major readability flaw.

Run 1

Code Structure: Well organized into focused middleware methods, though several unused imports add clutter. Nesting: Mostly manageable, but URL validation and user-agent checking contain multiple nested levels. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior clearly; dynamic builtins imports and the name loopIterator obscure an otherwise simple iteration. Code length: Generally appropriate, but the manual iterator/while/try-except sequence is unnecessarily verbose compared with a for loop. Action granularity: Statements generally perform one clear action per line, with readable formatting for longer expressions. Reading flow: Request handling, redirect helpers, and response handling follow a logical sequence, but the unconventional iteration interrupts the otherwise natural Python style.

Run 2

Code Structure: Well-organized middleware methods separate request checks, redirect decisions, path construction, and response handling; unused imports add clutter. Nesting: Mostly moderate, but the user-agent loop and slash-validation logic have several nested levels. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well; repeated dynamic builtins imports and the generic loopIterator name obscure a simple iteration. Code length: Generally appropriate, though manual iterator handling is unnecessarily verbose compared with a for loop. Action granularity: Most lines perform one clear action, but dynamic imports embedded in iteration and exception handling complicate individual expressions. Reading flow: Methods follow a natural request-to-response progression, with useful contextual comments; the unconventional while/try/except loop interrupts otherwise idiomatic Python.

Run 3

Code Structure: Well-organized middleware with separate methods for request checks, slash handling, and response processing; unused imports add clutter. Nesting: Mostly manageable, but user-agent iteration and slash validation introduce several nested levels. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior clearly; repeated dynamic builtins imports and the generic loopIterator name obscure a simple iteration. Code length: Generally justified, but manually implementing iteration with while/try/except is unnecessarily verbose compared with a for loop. Action granularity: Most lines perform one action, although dynamic import expressions combine lookup and execution awkwardly. Reading flow: Methods follow a natural request-to-response progression, but the nonidiomatic iterator block interrupts otherwise straightforward Python.