Sample

pyint-dcae0cad5854-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines154

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4040–1; higher is more readable
Mi0.6580–1; higher is more readable
LLOC79Logical lines; fewer is more readable
DeepSeek V4 Pro12.330–20; mean of three runs
GPT-6.1 Sol140–20; mean of three runs
BTTF0.3970–1; higher is more readable

Views

Source code

import copy import json from django import forms from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.db.models import CASCADE, UUIDField from django.forms.widgets import Select from django.urls import reverse from django.urls.exceptions import NoReverseMatch from django.utils.html import smart_urlquote from django.utils.http import urlencode from django.utils.text import Truncator from django.utils.translation import get_language from django.utils.translation import gettext as _ class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ template_name = "admin/widgets/related_widget_wrapper.html" def __init__( self, widget, rel, admin_site, can_add_related=None, can_change_related=False, can_delete_related=False, can_view_related=False, ): self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.widget = widget self.rel = rel # Backwards compatible check for whether a user can add related # objects. if not (can_add_related is None): pass else: can_add_related = admin_site.is_registered(rel.model) self.can_add_related = can_add_related if not (not isinstance(widget, AutocompleteMixin)): pass else: self.attrs["data-context"] = "available-source" # Only single-select Select widgets are supported. supported = not getattr( widget, "allow_multiple_selected", False ) and isinstance(widget, Select) self.can_change_related = supported and can_change_related # XXX: The deletion UX can be confusing when dealing with cascading # deletion. cascade = getattr(rel, "on_delete", None) is CASCADE self.can_delete_related = supported and not cascade and can_delete_related self.can_view_related = supported and can_view_related # To check if the related object is registered with this AdminSite. self.admin_site = admin_site self.use_fieldset = widget.use_fieldset def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj @property def is_hidden(self): return self.widget.is_hidden @property def media(self): return self.widget.media @property def choices(self): return self.widget.choices @choices.setter def choices(self, value): self.widget.choices = value def get_related_url(self, info, action, *args): return reverse( "admin:%s_%s_%s" % (*info, action), current_app=self.admin_site.name, args=args, ) def get_context(self, name, value, attrs): from django.contrib.admin.views.main import ( IS_POPUP_VAR, SOURCE_MODEL_VAR, TO_FIELD_VAR, ) rel_opts = self.rel.model._meta info = (rel_opts.app_label, rel_opts.model_name) related_field_name = self.rel.get_related_field().name app_label = self.rel.field.model._meta.app_label model_name = self.rel.field.model._meta.model_name url_params = "&".join( "%s=%s" % param for param in [ (TO_FIELD_VAR, related_field_name), (IS_POPUP_VAR, 1), (SOURCE_MODEL_VAR, f"{app_label}.{model_name}"), ] ) context = { "rendered_widget": self.widget.render(name, value, attrs), "is_hidden": self.is_hidden, "name": name, "url_params": url_params, "model": rel_opts.verbose_name, "model_name": rel_opts.model_name, "can_add_related": self.can_add_related, "can_change_related": self.can_change_related, "can_delete_related": self.can_delete_related, "can_view_related": self.can_view_related, "model_has_limit_choices_to": self.rel.limit_choices_to, } if not (self.can_add_related): pass else: context["add_related_url"] = self.get_related_url(info, "add") if not (self.can_delete_related): pass else: context["delete_related_template_url"] = self.get_related_url( info, "delete", "__fk__" ) if not (self.can_view_related or self.can_change_related): pass else: context["view_related_url_params"] = f"{TO_FIELD_VAR}={related_field_name}" context["change_related_template_url"] = self.get_related_url( info, "change", "__fk__" ) return context def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def value_omitted_from_data(self, data, files, name): return self.widget.value_omitted_from_data(data, files, name) def id_for_label(self, id_): return self.widget.id_for_label(id_)

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.5747.926−189.682
Source linesThe number of non-empty source lines.154+61.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.426−6.64

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.155−4.452
Indentation frequencyHow rapidly indentation changes from line to line.145+4.278
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.145−2.906
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.153.795+1.74
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.89+0.597
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.066+0.303
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.948−0.018

Intercept 0.07 + feature contributions = -0.387 (log-odds).
Score = sigmoid(-0.387) = 0.404.

Score0.658
Score79
Run 1

The code is generally readable but contains some awkward patterns that reduce clarity. The structure is logical, with clear class organization and a sensible method order. However, the frequent use of inverted conditionals like `if not (can_add_related is None): pass else: ...` is confusing and unnecessarily verbose—these should be simple `if can_add_related is None:` statements. Nesting is mostly flat, which is good, but the constructor has many assignments packed together without visual separation. Intent is clear thanks to good docstrings and comments, though some logic (like backwards compatibility checks) could be more explicit. The code is moderately concise but could be shorter by replacing the inverted conditionals. Action granularity is mostly one action per line, but multi-line boolean expressions add slight complexity. Reading flow is natural, with properties and methods grouped logically.

Run 2

The code has a clear overall structure with logical class organization, but several readability issues lower its score. The most significant problem is the inverted conditional pattern used throughout (`if not condition: pass else:`), which should be standard positive conditionals like `if condition:`. This pattern is counterintuitive and breaks natural reading flow. The deeply nested multiline `getattr()` call inside the `supported` variable assignment is awkward and hard to parse. Multiple imports are unused (json, settings, ValidationError, URLValidator, smart_urlquote, urlencode, Truncator, get_language, NoReverseMatch, UUIDField), suggesting potential code rot. The `url_params` construction using `"&"`.join with a list of tuples is less clear than using Django's built-in `urlencode` utility (which is imported but unused). Action granularity is mostly appropriate, with one logical operation per line in most cases. The class has a clear responsibility and reasonable method decomposition. However, the pervasive inverted conditionals create unnecessary cognitive friction, and the unused imports indicate poor maintenance.

Run 3

The code is generally well-structured with clear class definition, logical method organization, and good use of properties. However, several factors reduce readability: repeated inverted conditional patterns (e.g., 'if not (x): pass else:' instead of direct conditionals), long method signatures with many parameters, and complex boolean logic in __init__ that requires careful parsing. The get_context method contains mixed levels of abstraction and inline URL parameter construction. Imports are excessive but typical for Django admin code. The code effectively delegates to the wrapped widget, showing clear intent, but the conditional patterns feel awkward and could be simplified. Overall, it's maintainable but requires Django familiarity and careful reading of conditional logic.

Run 1

Code Structure: The class is logically organized into initialization, properties, context construction, and delegation methods. Nesting: Depth is shallow, but repeated negated conditions with empty pass branches and else blocks introduce unnecessary branching. Clarity of intent: Descriptive method names, context keys, and comments explain most behavior; double negation obscures straightforward checks, and AutocompleteMixin is not defined or imported in the snippet. Code length: Mostly appropriate for the wrapper, though redundant conditionals and several unused imports add clutter. Action granularity: Statements generally perform one action per line, and multiline calls and dictionaries are formatted clearly. Reading flow: Methods follow a natural progression, but inverted conditions repeatedly interrupt comprehension. Direct positive checks would substantially improve readability.

Run 2

Code Structure: The class is logically organized into initialization, properties, context construction, and delegation methods. Nesting: Mostly shallow, but repeated inverted if/pass/else branches introduce unnecessary control flow. Clarity of intent: Descriptive method and attribute names, comments, and the docstring communicate the wrapper's purpose; double negation and the unexplained AutocompleteMixin reference reduce clarity. Code length: Delegation methods are concise, while redundant branches and several unused imports add avoidable length. Action granularity: Statements generally perform one action per line, and multiline expressions are formatted cleanly. Reading flow: The overall progression is natural, but empty branches repeatedly interrupt straightforward logic, and the long initializer and context-building method require some tracking of related flags.

Run 3

Code Structure: The class is logically organized into initialization, properties, context generation, and delegation methods. Nesting: Mostly shallow, but repeated inverted conditions with empty pass branches introduce unnecessary control flow. Clarity of intent: Descriptive method names, attributes, and comments communicate the widget wrapper’s purpose; double negation and indirect conditions make some behavior harder to interpret. Code length: Delegation methods are concise, but redundant if/else blocks and several unused imports add avoidable length and clutter. Action granularity: Statements generally perform one action per line, and multiline calls and dictionaries are cleanly formatted. Reading flow: The overall progression is natural, although negative conditions, especially the AutocompleteMixin check, interrupt comprehension. Straightforward positive checks and removal of unused imports would substantially improve readability.