Sample

pyint-295a13937749-I12

Inline all eligible single-use intermediate local variables

Matched original source

Lines235

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1580–1; higher is more readable
Mi0.3350–1; higher is more readable
LLOC97Logical lines; fewer is more readable
DeepSeek V4 Pro160–20; mean of three runs
GPT-6.1 Sol16.330–20; mean of three runs
BTTF0.4320–1; higher is more readable

Views

Source code

from django.conf import settings from django.contrib import admin, messages from django.contrib.admin.options import IS_POPUP_VAR from django.contrib.admin.utils import unquote from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import ( AdminPasswordChangeForm, AdminUserCreationForm, UserChangeForm, ) from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import escape from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = "admin/auth/user/add_form.html" change_user_password_template = None fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("first_name", "last_name", "email")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", "usable_password", "password1", "password2"), }, ), ) form = UserChangeForm add_form = AdminUserCreationForm change_password_form = AdminPasswordChangeForm list_display = ("username", "email", "first_name", "last_name", "is_staff") list_filter = ("is_staff", "is_superuser", "is_active", "groups") search_fields = ("username", "first_name", "last_name", "email") ordering = ("username",) filter_horizontal = ( "groups", "user_permissions", ) def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: defaults["form"] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): return [ path( "<id>/password/", self.admin_site.admin_view(self.user_change_password), name="auth_user_password_change", ), *super().get_urls(), ] def lookup_allowed(self, lookup, value, request): # Don't allow lookups involving passwords. return not lookup.startswith("password") and super().lookup_allowed( lookup, value, request ) @method_decorator([sensitive_post_parameters(), csrf_protect]) def add_view(self, request, form_url="", extra_context=None): if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"): return self._add_view(request, form_url, extra_context) with transaction.atomic(using=router.db_for_write(self.model)): return self._add_view(request, form_url, extra_context) def _add_view(self, request, form_url="", extra_context=None): # It's an error for a user to have add permission but NOT change # permission for users. If we allowed such users to add users, they # could create superusers, which would mean they would essentially have # the permission to change users. To avoid the problem entirely, we # disallow users from adding users if they don't have change # permission. if not self.has_change_permission(request): if self.has_add_permission(request) and settings.DEBUG: # Raise Http404 in debug mode so that the user gets a helpful # error message. raise Http404( 'Your user does not have the "Change user" permission. In ' "order to add users, Django requires that your user " 'account have both the "Add user" and "Change user" ' "permissions set." ) raise PermissionDenied if extra_context is None: extra_context = {} username_field = self.opts.get_field(self.model.USERNAME_FIELD) extra_context.update(({ "auto_populated_fields": (), "username_help_text": username_field.help_text, })) return super().add_view(request, form_url, extra_context) @method_decorator(sensitive_post_parameters()) def user_change_password(self, request, id, form_url=""): user = self.get_object(request, unquote(id)) if not self.has_change_permission(request, user): raise PermissionDenied if user is None: raise Http404( _("%(name)s object with primary key %(key)r does not exist.") % { "name": self.opts.verbose_name, "key": escape(id), } ) if request.method == "POST": form = self.change_password_form(user, request.POST) if form.is_valid(): # If disabling password-based authentication was requested # (via the form field `usable_password`), the submit action # must be "unset-password". This check is most relevant when # the admin user has two submit buttons available (for example # when Javascript is disabled). valid_submission = ( form.cleaned_data["set_usable_password"] or "unset-password" in request.POST ) if not valid_submission: msg = gettext("Conflicting form data submitted. Please try again.") messages.error(request, msg) return HttpResponseRedirect(request.get_full_path()) user = form.save() self.log_change(request, user, (self.construct_change_message(request, form, None))) if user.has_usable_password(): msg = gettext("Password changed successfully.") else: msg = gettext("Password-based authentication was disabled.") messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( "%s:%s_%s_change" % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk,), ) ) else: form = self.change_password_form(user) fieldsets = [(None, {"fields": list(form.base_fields)})] admin_form = admin.helpers.AdminForm(form, fieldsets, {}) if user.has_usable_password(): title = _("Change password: %s") else: title = _("Set password: %s") request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or "admin/auth/user/change_password.html", ({ "title": title % escape(user.get_username()), "adminForm": admin_form, "form_url": form_url, "form": form, "is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), "is_popup_var": IS_POPUP_VAR, "add": True, "change": False, "has_delete_permission": False, "has_change_permission": True, "has_absolute_url": False, "opts": self.opts, "original": user, "save_as": False, "show_save": True, **self.admin_site.each_context(request), }), ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow further modification of the user just added i.e. the # 'Save' button should behave like the 'Save and continue editing' # button except in two scenarios: # * The user has pressed the 'Save and add another' button # * We are adding a user in a popup if "_addanother" not in request.POST and IS_POPUP_VAR not in request.POST: request.POST = request.POST.copy() request.POST["_continue"] = 1 return super().response_add(request, obj, post_url_continue)

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.9358.855−308.842
Source linesThe number of non-empty source lines.235+94
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.353−6.53

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.236−7.32
Indentation frequencyHow rapidly indentation changes from line to line.210+6.527
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.210−4.398
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.234.931+2.874
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.99.975+0.809
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.99.97−0.569
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.334

Intercept 0.07 + feature contributions = -1.673 (log-odds).
Score = sigmoid(-1.673) = 0.158.

Score0.335
Score97
Run 1

The code is generally well-structured and readable, following Django admin conventions. It has a clear logical organization with fieldsets, permissions, and custom methods separated appropriately. The imports are comprehensive and organized. The nesting level is moderate—the user_change_password method has some deeper nesting but remains manageable. The code's intent is clearly communicated through method names and comments. However, there are some readability issues: the `_add_view` method contains a long comment block that could be more concise, the `user_change_password` method is quite long and handles multiple responsibilities, and some dictionary construction in `TemplateResponse` is inconsistently formatted. The `extra_context.update(({...}))` has unnecessary parentheses. The code length is appropriate for the complexity of User admin functionality. Action granularity is mostly good with one action per line, though some lines like the `self.log_change` call are quite long. The reading flow is natural, progressing logically from setup to specific handlers.

Run 2

The code demonstrates strong readability through clear imports, logical class structure, and descriptive method names. Configuration attributes like fieldsets, list_display, and filter_horizontal are well-organized. Helpful comments explain non-obvious business logic, such as permission checks in _add_view and the response_add customization. However, the user_change_password method is notably long, containing multiple actions like validation, logging, messaging, and redirection. It could be refactored into smaller helper methods to improve readability. Some sections have unnecessary blank lines and a few verbose expressions, like constructing the HttpResponseRedirect, could be simplified. Overall, the code follows Django conventions and is generally easy to follow, but a few methods are long and could be broken down for better clarity.

Run 3

The code demonstrates good readability with clear organization, logical structure, and descriptive method names. It follows Django conventions well, making the intent clear. However, a few sections are overly verbose, particularly in _add_view with its long explanatory comment and in user_change_password with deeply nested conditionals and repetitive template context construction. The response_dict formatting could be improved for consistency. While the code is generally maintainable, some methods could benefit from extraction of smaller helpers to reduce nesting and improve flow. The flat structure for the most part and clear separation of concerns contribute positively. Overall, it's readable but could be more concise and have slightly better granularity.

Run 1

Code Structure: Well-organized Django admin class, with declarative configuration followed by focused methods; user_change_password handles several responsibilities. Nesting: Most methods are shallow, but password processing has nested POST, validation, and submission checks plus a deeply formatted redirect. Clarity of intent: Descriptive names, standard framework conventions, and security-focused comments make the purpose clear, though understanding requires Django familiarity. Code length: Mostly justified by configuration and workflows, but lengthy comments and the password-change method reduce concision. Action granularity: Generally one action per line; the long log_change call is harder to scan but remains a single operation. Reading flow: Methods follow coherent validation, processing, and response sequences, aided by early exits. Redundant parentheses, inconsistent dictionary indentation, extra whitespace, and a few long expressions interrupt otherwise natural reading.

Run 2

Code Structure: Configuration and behavior are logically grouped in a single admin class with focused methods. Nesting: Most methods are shallow, but password handling combines POST, validation, submission checks, and success branches with moderately deep nesting. Clarity of intent: Descriptive names, familiar Django conventions, and explanatory security comments make the purpose clear, though framework knowledge is required. Code length: Most verbosity is justified by configuration and workflow requirements; the password-change method and template context are lengthy. Action granularity: Statements generally perform one action per line, although the long log_change call compresses several operations visually. Reading flow: Imports, configuration, and methods follow a natural progression, with early permission checks helping navigation. Redundant parentheses, inconsistent dictionary indentation, extra blank lines, and a long unwrapped call introduce avoidable visual friction.

Run 3

Code Structure: Clearly organized into declarative admin configuration and focused methods, although user_change_password combines several responsibilities. Nesting: Most methods are shallow, but POST handling, form validation, and submission checks create moderately deep nesting. Clarity of intent: Descriptive names, familiar Django conventions, and explanatory security comments make the purpose clear; framework knowledge is needed for some details. Code length: Mostly justified by configuration and workflow requirements, though lengthy comments and context dictionaries add reading overhead. Action granularity: Statements generally perform one action per line, with no compressed multi-statement lines; one long log_change call is harder to scan. Reading flow: Guard clauses and orderly processing support natural reading, but redundant parentheses, inconsistent dictionary indentation, and stray whitespace interrupt the otherwise consistent formatting.