Python backend developer comparing original and reconstructed dataclass objects while reviewing dataclasses.replace code.

Why dataclasses.replace Recomputes Fields You Expected to Keep

Wed, Dec 2, 2026

A backend caller asks for an “updated” JobSpec, changes one constructor field, and expects the new object to keep a warmed transient list. dataclasses.replace() returns a new object, but that warmed state disappears. That is not, by itself, evidence of a dataclasses defect. The documented contract is reconstruction: the replacement object is created through the dataclass constructor, which means generated initialization runs again and __post_init__() runs again when present. init=False fields are not copied from the source; required InitVar context must be supplied; an init=False field with a default factory is initialized again through the generated constructor.

This article tests one boundary only: constructor-driven reconstruction versus retention of the source instance’s current state. I used three ordinary mutable dataclasses with generated constructors, no inheritance, no slots, no custom copying protocol, and deterministic in-memory traces. The local research run was real: CPython 3.13.5, executable /opt/pyvenv/bin/python3.13, platform Linux-6.18.64-x86_64-with-glibc2.41, fixture revision 2026-12-02-r2. The separately researched Python 3.13 documentation identified itself as 3.13.18; that is a documentation observation, not the interpreter patch tested here.

The important result is not a blanket pass. Nine behavioral controls aligned with the authored manifest, but D06 exposed a version/documentation discrepancy: the 3.13.18 docs specify ValueError when replace() is asked to change an init=False field, while the local 3.13.5 run raised TypeError. The reconciler therefore exited nonzero with HOLD_CONFLICTING_EVIDENCE. That is exactly the sort of outcome an operational validation harness should preserve rather than smooth over.

1. Declare what the caller expects the replacement to preserve

Before running replace(), I want the caller to state what “preserve” means. Otherwise a technically correct reconstruction can be mislabeled as data loss simply because the caller had an undocumented state-retention expectation.

The fixture separates four categories.

Category

Fixture examples

Caller must decide before execution

Ordinary constructor fields

job_id, units, unit_cost, tags, x

Retain the source value unless explicitly changed, or supply another approved input

Derived init=False fields

derived_total, scaled

Recompute from approved constructor context, or reject reconstruction if current stored state must be retained

Runtime-only mutable state

transient

Reset through construction, transfer explicitly, or retain via a separate copy policy

Construction-only context

factor: InitVar[int]

Supply an approved value, accept its declared default, or hold when the original value is unavailable

That table is a caller contract, not a description of what Python will necessarily do. The documented mechanics come later. The engineering decision comes first.

For this article, a successful constructor call is not sufficient for acceptance. D02 can produce a valid new JobSpec while failing a caller contract that requires the warmed transient == ["warm"] state. Conversely, D03 can change derived_total from 20 to 30 and be exactly correct when the caller’s policy is to reconstruct derived state from the approved new units=3.

The available policy outcomes are deliberately narrow:

RECONSTRUCT_WITH_APPROVED_INPUTS means constructor semantics are desired and every needed construction input is known.

RETAIN_STATE_UNDER_EXPLICIT_COPY_POLICY means selected current state must survive, with aliasing rules reviewed separately.

HOLD_MISSING_CONTEXT means reconstruction requires construction-only context that is unavailable or evidence conflicts.

REPAIR_CALLER_EXPECTATION means the library behavior is documented, but the caller incorrectly assumed replacement meant state retention.

That distinction prevents “different value after replace” from automatically becoming “library bug.”

2. Follow reconstruction through the documented lifecycle

The central rule is unusually explicit. Python 3.13’s dataclasses.replace() documentation says the returned object is created by calling the dataclass init(), which in turn causes __post_init__() to run for classes using the generated constructor. The same section says init=False fields are not copied from the source object; they are initialized again through the normal lifecycle, if they are initialized at all.

PEP 557 shows that this was an intentional design decision rather than an accidental side effect. An earlier design would have copied init=False fields after constructing the destination, but that approach was rejected because it could overwrite a freshly recomputed derived value with stale state from the original. The PEP’s example uses a derived area value to illustrate why post-construction copying would contradict constructor semantics.

That makes dataclasses.replace init=False a lifecycle question, not a generic field-update question. If derived_total is calculated in __post_init__(), replacement is supposed to give __post_init__() another opportunity to calculate it from the replacement constructor inputs. If a runtime cache is represented by an init=False default-factory field, the generated initializer invokes that factory again. Python’s default-factory section specifically says an init=False field with default_factory always has that factory called from the generated init().

This differs from the adjacent problem covered in Pydantic model-copy validation boundaries. There, the operational question is whether an update path revalidates model data. Here construction does run; the question is what lifecycle state that reconstruction produces.

Distinguish constructor inputs from current instance state

Three inventories answer three different questions.

dataclasses.fields() tells us about true dataclass fields, and it omits InitVar pseudo-fields. Python documents that InitVar names are constructor parameters passed to __post_init__() but are not returned by fields().

inspect.signature(Class) tells us what arguments the callable accepts. A Signature contains ordered Parameter objects, and the test Parameter.default is Parameter.empty distinguishes required parameters from parameters with defaults.

The live instance tells us current stored state.

Those are not interchangeable. DefaultScale.factor has a class-level constructor default of 10, so inspect.signature(DefaultScale) can show factor=10. But an instance created with factor=100 does not thereby retain “100” as an ordinary instance field. A generated signature proves call shape; it does not prove the state semantics a caller wants from replacement.

3. Freeze a small, observable Python environment

The research date is 2026-12-02, Africa/Nairobi. The local execution used only the Python standard library.

Recorded runtime:

implementation: CPython
python patch:   3.13.5
executable:     /opt/pyvenv/bin/python3.13
platform:       Linux-6.18.64-x86_64-with-glibc2.41
fixture:        2026-12-02-r2
execution:      EXECUTED
final status:   HOLD_CONFLICTING_EVIDENCE

The documentation consulted during research was the versioned Python 3.13 branch whose page header reported 3.13.18. That newer documentation identifier must not be presented as the locally tested interpreter.

Run these commands before trusting a local reproduction:

python3.13 -V
python3.13 -c 'import sys, platform; print(sys.executable); print(platform.platform())'
python3.13 dataclass_replace_lab.py > dataclass_replace_lab.json
printf 'exit=%s\n' "$?"

The complete script below is standard-library-only. It defines exactly three dataclasses and includes the independent expectation manifest, D01–D10 runners, primitive snapshots, constructor inventory, and evidence reconciler.

from future import annotations

from copy import copy
from dataclasses import InitVar, MISSING, dataclass, field, fields, replace
from inspect import Parameter, signature
import json
import platform
import sys
from typing import Any

REV = "2026-12-02-r2"
TRACE: list[tuple[Any, ...]] = []

def transient_factory() -> list[str]:
    TRACE.append(("factory", "JobSpec.transient"))
    return []

@dataclass
class JobSpec:
    job_id: str
    units: int
    unit_cost: int
    tags: list[str]
    derived_total: int = field(init=False)
    transient: list[str] = field(init=False, default_factory=transient_factory)

    def __post_init__(self) -> None:
        self.derived_total = self.units self.unit_cost
        TRACE.append(("post_init", "JobSpec", self.job_id,
                      self.units, self.unit_cost, self.derived_total))

@dataclass
class RequiredScale:
    x: int
    factor: InitVar[int]
    scaled: int = field(init=False)

    def __post_init__(self, factor: int) -> None:
        self.scaled = self.x factor
        TRACE.append(("post_init", "RequiredScale", self.x, factor, self.scaled))

@dataclass
class DefaultScale:
    x: int
    factor: InitVar[int] = 10
    scaled: int = field(init=False)

    def __post_init__(self, factor: int) -> None:
        self.scaled = self.x * factor
        TRACE.append(("post_init", "DefaultScale", self.x, factor, self.scaled))

def reset() -> None:
    TRACE.clear()

def job_snap(x: JobSpec) -> dict[str, Any]:
    return {
        "job_id": x.job_id,
        "units": x.units,
        "unit_cost": x.unit_cost,
        "tags": list(x.tags),
        "derived_total": x.derived_total,
        "transient": list(x.transient),
    }

def scale_snap(x: RequiredScale | DefaultScale) -> dict[str, Any]:
    return {"x": x.x, "scaled": x.scaled}

def new_job() -> JobSpec:
    x = JobSpec("job-a", 2, 10, ["ready"])
    x.transient.append("warm")
    return x

def inventory(cls: type) -> dict[str, Any]:
    return {
        "class": cls.__name__,
        "fields": [
            {
                "name": f.name,
                "init": f.init,
                "default": f.default is not MISSING,
                "default_factory": f.default_factory is not MISSING,
            }
            for f in fields(cls)
        ],
        "signature": str(signature(cls)),
        "parameters": [
            {
                "name": n,
                "required": p.default is Parameter.empty,
                "default": None if p.default is Parameter.empty else repr(p.default),
            }
            for n, p in signature(cls).parameters.items()
        ],
    }

EXPECTED = {
    "D01": {"total": 20, "transient": ["warm"]},
    "D02": {"total": 20, "transient": [], "trace_delta": 2},
    "D03": {"candidate_total": 30, "source_total": 20},
    "D04": {"tags_shared": True},
    "D05": {"tags_shared": False},
    "D06": {"documented_exception": "ValueError", "trace_delta": 0},
    "D07": {"total": 20, "transient": ["warm"], "trace_delta": 0},
    "D08": {"candidate": None, "trace_delta": 0},
    "D09": {"candidate_scaled": 30, "trace_delta": 1},
    "D10": {
        "omit_factor": 30,
        "explicit_factor_100": 300,
    },
}

def run() -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []

    reset()
    s = new_job()
    out.append({"case_id": "D01", "source": job_snap(s),
                "trace_delta": len(TRACE), "expected": EXPECTED["D01"]})

    reset()
    s = new_job()
    before = job_snap(s)
    mark = len(TRACE)
    c = replace(s)
    out.append({"case_id": "D02", "source_before": before,
                "source_after": job_snap(s), "candidate": job_snap(c),
                "new_identity": c is not s, "tags_shared": c.tags is s.tags,
                "transient_shared": c.transient is s.transient,
                "trace_delta": len(TRACE) - mark, "expected": EXPECTED["D02"]})

    reset()
    s = new_job()
    mark = len(TRACE)
    c = replace(s, units=3)
    out.append({"case_id": "D03", "source": job_snap(s),
                "candidate": job_snap(c), "trace_delta": len(TRACE) - mark,
                "expected": EXPECTED["D03"]})

    reset()
    s = new_job()
    mark = len(TRACE)
    c = replace(s)
    shared = c.tags is s.tags
    c.tags.append("candidate-added")
    out.append({"case_id": "D04", "source": job_snap(s),
                "candidate": job_snap(c), "tags_shared": shared,
                "intended_source_change": True,
                "trace_delta": len(TRACE) - mark, "expected": EXPECTED["D04"]})

    reset()
    s = new_job()
    mark = len(TRACE)
    c = replace(s, tags=list(s.tags))
    shared = c.tags is s.tags
    c.tags.append("candidate-added")
    out.append({"case_id": "D05", "source": job_snap(s),
                "candidate": job_snap(c), "tags_shared": shared,
                "trace_delta": len(TRACE) - mark, "expected": EXPECTED["D05"]})

    reset()
    s = new_job()
    before = job_snap(s)
    mark = len(TRACE)
    c = None
    error = None
    try:
        c = replace(s, derived_total=777)
    except Exception as exc:
        error = {"class": type(exc).__name__, "message": str(exc)}
    out.append({"case_id": "D06", "source_before": before,
                "source_after": job_snap(s), "candidate_completed": c is not None,
                "exception": error, "trace_delta": len(TRACE) - mark,
                "expected": EXPECTED["D06"]})

    reset()
    s = new_job()
    mark = len(TRACE)
    c = copy(s)
    out.append({"case_id": "D07", "source": job_snap(s),
                "candidate": job_snap(c), "new_identity": c is not s,
                "tags_shared": c.tags is s.tags,
                "transient_shared": c.transient is s.transient,
                "trace_delta": len(TRACE) - mark, "expected": EXPECTED["D07"]})

    reset()
    s = RequiredScale(2, factor=10)
    before = scale_snap(s)
    mark = len(TRACE)
    c = None
    error = None
    try:
        c = replace(s, x=3)
    except Exception as exc:
        error = {"class": type(exc).__name__, "message": str(exc)}
    out.append({"case_id": "D08", "source_before": before,
                "source_after": scale_snap(s), "candidate_completed": c is not None,
                "exception": error, "trace_delta": len(TRACE) - mark,
                "context": {"original_factor": 10, "replacement_factor": "OMITTED"},
                "expected": EXPECTED["D08"]})

    reset()
    s = RequiredScale(2, factor=10)
    mark = len(TRACE)
    c = replace(s, x=3, factor=10)
    out.append({"case_id": "D09", "source": scale_snap(s),
                "candidate": scale_snap(c), "trace_delta": len(TRACE) - mark,
                "context": {"original_factor": 10, "replacement_factor": 10},
                "expected": EXPECTED["D09"]})

    branches = {}
    for name, factor in (("omit_factor", None), ("explicit_factor_100", 100)):
        reset()
        s = DefaultScale(2, factor=100)
        mark = len(TRACE)
        c = replace(s, x=3) if factor is None else replace(s, x=3, factor=factor)
        branches[name] = {
            "source": scale_snap(s),
            "candidate": scale_snap(c),
            "trace_delta": len(TRACE) - mark,
            "context": {
                "original_factor": 100,
                "replacement_factor": "OMITTED" if factor is None else factor,
            },
        }
    out.append({"case_id": "D10", "branches": branches,
                "expected": EXPECTED["D10"]})
    return out

def reconcile(rows: list[dict[str, Any]]) -> list[str]:
    errors: list[str] = []
    ids = [r["case_id"] for r in rows]
    required = [f"D{i:02d}" for i in range(1, 11)]
    if len(ids) != len(set(ids)):
        errors.append("duplicate case ID")
    if missing := sorted(set(required) - set(ids)):
        errors.append(f"missing cases: {missing}")
    by_id = {r["case_id"]: r for r in rows}
    if set(by_id) != set(required):
        return errors

    def need(ok: bool, msg: str) -> None:
        if not ok:
            errors.append(msg)

    need(by_id["D01"]["source"]["derived_total"] == 20, "D01 total")
    need(by_id["D02"]["candidate"]["transient"] == [], "D02 transient")
    need(by_id["D02"]["trace_delta"] == 2, "D02 trace")
    need(by_id["D03"]["candidate"]["derived_total"] == 30, "D03 total")
    need(by_id["D03"]["source"]["derived_total"] == 20, "D03 source")
    need(by_id["D04"]["tags_shared"] is True, "D04 alias")
    need(by_id["D04"]["source"]["tags"] == ["ready", "candidate-added"], "D04 source")
    need(by_id["D05"]["tags_shared"] is False, "D05 alias")
    need(by_id["D05"]["source"]["tags"] == ["ready"], "D05 source")

    d6 = by_id["D06"]
    need(not d6["candidate_completed"], "D06 candidate")
    need((d6["exception"] or {}).get("class") == "ValueError",
         "D06 documented ValueError not observed")
    need(d6["trace_delta"] == 0, "D06 trace")
    need(d6["source_before"] == d6["source_after"], "D06 source")

    d7 = by_id["D07"]
    need(d7["trace_delta"] == 0, "D07 trace")
    need(d7["candidate"]["transient"] == ["warm"], "D07 transient")
    need(d7["tags_shared"] and d7["transient_shared"], "D07 aliases")

    d8 = by_id["D08"]
    msg = (d8["exception"] or {}).get("message", "")
    need(not d8["candidate_completed"], "D08 candidate")
    need("InitVar" in msg and "factor" in msg, "D08 attribution")
    need(d8["trace_delta"] == 0, "D08 trace")
    need(d8["source_before"] == d8["source_after"], "D08 source")

    d9 = by_id["D09"]
    need(d9["candidate"]["scaled"] == 30, "D09 scaled")
    need(d9["source"]["scaled"] == 20, "D09 source")

    d10 = by_id["D10"]["branches"]
    need(set(d10) == {"omit_factor", "explicit_factor_100"}, "D10 branches")
    if set(d10) == {"omit_factor", "explicit_factor_100"}:
        need(d10["omit_factor"]["candidate"]["scaled"] == 30, "D10 omit")
        need(d10["explicit_factor_100"]["candidate"]["scaled"] == 300, "D10 explicit")
    return errors

def rejection_controls(rows: list[dict[str, Any]]) -> dict[str, bool]:
    missing = [r for r in rows if r["case_id"] != "D09"]
    duplicate = rows + [rows[0]]

    no_branch = json.loads(json.dumps(rows))
    next(r for r in no_branch if r["case_id"] == "D10")["branches"].pop(
        "explicit_factor_100"
    )

    altered = json.loads(json.dumps(rows))
    next(r for r in altered if r["case_id"] == "D03")["candidate"]["derived_total"] = 31

    return {
        "reject_omitted_case": bool(reconcile(missing)),
        "reject_duplicate_id": bool(reconcile(duplicate)),
        "reject_missing_d10_branch": bool(reconcile(no_branch)),
        "reject_altered_expected_total": bool(reconcile(altered)),
    }

def main() -> int:
    if sys.implementation.name != "cpython" or sys.version_info[:2] != (3, 13):
        print(json.dumps({
            "status": "HOLD_WRONG_RUNTIME",
            "python": platform.python_version(),
            "executable": sys.executable,
        }, indent=2))
        return 2

    rows = run()
    errors = reconcile(rows)
    controls = rejection_controls(rows)
    if not all(controls.values()):
        errors.append("reconciler rejection control failed")

    status = "PASS_10_CASES" if not errors else "HOLD_CONFLICTING_EVIDENCE"
    print(json.dumps({
        "fixture_revision": REV,
        "runtime": {
            "python": platform.python_version(),
            "executable": sys.executable,
            "platform": platform.platform(),
        },
        "inventory": [inventory(JobSpec), inventory(RequiredScale), inventory(DefaultScale)],
        "records": rows,
        "reconciler_controls": controls,
        "errors": errors,
        "status": status,
    }, indent=2, sort_keys=True))
    return 0 if status == "PASS_10_CASES" else 1

if name == "__main__":
    raise SystemExit(main())

Inventory fields, signatures, and constructor-only inputs

The local generated signatures were equivalent to:

JobSpec(job_id: str, units: int, unit_cost: int, tags: list[str])
RequiredScale(x: int, factor: dataclasses.InitVar[int])
DefaultScale(x: int, factor: dataclasses.InitVar[int] = 10)

The meaningful inventory is:

Class

Name

Kind

init field?

Stored by fields()?

Context policy

JobSpec

job_id

ordinary

yes

yes

retain unless changed

JobSpec

units

ordinary

yes

yes

approved replacement input

JobSpec

unit_cost

ordinary

yes

yes

retain unless changed

JobSpec

tags

ordinary mutable

yes

yes

aliasing policy required

JobSpec

derived_total

derived

no

yes

recompute

JobSpec

transient

runtime mutable

no

yes

fresh factory state under reconstruction

RequiredScale

factor

required InitVar

constructor-only

no

must be supplied to replacement

DefaultScale

factor

defaulted InitVar

constructor-only

no

omission means constructor default 10

The separation matters because fields() intentionally omits InitVar, while inspect.signature() exposes callable parameters and their defaults. For a broader interface-testing discussion, real Python call-signature checks are related reading, but signature compatibility alone still does not tell us whether a replacement preserves the state contract the caller requires.

The input manifest should therefore live separately from object snapshots. If a required constructor-only value is missing, the operational response is not to reverse-engineer it from a derived field; it is to hold the reconstruction.

4. Build the baseline job and its evidence record

D01 establishes the fixture rather than performing replacement:

source = JobSpec(
    job_id="job-a",
    units=2,
    unit_cost=10,
    tags=["ready"],
)
source.transient.append("warm")

Construction calls transient_factory(), producing a fresh empty list and one deterministic trace event. The generated initializer then invokes __post_init__(), which computes derived_total = units * unit_cost = 20 and appends another deterministic trace event. The explicit warm-up operation happens after construction and changes transient to ["warm"].

That distinction is the whole test. transient == ["warm"] is current instance state, not a constructor input. derived_total == 20 is also current state, but it has an authored production rule: the constructor lifecycle computes it from units and unit_cost.

Python documents both pieces of that mechanism: generated init() calls __post_init__(), and an init=False default factory runs from generated initialization.

Capture primitive snapshots before any mutation

The evidence record copies list contents immediately:

{
    "tags": list(source.tags),
    "transient": list(source.transient),
}

It does not store source.tags itself in the ledger. Otherwise D04’s later intentional list mutation would rewrite the “before” evidence and make the ledger useless.

Identity is recorded independently with id() or direct is checks. Object equality is not used as a substitute for lifecycle evidence. Two objects can compare equal while one was reconstructed through a fresh factory and the other retained an already-warmed list.

D01 acceptance requires a primitive snapshot showing units=2, unit_cost=10, derived_total=20, tags=["ready"], and transient=["warm"]. The local execution produced those values. Its trace contained the expected factory and post-init events before warm-up. This baseline establishes only this fixture; it makes no claim about dataclasses with custom constructors, inheritance, slots, frozen semantics, or user-defined copy protocols.

5. Replace without changes, then change one constructor input

D02 calls:

candidate = replace(source)

The documentation says replacement creates a new object through init(). The local observation matched that reconstruction model: candidate identity differed from source identity; derived_total was 20 again; the transient factory ran again; candidate transient was [], not the source’s warmed ["warm"]; and the reconstruction trace gained two events.

This is the first useful operational boundary. “No requested changes” does not mean “copy every current attribute exactly.” It means “construct another instance using the source values for eligible constructor fields.”

D03 starts from a separately constructed and separately warmed source:

candidate = replace(source, units=3)

Expected independent arithmetic is 3 × 10 = 30. The local run produced candidate units=3, derived_total=30, and a fresh empty transient. Its source remained units=2, derived_total=20, transient=["warm"].

That changed derived value is not evidence of corruption. It is exactly what PEP 557’s rejected init=False copying design was intended to preserve: a replacement should allow constructor/post-init logic to generate state consistent with the new constructor inputs rather than overwrite it with stale derived state.

The before/after contract for D02 and D03 is therefore:

Case

Source before

Requested change

Candidate expected

Source after

D02

total 20, transient warm

none

total 20, transient fresh

unchanged

D03

units 2, total 20

units=3

units 3, total 30

units 2, total 20

Both cases completed successfully in the local run.

6. Attempt to preserve a field the constructor owns

D06 deliberately tries to override the derived field:

replace(source, derived_total=777)

The Python 3.13.18 dataclasses.replace() documentation states that putting an init=False field in changes is an error and specifically documents ValueError. PEP 557 states the same historical contract.

The local CPython 3.13.5 run did not produce that documented exception class. It produced:

TypeError
field derived_total is declared with init=False, it cannot be specified with replace()

The candidate did not complete. The source primitive snapshot remained unchanged. The construction trace did not advance beyond the baseline checkpoint.

Those latter observations are useful, but they do not convert D06 into a pass. The authored D06 acceptance criterion intentionally requires the documented ValueError. Because the tested interpreter raised a different exception class, the evidence reconciler records D06 documented ValueError not observed and exits nonzero.

That is the correct operational handling of a source/runtime disagreement: preserve both facts and hold. Do not silently rewrite the expectation after seeing the result.

Explain why an explicit field edit is rejected

The rejection is tied to init=False. It is not evidence that Python evaluated int annotations, ran business validation, or enforced immutability. The replace() contract excludes those fields from caller-supplied changes because they are outside the constructor-input surface documented for reconstruction.

If a product requirement says callers should be able to specify a formerly derived value directly, that is an API-design discussion. Possible redesigns include making the value an ordinary constructor field or providing a separate class-level operation with explicit semantics. What I would not do is teach the caller to inject internal state around replace() and then pretend constructor invariants were preserved.

7. Bound the reference-sharing comparison

Constructor reconstruction does not imply deep copying of constructor inputs. D04 demonstrates that with tags.

A fresh source starts with tags=["ready"]. D04 executes replace(source), then verifies:

candidate.tags is source.tags

The local result was True. That makes sense within this fixture: tags is an ordinary constructor field, so replacement supplies the source’s current tags object to the new constructor. The constructor stores that reference; nothing in this fixture copies it.

D04 then intentionally performs:

candidate.tags.append("candidate-added")

Afterward both source and candidate show:

["ready", "candidate-added"]

This source mutation is expected and must be labeled as such. Reporting “source remained unchanged” for D04 would be false.

D05 changes only the replacement input policy:

candidate = replace(source, tags=list(source.tags))

Now candidate and source receive distinct flat lists. The local candidate.tags is source.tags observation was False. Appending "candidate-added" to the candidate left the source at ["ready"].

Nothing else about reconstruction changed: post-init still ran, derived_total was recomputed, and transient came from a fresh factory call.

This is a deliberately narrow aliasing control, not a deep-copy tutorial. The related failure mode in tests, where a stored reference later reflects mutation, is covered separately in mutable references in recorded mock arguments. Here the point is simply that constructor reconstruction and reference isolation are separate properties.

8. Compare a shallow copy with a reconstructed object

D07 uses:

candidate = copy(source)

For the deliberately plain fixture, the local shallow-copy observation was materially different from D02. Candidate identity was new, but there were no new factory or post-init trace events. derived_total remained 20, transient remained ["warm"], and both tags and transient were shared references.

That result is consistent with the standard copy documentation’s definition of a shallow copy: it creates a new compound object and, to the extent possible, inserts references to objects found in the original.

The important separation is:

  • retaining transient’s current value is one fact;

  • retaining the same transient identity is another.

For D07, both happened. A caller that wants the warmed value but requires an independent list would still need an explicit state-transfer policy.

I would not generalize this case to every class. Python’s copy module allows classes to customize copy behavior through copy/pickle-related protocols, so this observation is bounded to these plain dataclasses with no custom copying hooks.

That is why RETAIN_STATE_UNDER_EXPLICIT_COPY_POLICY must be an engineering policy, not shorthand for “use copy.copy() everywhere.”

9. Reconstruct only with known construction context

RequiredScale isolates construction-only context:

@dataclass
class RequiredScale:
    x: int
    factor: InitVar[int]
    scaled: int = field(init=False)

    def __post_init__(self, factor: int) -> None:
        self.scaled = self.x * factor

Python documents InitVar as an init-only pseudo-field: it is accepted by generated initialization, passed to __post_init__(), and omitted from fields(). The replace() section separately states that init-only variables without defaults must be provided during replacement.

D08 constructs a valid source with x=2, factor=10, yielding scaled=20, then attempts:

replace(source, x=3)

The local run failed before a candidate completed. The captured CPython 3.13.5 diagnostic was:

TypeError
InitVar 'factor' must be specified with replace()

This exact class and message are reported because they came from the real run; they are not inferred from documentation.

D08 is accepted as the expected negative control only in conjunction with D09. D09 uses the same original context but explicitly supplies it:

replace(source, x=3, factor=10)

That completed with scaled=30, one new post-init trace event, and an unchanged source at scaled=20.

Taken together, D08 and D09 support a specific conclusion: the failed reconstruction was attributable to omitted required construction context, and supplying approved context made the requested reconstruction succeed. If D09 had also failed, D08 would not be enough evidence to diagnose “missing InitVar” as the operational cause.

Compare omitted and explicit defaulted InitVar inputs

DefaultScale makes the subtler case visible:

@dataclass
class DefaultScale:
    x: int
    factor: InitVar[int] = 10
    scaled: int = field(init=False)

The source is created with x=2, factor=100, producing scaled=200. The factor 100 is not a true stored dataclass field. The class signature has a constructor default of 10. Python’s InitVar documentation supports the distinction between constructor-only pseudo-fields and stored fields, while inspect.Parameter.default tells us what default the callable will use when the argument is omitted.

D10 has two mandatory branches.

Omitting replacement factor:

replace(source, x=3)
produced scaled=30.

Supplying approved factor explicitly:

replace(source, x=3, factor=100)
produced scaled=300.

Both source objects remained at scaled=200.

The first branch is the dangerous one for callers who think “updated object” implicitly means “use whatever construction context created the old object.” It does not. A visible class-level default of 10 is evidence about what omission means for the new constructor call; it is not evidence that the original explicit 100 was retained.

Do not recover factor by calculating scaled / x. That would turn a derived value into allegedly authoritative construction context, which is exactly the provenance problem this lab is designed to avoid.

10. Reconcile all ten cases against an independent manifest

The manifest is authored before interpretation and the reconciler compares meaningful sub-assertions rather than one opaque Boolean.

The executed ledger is:

Case

Source / context

Requested change

Identity / trace / alias evidence

Expected

Actual status

D01

JobSpec 2 × 10; warmed transient

none

baseline factory + post-init trace

total 20; transient ["warm"]

OBSERVED as expected

D02

fresh warmed JobSpec

none

new identity; trace +2; tags shared; transient not shared

total 20; transient reset []

OBSERVED as expected

D03

fresh warmed JobSpec

units=3

new identity; trace +2

candidate total 30; source total 20

OBSERVED as expected

D04

fresh warmed JobSpec

none

tags shared

candidate tag mutation also changes source

OBSERVED as expected; source change intentional

D05

fresh warmed JobSpec

explicit list(source.tags)

tags not shared

candidate mutation isolated from source

OBSERVED as expected

D06

fresh warmed JobSpec

derived_total=777

no candidate; trace +0

documented ValueError

CONFLICT: local 3.13.5 raised TypeError

D07

fresh warmed JobSpec

shallow copy

new identity; trace +0; tags/transient shared

warmed state retained

OBSERVED as expected

D08

RequiredScale(2, factor=10)

x=3, factor omitted

no candidate; trace +0

required context blocks reconstruction

OBSERVED negative control

D09

RequiredScale(2, factor=10)

x=3, factor=10

new candidate; trace +1

candidate scaled 30

OBSERVED as expected

D10

source created with factor 100

branch A omit; branch B explicit 100

post-init +1 each

A → 30; B → 300

both OBSERVED as expected

This table is deliberately not reduced to “9 pass, 1 fail” as the main finding. Each case answers a different lifecycle question.

D02 proves fresh runtime state can be produced even when visible derived values happen to match the source. D03 proves recomputation can correctly change an init=False value. D04 proves reconstruction does not imply isolation of mutable constructor references. D07 distinguishes state retention under shallow copy from constructor reconstruction. D08–D10 expose construction context that the object’s ordinary field inventory cannot reconstruct.

D06 is also important precisely because it did not satisfy the expected documentation contract on the tested patch. The Python 3.13.18 docs and PEP 557 both document ValueError for supplying an init=False change. The local 3.13.5 run’s TypeError is therefore recorded as a conflict, not rewritten as compliant evidence.

11. Reject incomplete evidence and accidental cross-case state

A lifecycle lab is only useful if the evidence validator fails when the ledger is incomplete.

The script includes four reconciler controls:

  1. Remove D09 and require rejection for a missing case.

  2. Duplicate D01 and require rejection for a duplicate case ID.

  3. Remove one D10 branch and require rejection because both omitted-factor and explicit-factor observations are mandatory.

  4. Change D03’s observed total from 30 to 31 and require rejection against the independent arithmetic expectation.

All four rejection controls succeeded locally. The top-level script still exited nonzero because D06 conflicted with the documented expected exception class.

Fresh source construction per case matters too. D04 intentionally mutates its source through shared tags. If D05 reused that source, the case would start with contaminated evidence and could produce a technically correct but misleading result. This is the same general reason isolating mutable pytest parameters matters in test design, but this lab does not use pytest or parameter-order experiments.

The release rule is simple: incomplete IDs, duplicate IDs, missing D10 branches, expectation conflicts, unresolved runtime metadata, or unexplained trace changes must produce a nonzero exit and a hold state. Evidence should fail closed.

12. Choose a reconstruction or retention policy

Once the mechanics are observable, the caller still needs a policy decision.

Decision

Required evidence

Primary owner

Next action

RECONSTRUCT_WITH_APPROVED_INPUTS

Constructor fields known; required InitVar context known; recomputed state accepted

Caller + class owner

Call replace() with explicit approved context; record candidate

RETAIN_STATE_UNDER_EXPLICIT_COPY_POLICY

Specific current state must survive; aliasing rules declared

Caller owner

Use a separately reviewed copy/state-transfer path

HOLD_MISSING_CONTEXT

Required construction-only value unavailable, runtime/documentation conflict, or incomplete evidence

Reviewer / release owner

Retain source; collect context or revalidate runtime

REPAIR_CALLER_EXPECTATION

Documented reconstruction is correct but caller assumed snapshot semantics

Caller owner

Change caller contract, tests, or API naming/documentation

For D03, a caller wanting “new units and a new matching total” should choose RECONSTRUCT_WITH_APPROVED_INPUTS.

For D02, a caller requiring the already-warmed transient list should not approve ordinary replacement merely because construction succeeded. That requirement points toward RETAIN_STATE_UNDER_EXPLICIT_COPY_POLICY or toward redesigning which state belongs on the object.

For D08, if the original factor cannot be obtained from an approved input manifest, the correct policy is HOLD_MISSING_CONTEXT.

For D06 in this exact research run, the overall evidence state is also a hold because the tested patch and the researched 3.13.18 documentation disagree on the exception class.

python-databases-replace-first-img

Preserve the original before attempting recovery

Recovery begins from the retained source, not from a failed candidate.

Keep the original object, a primitive before-snapshot, and the approved construction-context manifest. Do not overwrite the D08 or D06 evidence record when trying a second path. Create another identified candidate and another evidence record.

The fixture has intentionally inert construction effects: only deterministic in-memory trace entries are appended. In production code, discarding an object cannot be assumed to reverse constructor side effects. This fixture therefore supports lifecycle reasoning without pretending that object abandonment provides transaction rollback.

A bounded recovery procedure is:

  1. Freeze the failed evidence record and retain the original object.

  2. Identify whether the failure concerns constructor fields, derived state, runtime state, or InitVar context.

  3. Obtain missing context only from an approved source; never infer it backward from a derived value.

  4. Select one of the four caller policies.

  5. Create a new candidate under that policy.

  6. Capture a new primitive snapshot, identity observations, trace delta, and context manifest.

  7. Reconcile the new evidence independently; do not erase the earlier failure.

That procedure keeps provenance visible.

13. Turn the result into a maintainable object-lifecycle contract

The class owner should document four things for each relevant dataclass: which attributes are constructor fields, which are derived init=False fields, which are runtime/transient state, and which inputs are construction-only context. The class owner should also document constructor effects, especially factories and __post_init__() work, because replacement invokes that lifecycle for the generated-constructor classes examined here.

The caller owner has a different responsibility: declare what an “updated object” must preserve. If warmed caches, accumulated instrumentation state, retry metadata, or other runtime state matters to correctness, that requirement must be explicit. Otherwise a reviewer has no principled way to distinguish a correct reconstruction from a broken caller expectation.

The reviewer owns evidence completeness. I would require the field/context inventory, runtime patch, executable, platform, fixture revision, D01–D10 ledger, both D10 branches, exception observations from real runs, and reconciler status before accepting a lifecycle-sensitive change.

Revalidation should be triggered when any of these change:

  • a constructor default;

  • a new init=False field or default factory;

  • a new or changed InitVar;

  • __post_init__() logic;

  • caller aliasing requirements;

  • or a newly customized copy protocol.

The small fixture supports conclusions only for ordinary mutable dataclasses with generated constructors, no inheritance, no slots, and no user-defined copying behavior. It intentionally does not cover frozen dataclasses, custom init, ORM persistence, Pydantic validation, authorization, deep-copy policy, concurrency, copy.replace(), or third-party dataclass systems.

The operational choice can be summarized once: use dataclasses.replace() when you want another instance produced through the approved constructor lifecycle; do not treat it as an implicit promise to retain every current value on the source instance. The current Python documentation explicitly frames replacement around constructor execution, post-init execution, required InitVar inputs, and non-copying of init=False fields. A documented reconstruction result can therefore be correct while violating an undocumented caller expectation.

The one unresolved item in this run is D06’s exception-class discrepancy. Until the target deployment patch is tested against the same acceptance criterion, that discrepancy remains a legitimate hold rather than something to explain away.

14. Develop the backend foundations behind this review

Object-lifecycle reviews like this sit on top of broader backend habits: explicit interfaces, deterministic fixtures, input provenance, state ownership, testing, and debugging. Refonte Learning’s Backend Developer Program currently lists a three-month period, 10–12 hours per week, and basic programming knowledge as the entry requirement. Its published curriculum names Node.js and Express, MongoDB and SQL, REST APIs and microservices, authentication and authorization, backend testing/debugging, Docker/cloud deployment, and a capstone. The page also describes hands-on projects and potential internship exposure, and says successful completion is associated with a Training Certificate and Certificate of Internship.

The program page lists backend developer, API developer, and database administrator as career directions; those are program outcomes described by the page, not employment guarantees.

For readers building the language layer first, Refonte’s Python development foundations provides broader Python context. The useful connection is not that this exact experiment is promised in the syllabus; it is that backend engineering becomes more reviewable when state contracts, constructor boundaries, debugging evidence, and testing discipline are treated as first-class design work.