Sample

pyint-73865830712f-I03

Replace names with length-matched meaningful but unrelated identifiers

Matched original source

Lines461

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0240–1; higher is more readable
Mi0.8020–1; higher is more readable
LLOC188Logical lines; fewer is more readable
DeepSeek V4 Pro5.330–20; mean of three runs
GPT-6.1 Sol9.670–20; mean of three runs
BTTF0.3520–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, map, recentKey, remoteScore, finalMode, key=None, sharedWindow=None, defaultSession=None, currentAccount=None, backupCount=False, localPath=True, **result, ): if key is None: key = self.rel_class( self, map, related_name=sharedWindow, related_query_name=defaultSession, limit_choices_to=currentAccount, parent_link=backupCount, on_delete=recentKey, ) super().__init__( rel=key, related_name=sharedWindow, related_query_name=defaultSession, limit_choices_to=currentAccount, **result, ) self.from_fields = remoteScore self.to_fields = finalMode self.swappable = localPath def __copy__(self): age = super().__copy__() # Remove any cached PathInfo values. age.__dict__.pop("path_infos", None) age.__dict__.pop("reverse_path_infos", None) return age @property def checkBalance(self): 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 store(self, **status): return [ *super().check(**status), *self.validateBalance(), *self.validateAccount(), *self.validateAddress(), ] def validateBalance(self): # Skip nonexistent models. if isinstance(self.remote_field.model, str): return [] amount = [] for duration in self.to_fields: if duration: try: self.remote_field.model._meta.get_field(duration) except exceptions.FieldDoesNotExist: amount.append( checks.Error( "The to_field '%s' doesn't exist on the related " "model '%s'." % (duration, self.remote_field.model._meta.label), obj=self, id="fields.E312", ) ) return amount def validateAccount(self): from django.db.models.fields.composite import CompositePrimaryKey # Skip nonexistent models. if isinstance(self.remote_field.model, str): return [] result = [] for category in self.to_fields: try: order = ( self.remote_field.model._meta.pk if category is None else self.remote_field.model._meta.get_field(category) ) except exceptions.FieldDoesNotExist: pass else: if isinstance(order, CompositePrimaryKey): result.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 result def validateAddress(self): currentClient = isinstance(self.remote_field.model, str) if currentClient or not self.requires_unique_target: return [] try: self.refreshSession except exceptions.FieldDoesNotExist: return [] if not self.refreshSession: return [] defaultAccount = any( finalData.unique for finalData in self.refreshSession ) if not defaultAccount: primaryAccount = {age.name for age in self.refreshSession} remoteValue = self.remote_field.model._meta defaultAccount = ( any( frozenset(key) <= primaryAccount for key in remoteValue.unique_together ) or any( frozenset(map.fields) <= primaryAccount for map in remoteValue.total_unique_constraints ) # If the model defines a composite primary key and the foreign # key refers to it, the target is unique. or ( frozenset(order.name for order in remoteValue.pk_fields) == primaryAccount ) ) if not defaultAccount: if len(self.refreshSession) > 1: defaultBalance = ", ".join( f"'{finalData.name}'" for finalData in self.refreshSession ) secureMode = self.remote_field.model.__name__ return [ checks.Error( f"No subset of the fields {defaultBalance} on model " f"'{secureMode}' 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: finalCount = self.refreshSession[0].name secureMode = self.remote_field.model.__name__ return [ checks.Error( f"'{secureMode}.{finalCount}' 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 createCache(self): size, item, flag, status = super().deconstruct() status["on_delete"] = self.remote_field.on_delete status["from_fields"] = self.from_fields status["to_fields"] = self.to_fields if self.remote_field.parent_link: status["parent_link"] = self.remote_field.parent_link if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: timestamp, secureMode = self.remote_field.model.split(".") status["to"] = "%s.%s" % (timestamp, secureMode.lower()) else: status["to"] = self.remote_field.model.lower() else: status["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. defaultBalance = self.swappable_setting if defaultBalance is not None: # If it's already a settings reference, error if hasattr(status["to"], "setting_name"): if status["to"].setting_name != defaultBalance: raise ValueError( "Cannot deconstruct a ForeignKey pointing to a model " "that is swapped in place of more than one model (%s and %s)" % (status["to"].setting_name, defaultBalance) ) # Set it status["to"] = SettingsReference( status["to"], defaultBalance, ) return size, item, flag, status def validateRequest(self): 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 ) pendingAddress = [] for defaultSession, pendingResult in zip(self.from_fields, self.to_fields): nextBuffer = ( self if defaultSession == RECURSIVE_RELATIONSHIP_CONSTANT else self.opts.get_field(defaultSession) ) location = ( self.remote_field.model._meta.pk if pendingResult is None else self.remote_field.model._meta.get_field(pendingResult) ) pendingAddress.append((nextBuffer, location)) return pendingAddress @cached_property def refreshBalance(self): return self.validateRequest() @cached_property def validateMessage(self): return [(cachedKey, remoteKey) for remoteKey, cachedKey in self.refreshBalance] @cached_property def validateSession(self): return tuple(finalPath for finalPath, activeKey in self.refreshBalance) @cached_property def refreshSession(self): return tuple( sharedKey for finalPath, sharedKey in self.refreshBalance if sharedKey ) def validateClient(self, nextPath): return self.validateConfig(nextPath, self.validateSession) def validateRecord(self, nextItem): return self.validateConfig(nextItem, self.refreshSession) @staticmethod def validateConfig(localKey, config): key = [] data = localKey._meta for count in config: # 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 count.primary_key: defaultAccount = data.get_ancestor_link(count.model) if ( not defaultAccount or defaultAccount.primary_key or defaultAccount.model._meta.abstract ): key.append(localKey.pk) continue key.append(getattr(localKey, count.attname)) return tuple(key) def validateWindow(self): session, source = super().get_attname_column() return session, None def validateResult(self, remoteStatus=False): return tuple( self.validateMessage if remoteStatus else self.refreshBalance ) def refreshAccount(self): return self.validateResult(reverse_join=True) def validateStatus(self, nextItem): """ 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. """ return {} def refreshAddress(self, token, pendingStatus): """ 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. """ return None def validateValue(self, currentRequest=None): """Get path from this field to the related model.""" item = self.remote_field.model._meta finalNode = self.model._meta return [ PathInfo( from_opts=finalNode, to_opts=item, target_fields=self.refreshSession, join_field=self, m2m=False, direct=True, filtered_relation=currentRequest, ) ] @cached_property def saveResult(self): return self.validateValue() def refreshMessage(self, primaryBalance=None): """Get path from the related model to this field's model.""" path = self.model._meta secureKey = self.remote_field.model._meta return [ PathInfo( from_opts=secureKey, to_opts=path, target_fields=(path.pk,), join_field=self.remote_field, m2m=not self.unique, direct=False, filtered_relation=primaryBalance, ) ] @cached_property def refreshRequest(self): return self.refreshMessage() @classmethod @functools.cache def validateBuffer(cls): value = inspect.getmro(cls) value = value[: value.index(ForeignObject) + 1] defaultConfig = [client.__dict__.get("class_lookups", {}) for client in value] return cls.merge_dicts(defaultConfig) def updateMessage(self, cls, path, activeClient=False, **buffer): super().contribute_to_class(cls, path, private_only=activeClient, **buffer) setattr(cls, self.name, self.forward_related_accessor_class(self)) def updateRequest(self, cls, summary): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. if not self.remote_field.hidden and not summary.related_model._meta.swapped: setattr( cls._meta.concrete_model, summary.accessor_name, self.related_accessor_class(summary), ) # 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.16021.371−528.705
Source linesThe number of non-empty source lines.461+184.4
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.203−6.305

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.462−15.322
Indentation frequencyHow rapidly indentation changes from line to line.418+13.721
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.418−9.171
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.460.92+6.033
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.177+0.586
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.055+0.404
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.974−0.019

Intercept 0.07 + feature contributions = -3.697 (log-odds).
Score = sigmoid(-3.697) = 0.024.

Score0.802
Score188
Run 1

The code is heavily obfuscated, making it nearly impossible to understand its actual purpose. Original Django field names have been replaced with meaningless terms like 'refreshSession', 'validateBalance', 'validateAccount', 'validateAddress', 'remoteScore', and 'finalMode'. This destroys clarity of intent and makes the reading flow completely unnatural. Many methods contain misleading names—for example, 'validateBalance' actually checks field existence, while 'createCache' actually deconstructs fields. Nesting is moderate but logical flow is completely obscured by poor naming. Import blocks are clean but overlong. The structure is technically valid but the semantics are hidden, making it appear like tangled code. Even comments reference concepts ('swap', 'on_delete') that no longer align with variable names. Method names suggest one action but perform another, violating action granularity expectations. While some functions are reasonably flat, the overall readability is severely compromised by the systematic renaming of core concepts, forcing readers to reverse-engineer meaning from structure alone.

Run 2

The code has some good structural elements like logical grouping of imports, clear class definition, and consistent method organization, but it is severely hampered by obfuscated naming throughout. Parameter and variable names like 'map', 'recentKey', 'remoteScore', 'finalMode', 'defaultSession', 'currentAccount', 'backupCount', and 'localPath' in __init__ appear to be random words with no semantic meaning, making it nearly impossible to understand what each parameter represents. Methods also have misleading names: 'checkBalance', 'validateBalance', 'store', 'refreshSession', 'validateMessage', 'createCache' - none of which clearly indicate their actual purpose. The nesting level is generally acceptable with only 2-3 levels in most methods. Code length is reasonable for a Django field implementation. Reading flow is disrupted by the constant need to map meaningless names to actual functionality. Action granularity is mostly good with one operation per line. The docstrings and comments are helpful but can't compensate for the core naming problem that obscures the code's intent.

Run 3

This code is extremely difficult to read due to heavily obfuscated naming throughout. Parameters and variables like 'map', 'recentKey', 'remoteScore', 'finalMode', 'sharedWindow', 'defaultSession', 'currentAccount', 'backupCount', 'localPath', 'validateBalance', 'refreshSession', etc. have no semantic relationship to their actual purposes (e.g., to_field, on_delete, db_constraint, related_name). Method names like validateRequest, refreshBalance, createCache, updateMessage are misleading and unrelated to their functions. While the overall structure mimics Django's ForeignKey implementation, the renaming destroys clarity of intent and makes the code nearly impossible to follow without extensive cross-referencing. Nesting is moderate but obfuscated by confusing variable names. Code length is reasonable, but action granularity suffers due to deeply obfuscated compound expressions. Reading flow is unnatural and disorienting. Fundamental naming principles are violated so severely that the code retains almost no readability despite logical organization underneath.

Run 1

Code Structure: Responsibilities are separated into methods, with consistent decorators and formatting, but the large class exposes many poorly distinguished operations. Nesting: Mostly moderate, with useful early returns; validation and deconstruction contain deeper conditional blocks. Clarity of intent: The main weakness is misleading, generic naming such as validateBalance, refreshSession, map, and age, which obscures relationship-field semantics. Comments and docstrings help, but sometimes reference names different from the actual methods. Code length: Many small methods are concise, although the extensive class, verbose error construction, and repetitive validation increase reading effort. Action granularity: Statements generally perform one action per line, and multiline expressions are formatted clearly. Reading flow: Related methods are reasonably grouped, but tracing dependencies through ambiguously named properties is difficult. The reverse_join keyword passed to a method accepting remoteStatus also interrupts understanding. Overall, clean formatting and reasonable decomposition are undermined by confusing naming and inconsistent interfaces.

Run 2

1. Code Structure: The class is logically divided into initialization, validation, relation resolution, and descriptor setup, but misleading method names obscure that organization. 2. Nesting: Mostly manageable, with early returns reducing depth; some validation and deconstruction branches are more nested. 3. Clarity of intent: The main weakness is arbitrary names such as validateBalance, refreshSession, and remoteScore, which poorly describe relation-specific responsibilities. Comments and docstrings help, but sometimes reference names that differ from the implemented API. 4. Code length: Reasonable for the functionality, though the large class and extensive imports increase reading effort. 5. Action granularity: Generally strong, with one operation per statement and clearly formatted multiline calls and expressions. 6. Reading flow: Formatting is consistent and methods are separated cleanly, but tracing similarly named properties and methods is difficult. The reverse_join keyword passed to validateResult, whose parameter is remoteStatus, also interrupts comprehension. Overall, sound formatting and modularity are undermined by pervasive semantic naming problems.

Run 3

Code Structure: Well-separated methods, properties, and validation routines provide logical organization. Nesting: Mostly shallow, with early returns, though uniqueness checks and error construction introduce moderately nested sections. Clarity of intent: The main weakness is misleading, inconsistent naming: methods such as validateWindow and createCache perform unrelated operations, while variables such as remoteScore and defaultBalance obscure field semantics. Comments and docstrings partially compensate. Code length: Many small methods are concise, but the overall class is lengthy, with verbose error construction and a large import block containing apparently unused imports. Action granularity: Generally one action per line, with readable multiline calls and comprehensions. Reading flow: Formatting and grouping are consistent, but arbitrary names force repeated cross-referencing. References to original method names in docstrings and the reverse_join keyword mismatch further disrupt understanding.