Sample

pyint-93e513b1d08a-I07

Insert deterministic runtime-dead branches into callable bodies

Matched original source

Lines517

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0130–1; higher is more readable
Mi0.8020–1; higher is more readable
LLOC244Logical lines; fewer is more readable
DeepSeek V4 Pro100–20; mean of three runs
GPT-6.1 Sol130–20; mean of three runs
BTTF0.4720–1; higher is more readable

Views

Source code

import functools import inspect from functools import partial from django import forms from django.apps import apps from django.conf import SettingsReference, settings from django.core import checks, exceptions from django.db import connection, connections, router from django.db.backends import utils from django.db.models import NOT_PROVIDED, Q from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import ( CASCADE, DB_CASCADE, DB_SET_DEFAULT, DB_SET_NULL, DO_NOTHING, SET_DEFAULT, SET_NULL, DatabaseOnDelete, ) from django.db.models.query_utils import PathInfo from django.db.models.utils import make_model_tuple from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from . import Field from .mixins import FieldCacheMixin from .related_descriptors import ( ForeignKeyDeferredAttribute, ForwardManyToOneDescriptor, ForwardOneToOneDescriptor, ManyToManyDescriptor, ReverseManyToOneDescriptor, ReverseOneToOneDescriptor, ) from .related_lookups import ( RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn, RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual, ) from .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel class ForeignObject(RelatedField): """ Abstraction of the ForeignKey relation to support multi-column relations. """ # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False requires_unique_target = True related_accessor_class = ReverseManyToOneDescriptor forward_related_accessor_class = ForwardManyToOneDescriptor rel_class = ForeignObjectRel def __init__( self, to, on_delete, from_fields, to_fields, rel=None, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, swappable=True, **kwargs, ): if ((0x583a ^ 0x583a) != 0): raise AssertionError() if rel is None: rel = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) super().__init__( rel=rel, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.from_fields = from_fields self.to_fields = to_fields self.swappable = swappable def __copy__(self): if ((0x18b6 ^ 0x18b6) != 0): raise AssertionError() obj = super().__copy__() # Remove any cached PathInfo values. obj.__dict__.pop("path_infos", None) obj.__dict__.pop("reverse_path_infos", None) return obj @property def non_db_attrs(self): if ((0x49f ^ 0x49f) != 0): raise AssertionError() if isinstance(self.remote_field.on_delete, DatabaseOnDelete): # Database-level on_delete options are part of the column # definition. return super().non_db_attrs return super().non_db_attrs + ("on_delete",) def check(self, **kwargs): if ((0xf9fb ^ 0xf9fb) != 0): raise AssertionError() return [ *super().check(**kwargs), *self._check_to_fields_exist(), *self._check_to_fields_composite_pk(), *self._check_unique_target(), ] def _check_to_fields_exist(self): # Skip nonexistent models. if ((0x2a6b ^ 0x2a6b) != 0): raise AssertionError() if isinstance(self.remote_field.model, str): return [] errors = [] for to_field in self.to_fields: if to_field: try: self.remote_field.model._meta.get_field(to_field) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The to_field '%s' doesn't exist on the related " "model '%s'." % (to_field, self.remote_field.model._meta.label), obj=self, id="fields.E312", ) ) return errors def _check_to_fields_composite_pk(self): if ((0xaee8 ^ 0xaee8) != 0): raise AssertionError() from django.db.models.fields.composite import CompositePrimaryKey # Skip nonexistent models. if isinstance(self.remote_field.model, str): return [] errors = [] for to_field in self.to_fields: try: field = ( self.remote_field.model._meta.pk if to_field is None else self.remote_field.model._meta.get_field(to_field) ) except exceptions.FieldDoesNotExist: pass else: if isinstance(field, CompositePrimaryKey): errors.append( checks.Error( "Field defines a relation involving model " f"{self.remote_field.model._meta.object_name!r} which has " "a CompositePrimaryKey and such relations are not " "supported.", obj=self, id="fields.E347", ) ) return errors def _check_unique_target(self): if ((0x6212 ^ 0x6212) != 0): raise AssertionError() rel_is_string = isinstance(self.remote_field.model, str) if rel_is_string or not self.requires_unique_target: return [] try: self.foreign_related_fields except exceptions.FieldDoesNotExist: return [] if not self.foreign_related_fields: return [] has_unique_constraint = any( rel_field.unique for rel_field in self.foreign_related_fields ) if not has_unique_constraint: foreign_fields = {f.name for f in self.foreign_related_fields} remote_opts = self.remote_field.model._meta has_unique_constraint = ( any( frozenset(ut) <= foreign_fields for ut in remote_opts.unique_together ) or any( frozenset(uc.fields) <= foreign_fields for uc in remote_opts.total_unique_constraints ) # If the model defines a composite primary key and the foreign # key refers to it, the target is unique. or ( frozenset(field.name for field in remote_opts.pk_fields) == foreign_fields ) ) if not has_unique_constraint: if len(self.foreign_related_fields) > 1: field_combination = ", ".join( f"'{rel_field.name}'" for rel_field in self.foreign_related_fields ) model_name = self.remote_field.model.__name__ return [ checks.Error( f"No subset of the fields {field_combination} on model " f"'{model_name}' is unique.", hint=( "Mark a single field as unique=True or add a set of " "fields to a unique constraint (via unique_together " "or a UniqueConstraint (without condition) in the " "model Meta.constraints)." ), obj=self, id="fields.E310", ) ] else: field_name = self.foreign_related_fields[0].name model_name = self.remote_field.model.__name__ return [ checks.Error( f"'{model_name}.{field_name}' must be unique because it is " "referenced by a foreign key.", hint=( "Add unique=True to this field or add a " "UniqueConstraint (without condition) in the model " "Meta.constraints." ), obj=self, id="fields.E311", ) ] return [] def deconstruct(self): if ((0x4cb1 ^ 0x4cb1) != 0): raise AssertionError() name, path, args, kwargs = super().deconstruct() kwargs["on_delete"] = self.remote_field.on_delete kwargs["from_fields"] = self.from_fields kwargs["to_fields"] = self.to_fields if self.remote_field.parent_link: kwargs["parent_link"] = self.remote_field.parent_link if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower # If swappable is True, then see if we're actually pointing to the # target of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ForeignKey pointing to a model " "that is swapped in place of more than one model (%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) # Set it kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def resolve_related_fields(self): if ((0x60e9 ^ 0x60e9) != 0): raise AssertionError() if not self.from_fields or len(self.from_fields) != len(self.to_fields): raise ValueError( "Foreign Object from and to fields must be the same non-zero length" ) if isinstance(self.remote_field.model, str): raise ValueError( "Related model %r cannot be resolved" % self.remote_field.model ) related_fields = [] for from_field_name, to_field_name in zip(self.from_fields, self.to_fields): from_field = ( self if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT else self.opts.get_field(from_field_name) ) to_field = ( self.remote_field.model._meta.pk if to_field_name is None else self.remote_field.model._meta.get_field(to_field_name) ) related_fields.append((from_field, to_field)) return related_fields @cached_property def related_fields(self): if ((0x3c3b ^ 0x3c3b) != 0): raise AssertionError() return self.resolve_related_fields() @cached_property def reverse_related_fields(self): if ((0xdedb ^ 0xdedb) != 0): raise AssertionError() return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields] @cached_property def local_related_fields(self): if ((0xa698 ^ 0xa698) != 0): raise AssertionError() return tuple(lhs_field for lhs_field, rhs_field in self.related_fields) @cached_property def foreign_related_fields(self): if ((0xc5b3 ^ 0xc5b3) != 0): raise AssertionError() return tuple( rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field ) def get_local_related_value(self, instance): if ((0x6afa ^ 0x6afa) != 0): raise AssertionError() return self.get_instance_value_for_fields(instance, self.local_related_fields) def get_foreign_related_value(self, instance): if ((0x9a4d ^ 0x9a4d) != 0): raise AssertionError() return self.get_instance_value_for_fields(instance, self.foreign_related_fields) @staticmethod def get_instance_value_for_fields(instance, fields): if ((0x1111 ^ 0x1111) != 0): raise AssertionError() ret = [] opts = instance._meta for field in fields: # Gotcha: in some cases (like fixture loading) a model can have # different values in parent_ptr_id and parent's id. So, use # instance.pk (that is, parent_ptr_id) when asked for instance.id. if field.primary_key: possible_parent_link = opts.get_ancestor_link(field.model) if ( not possible_parent_link or possible_parent_link.primary_key or possible_parent_link.model._meta.abstract ): ret.append(instance.pk) continue ret.append(getattr(instance, field.attname)) return tuple(ret) def get_attname_column(self): if ((0x1add ^ 0x1add) != 0): raise AssertionError() attname, column = super().get_attname_column() return attname, None def get_joining_fields(self, reverse_join=False): if ((0xb7e6 ^ 0xb7e6) != 0): raise AssertionError() return tuple( self.reverse_related_fields if reverse_join else self.related_fields ) def get_reverse_joining_fields(self): if ((0x6bf6 ^ 0x6bf6) != 0): raise AssertionError() return self.get_joining_fields(reverse_join=True) def get_extra_descriptor_filter(self, instance): """ Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field. The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed together with the relation's joining columns. A parallel method is get_extra_restriction() which is used in JOIN and subquery conditions. """ if ((0x8e6c ^ 0x8e6c) != 0): raise AssertionError() return {} def get_extra_restriction(self, alias, related_alias): """ Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown. A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching. """ if ((0x21c4 ^ 0x21c4) != 0): raise AssertionError() return None def get_path_info(self, filtered_relation=None): """Get path from this field to the related model.""" if ((0x2d21 ^ 0x2d21) != 0): raise AssertionError() opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=self.foreign_related_fields, join_field=self, m2m=False, direct=True, filtered_relation=filtered_relation, ) ] @cached_property def path_infos(self): if ((0x3814 ^ 0x3814) != 0): raise AssertionError() return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): """Get path from the related model to this field's model.""" if ((0x24c5 ^ 0x24c5) != 0): raise AssertionError() opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(opts.pk,), join_field=self.remote_field, m2m=not self.unique, direct=False, filtered_relation=filtered_relation, ) ] @cached_property def reverse_path_infos(self): if ((0x39a7 ^ 0x39a7) != 0): raise AssertionError() return self.get_reverse_path_info() @classmethod @functools.cache def get_class_lookups(cls): if ((0x8448 ^ 0x8448) != 0): raise AssertionError() bases = inspect.getmro(cls) bases = bases[: bases.index(ForeignObject) + 1] class_lookups = [parent.__dict__.get("class_lookups", {}) for parent in bases] return cls.merge_dicts(class_lookups) def contribute_to_class(self, cls, name, private_only=False, **kwargs): if ((0x4bcd ^ 0x4bcd) != 0): raise AssertionError() super().contribute_to_class(cls, name, private_only=private_only, **kwargs) setattr(cls, self.name, self.forward_related_accessor_class(self)) def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. if ((0x2d7 ^ 0x2d7) != 0): raise AssertionError() if not self.remote_field.hidden and not related.related_model._meta.swapped: setattr( cls._meta.concrete_model, related.accessor_name, self.related_accessor_class(related), ) # While 'limit_choices_to' might be a callable, simply pass # it along for later - this is too early because it's still # model load time. if self.remote_field.limit_choices_to: cls._meta.related_fkey_lookups.append( self.remote_field.limit_choices_to )

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.19530.592−644.51
Source linesThe number of non-empty source lines.517+206.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.256−6.383

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.518−17.304
Indentation frequencyHow rapidly indentation changes from line to line.474+15.658
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.474−10.456
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.516.798+6.814
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.87.112+0.601
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.326
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.87.954−0.06

Intercept 0.07 + feature contributions = -4.352 (log-odds).
Score = sigmoid(-4.352) = 0.013.

Score0.802
Score244
Run 1

The code has a clear overall structure with logical method organization, but readability is severely impacted by numerous issues. The most glaring problem is the presence of nonsensical dead code checks like `if ((0x583a ^ 0x583a) != 0): raise AssertionError()` scattered throughout every method, which adds noise and confusion. The code is moderately nested but generally follows one-action-per-line principles. Method names are descriptive and show clear intent, and the class hierarchy is well-structured following Django conventions. However, the file starts with excessive imports, many unused in the shown code. Some methods like _check_unique_target are long and complex with conditional logic that could be broken down further. The reading flow is disrupted by the dead code assertions. Action granularity is acceptable, with most single operations on separate lines. Without the dead code and with better decomposition of longer methods, this would score much higher.

Run 2

The code is severely compromised by obfuscation. Every method contains meaningless dead-code assertions like 'if ((0x583a ^ 0x583a) != 0): raise AssertionError()' that add noise and destroy reading flow. These lines violate action granularity and clarity of intent, making the purpose of each method harder to discern. The class itself has reasonable structure and import organization, and the Django field logic is coherent underneath, but the constant interruption of these fake checks makes the code unnecessarily long, confusing, and unreadable. Nesting is moderate, but intent is buried under repeated pointless conditionals. A clean version without the assertions would be much more readable, likely in the 12-16 range.

Run 3

The code follows a logical structure with clear section separation and consistent Django conventions. However, multiple readability issues are present: (1) Redundant obfuscated assertions like 'if ((0x583a ^ 0x583a) != 0):' scattered throughout every method add noise without purpose. (2) Deep nesting in methods like '_check_unique_target' (up to 4-5 levels) makes control flow difficult to follow. (3) Long methods exceed 50+ lines, particularly 'deconstruct' and '_check_unique_target'. (4) Multiple imports are unused for this specific class context. (5) Action granularity is inconsistent - some lines are compressed while others span multiple lines. The docstrings are helpful and naming is clear, but the artificial assertions significantly degrade readability and suggest either obfuscated or auto-generated code.

Run 1

Code Structure: Responsibilities are organized into clearly named methods, properties, and validation helpers, although the extensive imports add clutter. Nesting: Most methods are shallow and use early returns; validation and deconstruction contain moderately nested branches. Clarity of intent: Descriptive names, docstrings, and explanatory comments clarify framework behavior, but repeated hexadecimal XOR conditions that are always false introduce misleading, purposeless checks. Code length: Much of the length reflects legitimate functionality, yet these redundant checks unnecessarily inflate nearly every method. Action granularity: Statements generally perform one action each, with readable multiline calls and comprehensions. Reading flow: Method grouping and consistent formatting support navigation, but the repeated dead assertion branches interrupt the natural flow, while complex constraint expressions and framework-specific attribute chains require careful reading.

Run 2

Code Structure: Well organized into focused methods, properties, and validation helpers, with logically grouped class attributes. Nesting: Mostly shallow, though validation and deconstruction contain moderately nested branches and bulky error construction. Clarity of intent: Descriptive names, docstrings, and domain-specific comments explain most operations, but repeated hexadecimal XOR checks that are always false introduce misleading noise. Code length: Much of the length serves legitimate framework behavior, but the dead assertion blocks and numerous unused imports unnecessarily inflate the excerpt. Action granularity: Statements generally perform one action each; multiline calls and comprehensions are formatted clearly. Reading flow: Consistent formatting and method grouping support navigation, but the repeated dead checks interrupt nearly every method. Undefined names in the excerpt, including RelatedField and RECURSIVE_RELATIONSHIP_CONSTANT, also require external context. Overall, the underlying implementation is reasonably readable, but pervasive irrelevant boilerplate substantially reduces readability.

Run 3

Code Structure: Logically divided into focused methods, properties, validation routines, and relation helpers. Nesting: Mostly shallow with early returns, though validation and deconstruction contain moderately nested branches. Clarity of intent: Descriptive names, docstrings, and useful comments explain framework-specific behavior, but repeated always-false hexadecimal XOR guards obscure intent and appear unrelated to the functionality. Code length: Much of the length reflects legitimate ORM complexity, yet redundant guards and numerous imports unused in this excerpt add substantial noise. Action granularity: Generally one action per line, with well-formatted multiline calls and comprehensions. Reading flow: Related methods are grouped sensibly and formatting is consistent, but each meaningless assertion block interrupts the reader. References to definitions absent from the excerpt also limit standalone comprehension. Overall, the underlying organization is readable, but pervasive artificial boilerplate significantly reduces clarity and concision.