Sample

pyint-da1aaece1c56-I13

Lower every eligible synchronous for loop to a while loop

Matched original source

Lines127

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4780–1; higher is more readable
Mi0.6550–1; higher is more readable
LLOC58Logical lines; fewer is more readable
DeepSeek V4 Pro17.330–20; mean of three runs
GPT-6.1 Sol180–20; mean of three runs
BTTF0.3950–1; higher is more readable

Views

Source code

from datetime import datetime from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mechanism. """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" algorithm = None _secret = None _secret_fallbacks = None def __init__(self): self.algorithm = self.algorithm or "sha256" def _get_secret(self): return self._secret or settings.SECRET_KEY def _set_secret(self, secret): self._secret = secret secret = property(_get_secret, _set_secret) def _get_fallbacks(self): if self._secret_fallbacks is None: return settings.SECRET_KEY_FALLBACKS return self._secret_fallbacks def _set_fallbacks(self, fallbacks): self._secret_fallbacks = fallbacks secret_fallbacks = property(_get_fallbacks, _set_fallbacks) def make_token(self, user): """ Return a token that can be used once to do a password reset for the given user. """ return self._make_token_with_timestamp( user, self._num_seconds(self._now()), self.secret, ) def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with for secret in [self.secret, *self.secret_fallbacks]: if constant_time_compare( self._make_token_with_timestamp(user, ts, secret), token, ): break else: return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True def _make_token_with_timestamp(self, user, timestamp, secret): # timestamp is number of seconds since 2001-1-1. Converted to base 36, # this gives us a 6 digit string until about 2069. ts_b36 = int_to_base36(timestamp) hash_string = salted_hmac( self.key_salt, self._make_hash_value(user, timestamp), secret=secret, algorithm=self.algorithm, ).hexdigest()[ ::2 ] # Limit to shorten the URL. return "%s-%s" % (ts_b36, hash_string) def _make_hash_value(self, user, timestamp): """ Hash the user's primary key, email (if available), and some user state that's sure to change after a password reset to produce a token that is invalidated when it's used: 1. The password field will change upon a password reset (even if the same password is chosen, due to password salting). 2. The last_login field will usually be updated very shortly after a password reset. Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually invalidates the token. Running this data through salted_hmac() prevents password cracking attempts using the reset token, provided the secret isn't compromised. """ # Truncate microseconds so that tokens are consistent even if the # database doesn't support microseconds. login_timestamp = ( "" if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) ) email_field = user.get_email_field_name() email = getattr(user, email_field, "") or "" return f"{user.pk}{user.password}{login_timestamp}{timestamp}{email}" def _num_seconds(self, dt): return int((dt - datetime(2001, 1, 1)).total_seconds()) def _now(self): # Used for mocking in tests return datetime.now()

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.2962.12−97.75
Source linesThe number of non-empty source lines.127+50.8
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.414−6.62

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.128−3.496
Indentation frequencyHow rapidly indentation changes from line to line.97+2.618
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.97−1.805
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.126.786+1.362
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.82.852+0.532
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.047+0.481
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.82.984+0.15

Intercept 0.07 + feature contributions = -0.087 (log-odds).
Score = sigmoid(-0.087) = 0.478.

Score0.655
Score58
Run 1

This code demonstrates excellent readability through clear organization, minimal nesting, and logical structure. The class has a clear single responsibility around token generation/verification. Methods are concise and well-named, making intent obvious. Nesting is minimal - the deepest nesting occurs in check_token with try/except blocks and loops, but it's handled cleanly with early returns. Code length is appropriate for the functionality provided. Action granularity is good with one main operation per line, though a few lines like the salted_hmac call chain could be broken up. Reading flow is natural - make_token flows to _make_token_with_timestamp, check_token validates logically step-by-step. Comments explain non-obvious security decisions without being excessive. The use of properties for secret management and clear separation of time-related helper methods contribute to overall maintainability.

Run 2

The code is highly readable with clear logical organization into small, single-purpose methods. Nesting is minimal and well-controlled, especially in check_token where early returns avoid deep indentation. Comments effectively explain non-obvious decisions (e.g., timestamp base, hash truncation, hash value rationale). Action granularity is appropriate—most lines perform one operation. Naming is descriptive and imports are clean. Minor deductions: the else clause on the for loop in check_token is slightly uncommon and could reduce clarity for some readers, and the inline comment on the hash slice truncation slightly interrupts flow, but these are negligible. Overall, the code follows strong Python conventions and demonstrates clear intent throughout.

Run 3

The code is generally readable and well-structured. It uses clear class organization, descriptive method names, and helpful comments explaining non-obvious logic (e.g., token invalidation reasoning). Nesting is shallow, and actions are mostly one per line. However, the `check_token` method has a somewhat non-obvious `for...else` construct and a try/except for token parsing that slightly interrupts flow. Some logic, like `self.algorithm = self.algorithm or 'sha256'`, and the inline hexdigest slicing, could be clearer. Overall, the code is maintainable and understandable for a Django contributor, but minor clarity improvements would help.

Run 1

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Shallow overall; early returns keep validation flat, though the for-else construct requires some familiarity. Clarity of intent: Descriptive method names, docstrings, and comments explain both purpose and security rationale; abbreviated timestamp variables are slightly less explicit. Code length: Mostly concise and justified, with a lengthy but useful hashing docstring and some property boilerplate. Action granularity: Most statements perform one clear action; the chained HMAC, hexadecimal conversion, and slicing expression combines several operations. Reading flow: Validation follows a natural parse, verify, and expiration-check sequence. The awkward multiline slice formatting interrupts an otherwise smooth reading experience.

Run 2

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Shallow overall; early returns keep validation flat, although the for-else construct requires some familiarity. Clarity of intent: Descriptive names, docstrings, and security-related comments explain both purpose and implementation choices. Code length: Appropriately concise for the functionality; lengthy documentation adds useful context rather than unnecessary code. Action granularity: Most statements perform one clear action, though the chained HMAC call and sliced digest combine several operations. Reading flow: Validation proceeds naturally from parsing through verification to expiration checking. Minor distractions include the awkward multiline digest slice, indirect property definitions, and abbreviated timestamp variables.

Run 3

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Shallow control flow and early returns keep validation easy to follow. Clarity of intent: Descriptive names, docstrings, and comments explain both purpose and security-related decisions; abbreviated timestamp variables and the less-common for-else construct require some attention. Code length: Appropriately concise for the functionality, although property boilerplate and the lengthy hashing docstring add reading overhead. Action granularity: Most statements perform one clear action; the chained HMAC call and unusually split hexadecimal slicing are slightly harder to scan. Reading flow: Validation progresses naturally from parsing to signature checking to expiration, and helper methods support that sequence. Overall, highly readable with minor formatting and idiom-related friction.