Sample

pyint-0e1e15d3a0cf-I12

Inline all eligible single-use intermediate local variables

Matched original source

Lines127

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4770–1; higher is more readable
Mi0.6550–1; higher is more readable
LLOC57Logical lines; fewer is more readable
DeepSeek V4 Pro170–20; mean of three runs
GPT-6.1 Sol180–20; mean of three runs
BTTF0.3870–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. 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" % ((int_to_base36(timestamp)), 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.2955.433−97.529
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.41−6.614

Intercept 8.87 + feature contributions = -44.474 (log-odds).
Score = sigmoid(-44.474) = 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.048+0.476
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.969+0.151

Intercept 0.07 + feature contributions = -0.091 (log-odds).
Score = sigmoid(-0.091) = 0.477.

Score0.655
Score57
Run 1

The code is well-structured, with clear separation of concerns via small, focused methods. Nesting is minimal; the deepest logic in check_token uses a try/except and a for/else, which is manageable. Intent is explicit through descriptive method names and docstrings, especially for token lifecycle logic. Code length is concise without sacrificing clarity. Action granularity is mostly one action per line, though some lines (e.g., hash_string slicing with inline comment) pack multiple operations. Reading flow is natural, with private helpers placed logically after their public callers. Minor readability drawbacks include the somewhat dense _make_hash_value return statement and the use of property definitions, but overall the code is highly readable.

Run 2

The code is generally well-structured and readable, with clear class and method organization, good use of properties, and concise helper methods. Nesting is mostly shallow, with only a few try/except blocks in check_token. The intent is mostly clear through naming and docstrings, though some methods like _make_hash_value are dense and could be broken down. Code length is reasonable, though the hash_string construction in _make_token_with_timestamp is somewhat hard to parse. Action granularity is mixed: most lines do one thing, but return statements with multiple chained calls are common. Reading flow is natural overall, but the check_token method breaks flow with early returns and a for-else loop that may confuse less experienced readers. The constant-time comparison and fallback secret loop are appropriate but could be refactored for clarity. Overall, the code is readable but benefits from Python familiarity.

Run 3

The code is highly readable, with clear class structure, logical method organization, and minimal nesting. Each method has a single responsibility and follows Django's conventions. Comments and docstrings clarify intent, especially for token generation and hash value composition. The use of properties and fallback logic is clear. A few spots, such as hash_string slicing and the loop with `for...else...`, may slow readers slightly, but overall flow is natural and maintainable. Concise, well-named, and fairly flat.

Run 1

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Shallow overall; guard clauses and early returns keep validation straightforward. Clarity of intent: Descriptive method names, docstrings, and explanatory comments communicate purpose well, though abbreviations such as ts and ts_b36 require interpretation. Code length: Reasonably concise for the functionality; lengthy documentation explains important behavior rather than adding unnecessary code. Action granularity: Most statements perform one clear action, although the chained HMAC conversion and slicing combine several operations. Reading flow: Validation progresses naturally from input checks through parsing, signature verification, and expiration. Minor friction comes from the less familiar for-else construct, property getter/setter boilerplate, and awkward multiline slicing.

Run 2

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Mostly flat, with early returns keeping validation straightforward; the loop with an else clause requires slightly more attention. Clarity of intent: Descriptive names, docstrings, and explanatory comments make the purpose clear, though abbreviated timestamp variables and implicit hash-field concatenation add minor ambiguity. Code length: Appropriately concise for the functionality; detailed documentation is useful rather than excessive. Action granularity: Most statements perform one clear action, although the chained HMAC calculation and slicing combine several operations. Reading flow: Validation proceeds naturally from parsing to verification to expiration checking. The unusually wrapped hexdigest slice, redundant parentheses in token formatting, and getter/setter property boilerplate slightly interrupt an otherwise clean flow.

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 readable; the for-else construct requires some Python familiarity. Clarity of intent: Descriptive method names, docstrings, and explanatory comments make the purpose clear, though abbreviated timestamp variables slightly reduce clarity. Code length: Mostly concise; property accessor boilerplate and the lengthy hashing docstring add length but serve useful purposes. Action granularity: Statements generally perform one action each, with a few compact chained expressions. Reading flow: Validation follows a natural sequence from input checks through parsing, signature verification, and expiration. The awkward multiline hexdigest slice and redundant parentheses in token formatting slightly interrupt an otherwise smooth flow.