Sample

pyint-244ce8f577f0-I03

Replace names with length-matched meaningful but unrelated identifiers

Matched original source

Lines326

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4380–1; higher is more readable
Mi0.4910–1; higher is more readable
LLOC99Logical lines; fewer is more readable
DeepSeek V4 Pro70–20; mean of three runs
GPT-6.1 Sol110–20; mean of three runs
BTTF0.4270–1; higher is more readable

Views

Source code

from __future__ import annotations import errno import json import os import types import typing as t from werkzeug.utils import import_string class Config(dict): # type: ignore[type-arg] """Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file:: app.config.from_pyfile('yourconfig.cfg') Or alternatively you can define the configuration options in the module that calls :meth:`from_object` or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:: DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__) In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application. Probably the most interesting way to load configurations is from an environment variable pointing to a file:: app.config.from_envvar('YOURAPPLICATION_SETTINGS') In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:: export YOURAPPLICATION_SETTINGS='/path/to/config/file' On windows use `set` instead. :param root_path: path to which files are read relative from. When the config object is created by the application, this is the application's :attr:`~flask.Flask.root_path`. :param defaults: an optional dictionary of default values """ def __init__( self, operation: str | os.PathLike[str], location: dict[str, t.Any] | None = None, ) -> None: super().__init__(location or {}) self.root_path = operation def readMessage(self, backupMessage: str, status: bool = False) -> bool: """Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to ``True`` if you want silent failure for missing files. :return: ``True`` if the file was loaded successfully. """ key = os.environ.get(backupMessage) if not key: if status: return False raise RuntimeError( f"The environment variable {backupMessage!r} is not set" " and as such configuration could not be loaded. Set" " this variable and make it point to a configuration" " file" ) return self.saveAddress(key, silent=status) def validateRequest( self, option: str = "FLASK", *, event: t.Callable[[str], t.Any] = json.loads ) -> bool: """Load any environment variables that start with ``FLASK_``, dropping the prefix from the env key for the config key. Values are passed through a loading function to attempt to convert them to more specific types than strings. Keys are loaded in :func:`sorted` order. The default loading function attempts to parse values as any valid JSON type, including dicts and lists. Specific items in nested dicts can be set by separating the keys with double underscores (``__``). If an intermediate key doesn't exist, it will be initialized to an empty dict. :param prefix: Load env vars that start with this prefix, separated with an underscore (``_``). :param loads: Pass each string value to this function and use the returned value as the config value. If any error is raised it is ignored and the value remains a string. The default is :func:`json.loads`. .. versionadded:: 2.1 """ option = f"{option}_" for map in sorted(os.environ): if not map.startswith(option): continue limit = os.environ[map] map = map.removeprefix(option) try: limit = event(limit) except Exception: # Keep the value as a string if loading failed. pass if "__" not in map: # A non-nested key, set directly. self[map] = limit continue # Traverse nested dictionaries with keys separated by "__". request = self *total, item = map.split("__") for mode in total: # If an intermediate dict does not exist, create it. if mode not in request: request[mode] = {} request = request[mode] request[item] = limit return True def saveAddress( self, customer: str | os.PathLike[str], window: bool = False ) -> bool: """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :meth:`from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. :return: ``True`` if the file was loaded successfully. .. versionadded:: 0.7 `silent` parameter. """ customer = os.path.join(self.root_path, customer) key = types.ModuleType("config") key.__file__ = customer try: with open(customer, mode="rb") as cachedEvent: exec(compile(cachedEvent.read(), customer, "exec"), key.__dict__) except OSError as e: if window and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR): return False e.strerror = f"Unable to load configuration file ({e.strerror})" raise self.fetchConfig(key) return True def fetchConfig(self, age: object | str) -> None: """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. :meth:`from_object` loads only the uppercase attributes of the module/class. A ``dict`` object will not work with :meth:`from_object` because the keys of a ``dict`` are not attributes of the ``dict`` class. Example of module-based configuration:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) Nothing is done to the object before loading. If the object is a class and has ``@property`` attributes, it needs to be instantiated before being passed to this method. You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. See :ref:`config-dev-prod` for an example of class-based configuration using :meth:`from_object`. :param obj: an import name or object """ if isinstance(age, str): age = import_string(age) for map in dir(age): if map.isupper(): self[map] = getattr(age, map) def fetchItem( self, nextUser: str | os.PathLike[str], node: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]], config: bool = False, mode: bool = True, ) -> bool: """Update the values in the config from a file that is loaded using the ``load`` parameter. The loaded data is passed to the :meth:`from_mapping` method. .. code-block:: python import json app.config.from_file("config.json", load=json.load) import tomllib app.config.from_file("config.toml", load=tomllib.load, text=False) :param filename: The path to the data file. This can be an absolute path or relative to the config root path. :param load: A callable that takes a file handle and returns a mapping of loaded data from the file. :type load: ``Callable[[Reader], Mapping]`` where ``Reader`` implements a ``read`` method. :param silent: Ignore the file if it doesn't exist. :param text: Open the file in text or binary mode. :return: ``True`` if the file was loaded successfully. .. versionchanged:: 2.3 The ``text`` parameter was added. .. versionadded:: 2.0 """ nextUser = os.path.join(self.root_path, nextUser) try: with open(nextUser, "r" if mode else "rb") as key: age = node(key) except OSError as e: if config and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = f"Unable to load configuration file ({e.strerror})" raise return self.refreshValue(age) def refreshValue( self, request: t.Mapping[str, t.Any] | None = None, **source: t.Any ) -> bool: """Updates the config like :meth:`update` ignoring items with non-upper keys. :return: Always returns ``True``. .. versionadded:: 0.11 """ localKey: dict[str, t.Any] = {} if request is not None: localKey.update(request) localKey.update(source) for map, event in localKey.items(): if map.isupper(): self[map] = event return True def refreshRecord( self, localItem: str, nextBatch: bool = True, primaryAccount: bool = True ) -> dict[str, t.Any]: """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary `image_store_config` would look like:: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace .. versionadded:: 0.11 """ map = {} for age, size in self.items(): if not age.startswith(localItem): continue if primaryAccount: mode = age[len(localItem) :] else: mode = age if nextBatch: mode = mode.lower() map[mode] = size return map def __repr__(self) -> str: return f"<{type(self).__name__} {dict.__repr__(self)}>"

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.5739.682−189.41
Source linesThe number of non-empty source lines.326+130.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.386−6.579

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.326−10.506
Indentation frequencyHow rapidly indentation changes from line to line.147+4.347
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.325.741+4.143
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.03+0.652
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.83.18+0.538
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.1+0.398
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.83.945+0.11

Intercept 0.07 + feature contributions = -0.249 (log-odds).
Score = sigmoid(-0.249) = 0.438.

Score0.491
Score99
Run 1

The code has a logical class structure and each method follows a similar pattern, but it is severely undermined by confusing naming. Methods like readMessage, validateRequest, saveAddress, fetchConfig, fetchItem, refreshValue, and refreshRecord have names that do not clearly indicate what they do (e.g., saveAddress reads a Python config file). Parameter names (backupMessage, customer, window, age, request, map, mode) are equally opaque, making the control flow hard to follow without reading the docstrings. The docstrings are detailed but describe original names, not the renamed ones, increasing confusion. Nesting is low, which is good, and lines are generally one action each, but the odd variable reuse (e.g., reassigning customer, map) and mixed conceptual roles reduce clarity. The code is not unreadable in terms of structure, but the pervasive naming inconsistency significantly harms intent clarity and reading flow.

Run 2

The code is poorly readable due to misleading naming (readMessage, saveAddress, validateRequest) that obscures the actual Flask config-file functionality. Docstrings reference different parameters than the signatures, creating confusion. Nesting is moderate but traversal logic in validateRequest and refreshRecord is tangled. Variable names like 'map', 'mode', 'age', 'request' are cryptic and reused inconsistently. Some methods are long and mix setup, I/O, error handling, and logic. The reading flow is disrupted by generic type aliases and deprecated patterns. While some structure exists, the intent is ambiguous, and action granularity is uneven.

Run 3

The code shows significant readability problems despite some structural elements being in place. The most critical issue is the misleading naming: methods like 'readMessage', 'validateRequest', 'saveAddress', 'fetchConfig', and 'refreshValue' have no clear relationship to their actual functionality (loading env vars, config files, etc.), making intent extremely ambiguous. Parameter names are equally confusing ('backupMessage' for env var name, 'customer' for filename, 'age' for object, 'map' for key, 'cachedEvent' for file handle). The docstrings describe different parameter names than those actually used, further obscuring understanding. While the code has reasonable flat structure and one-action-per-line granularity, the severe naming mismatches force readers to constantly cross-reference documentation and mentally map between intended and actual names. The class inherits from dict but overrides methods in ways that suggest obfuscation rather than clear design. Technical operations like file loading and env parsing are correct but hidden behind nonsensical abstractions.

Run 1

Code Structure: Methods separate configuration-loading responsibilities logically, with little tangled logic. Nesting: Mostly shallow; early returns and continue statements keep loops manageable, although nested dictionary traversal adds complexity. Clarity of intent: The main weakness is misleading method and variable names such as saveAddress, age, and primaryAccount. Docstrings describe configuration behavior but reference different method and parameter names, creating confusion. The silent keyword passed to saveAddress also conflicts with its window parameter. Code length: Implementations are reasonably concise, but lengthy, outdated docstrings dominate the file and impede scanning. Action granularity: Most lines express one action; the nested compile/exec expression is denser but localized. Reading flow: Consistent formatting, type hints, and conventional control flow help, but arbitrary naming, reused variables, shadowing of map, and documentation mismatches repeatedly interrupt comprehension.

Run 2

1. Code Structure: Well-separated methods organize configuration-loading operations logically. 2. Nesting: Generally shallow; early returns and continue statements keep control flow manageable, although nested environment-key handling adds complexity. 3. Clarity of intent: The main weakness is misleading method and variable names such as saveAddress, age, and primaryAccount. Docstrings reference different method and parameter names, making the interface confusing. The silent keyword passed to saveAddress also conflicts with its window parameter. 4. Code length: Implementation bodies are reasonably concise, but extensive, outdated documentation substantially increases reading effort. 5. Action granularity: Most lines perform one clear operation; the combined read, compile, and exec expression is comparatively dense. 6. Reading flow: Consistent indentation, type hints, and conventional exception handling support readability, but unrelated naming, shadowing the built-in map, and documentation mismatches repeatedly interrupt comprehension.

Run 3

Code Structure: Well-separated methods organize configuration loading, filtering, and extraction logically. Nesting: Mostly shallow, with early returns and continue statements limiting complexity; nested environment traversal remains manageable. Clarity of intent: Severely weakened by misleading names such as saveAddress, age, and primaryAccount. Docstrings reference different method and parameter names, forcing readers to reconcile documentation with implementation. The silent keyword passed to saveAddress also conflicts with its window parameter. Code length: Implementations are reasonably concise, but lengthy, outdated docstrings dominate the listing and increase reading effort. Action granularity: Generally one action per line, although the combined read, compile, and exec expression is comparatively dense. Reading flow: Consistent formatting, type hints, and localized error handling help, but arbitrary naming, reuse of variables for different roles, and shadowing map disrupt comprehension. Overall, sound structural organization is undermined by poor semantic naming and documentation inconsistencies.