Trending

World technology news

→
Freeze import policy snapshots with Python 3.15 frozendict
Software Engineering · 2026
Software Engineering

Freeze import policy snapshots with Python 3.15 frozendict

A Python workflow that captures editable settings at job start, stores immutable required fields, and bounds its cache.

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. Choose when an import policy takes effect
  2. Validate contents before taking the snapshot
  3. Verify the same header with two policy versions
  4. Cache preparation work with an explicit limit
  5. Make reruns and version changes traceable

Choose when an import policy takes effect

A supplier import may require date and sku when it starts. Later the operator might make site mandatory. If the importer rereads the settings before opening each file, one batch can apply two policies. Capture the delimiter, required columns, and tolerance at job start and pass that policy to the rest of the job. The next job can capture the updated version. Python 3.15 was released on October 9, 2026 and added the built-in frozendict type. Its mapping entries cannot be reassigned after construction. Here a frozen policy also acts as a cache key for a small header plan. Attaching a policy version to the job helps explain a rejected file after configuration has changed. The choice of policy for a rerun remains a business decision rather than a side effect of reading current settings.

Validate contents before taking the snapshot

A frozendict does not recursively freeze its contents. A list value can still be changed through another reference, and an unhashable value prevents the mapping from being hashable. This fixture copies required field names into a tuple and validates that they are nonempty strings. It restricts the delimiter and requires a nonnegative integer tolerance. It rejects duplicated field names. Preserving field order keeps missing field diagnostics in the configured order, which is useful when an operator reads them. If ordering is immaterial to another importer, define an appropriate representation explicitly and ensure that its equality suits reuse. When a configuration store can update multiple fields at once, read a consistent configuration version before building an immutable object. The object does not prevent inconsistent reads from its original source during construction.

Application flowConceptual sketch · summary of the article's technical flow

Verify the same header with two policy versions

The script first declares date and sku as required under a semicolon delimiter. It makes an equivalent snapshot from the same rules listed in a different key order. The editable list is then extended with site. A new snapshot knows about the additional field. The old snapshot still requires exactly two fields. All three checks see the header date;sku. The first two pass and the last reports site as missing. In this process and call order, the cache has one hit and two misses. The script can run offline and uses the standard csv reader for the single header line. A complete importer should add cases for empty files, repeated column headers, file encodings, and multiline records. The fixture focuses on the rules at the job boundary and on stable sharing of an equivalent plan.

import csv
from functools import lru_cache

def snapshot(settings):
    delimiter = settings["delimiter"]
    required = settings["required"]
    if not isinstance(required, (list, tuple)):
        raise ValueError("required fields must be a list or tuple")
    fields = tuple(required)
    max_missing = settings["max_missing"]
    if delimiter not in (",", ";"):
        raise ValueError("unsupported delimiter")
    if not fields or any(not isinstance(name, str) or not name for name in fields):
        raise ValueError("required field names must be nonempty strings")
    if len(set(fields)) != len(fields) or type(max_missing) is not int or max_missing < 0:
        raise ValueError("invalid field count or duplicate field")
    return frozendict(delimiter=delimiter, required=fields, max_missing=max_missing)

@lru_cache(maxsize=128)
def header_plan(policy):
    return policy["delimiter"], policy["required"], policy["max_missing"]

def inspect_header(line, policy):
    delimiter, required, max_missing = header_plan(policy)
    column_names = set(next(csv.reader([line], delimiter=delimiter)))
    missing = tuple(name for name in required if name not in column_names)
    return len(missing) <= max_missing, missing

settings = {"delimiter": ";", "required": ["date", "sku"], "max_missing": 0}
old_policy = snapshot(settings)
equivalent = snapshot({"required": ["date", "sku"], "max_missing": 0, "delimiter": ";"})
settings["required"].append("site")
new_policy = snapshot(settings)

results = [inspect_header("date;sku", p) for p in (old_policy, equivalent, new_policy)]
info = header_plan.cache_info()
assert results == [(True, ()), (True, ()), (False, ("site",))]
assert old_policy["required"] == ("date", "sku")
assert (info.hits, info.misses, info.currsize) == (1, 2, 2)
print(results)
print(info)

Cache preparation work with an explicit limit

The demonstration caches a plan containing the delimiter, required field sequence, and missing count limit. It does not need to cache a supplier file. Preparing this small plan is inexpensive, so the example makes no performance claim. A larger import could prepare mapping or validation steps for each policy. Measure preparation cost and frequency of reuse before enabling the cache. The example bounds it at 128 entries, where least recently used entries can eventually be evicted. Count and size are distinct measures when cached plans grow. A configuration change can produce a new snapshot and cache key. If the interpretation changes independently from settings, also preserve the application version for reproducibility. A Python hash serves local hashing. A durable cross-process policy identity needs a deliberately specified representation, encoding, and version.

Make reruns and version changes traceable

A rejected file should carry the job ID, source version, and applicable policy version alongside its missing fields. Decide whether a correction replays the original business rules or applies the current policy. Run the same header under both configurations and keep both outcomes for review. This helps an operator separate policy differences from parser changes. Before rolling it out, check the Python version in the deployment runtime. Confirm that unrecognised delimiters, empty field lists, duplicated columns, and malformed headers produce the expected operator experience. Keep a snapshot available across validation, reporting, and any retry that is considered part of the same run. If the business requires a gradual rollout within one batch, carry the applicable policy ID with each classified record. The stable object then supports traceability without forcing every batch to follow the same rollout rule.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.