Python developer reviewing weakref.finalize callbacks and object ownership in a code editor.

A Bound-Method Finalizer Can Keep Its Python Object Alive

Mon, Nov 30, 2026

An owner disappears from its caller. The caller deletes its last ordinary reference, requests garbage collection, and expects fallback cleanup to begin. Nothing happens: the synthetic resource still reports zero release attempts, and a weak-reference probe says the owner remains alive.

That result can be caused by the cleanup registration itself. In particular, weakref.finalize(owner, owner.close) gives the finalizer a bound method whose self is owner. Python’s weakref.finalize documentation explicitly warns that func, args, and kwargs must not own references to the object being finalized, directly or indirectly, and specifically says that func should not be a bound method of that object.

The practical investigation therefore needs three independent observables: object liveness, finalizer state, and resource-release effect. None substitutes for the other two. A live owner can already have released its resource. A dead finalizer can represent either successful cleanup or a failed callback. A detached finalizer can be dead without attempting cleanup at all.

This article defines a bounded CPython 3.13 laboratory for those distinctions. The Python 3.13 documentation identified itself as 3.13.18 when checked on November 30, 2026; that is documentation identity, not evidence of an installed interpreter or a latest-release claim. No fixture described below was executed during preparation. Every behavioral result remains EXPECTED / NOT EXECUTED, with executed=false and observed=null, until the exact script is run and its runtime record retained.

1. Declare the owner-lifetime and resource-release contract

The test object owns one synthetic resource-state dictionary. The dictionary contains only primitive values and a list of strings:

{
    "attempts": 0,
    "released": False,
    "events": [],
    "fail": False,
}

No real file descriptor, socket, database connection, temporary path, thread, subprocess, or operating-system handle participates. Consequently, released=True is only an application-owned receipt produced by this fixture. It does not prove that an operating-system resource would have been closed.

The owner-lifetime contract is deliberately narrow. A builder creates the state and owner, installs exactly one finalizer, disables that finalizer’s shutdown fallback, and returns only a weak probe, the finalizer object, the state, and primitive metadata. Except in cases that explicitly retain the owner, the ordinary owner reference must stop at the builder boundary.

The cleanup contract is separate. For repaired cases, explicit close() must invoke the same finalizer used for fallback cleanup:

def close(self):
    return self._finalizer()

That single invocation gate matters because weakref.finalize.__call__() marks a live finalizer dead before invoking its callback, and later calls to the same finalizer return None. The documented interface therefore supplies an at-most-once invocation gate; it does not establish successful release when the callback itself raises.

Registration is consequently not a cleanup receipt. Acceptance requires evidence about the callback graph and evidence about the resource state.

This ownership problem differs from pytest fixture cleanup ownership, where setup, teardown registration, worker lifetime, and unresolved external resources are the qualification target. That page records cleanup obligations around a test fixture. Here, the disputed edge exists inside weakref.finalize: can callback-owned data keep the referent reachable after its caller has stopped retaining it? The existing pytest article itself distinguishes cleanup registration from confirmed release, but it is not authority for weakref semantics.

2. Trace the strong reference hidden in the bound callback

A weak reference does not, by itself, keep its referent alive. Python documents that when only weak references remain, garbage collection is free to destroy the referent. weakref.finalize, however, stores more than a weak relationship to its target: it also preserves the callable and supplied callback arguments until the finalizer is no longer live. Python therefore warns that the callback payload must not lead back to obj.

For the defective registration

finalize(owner, owner.close)

the important graph is:

Node

Relationship

Ownership significance

finalizer registration

weak relationship to owner as referent

does not itself require owner liveness

finalizer registration

strong callback reference to owner.close

callback data must remain callable

bound method

self refers to owner

strong path returns to the referent

owner

owns state

state is reached through retained owner

The operational path is therefore conceptually:

finalizer callback data
        |
        v
bound method owner.close
        |
        v
method.__self__
        |
        v
owner

That is the path to prove. Repeatedly calling gc.collect() does not remove a still-reachable object merely because the application wished it were unreachable. Python’s data model says objects may be collected when they become unreachable; CPython currently uses reference counting plus cyclic-garbage detection, while collection timing remains implementation-sensitive.

A method's self still points to its owner

Python’s data-model documentation defines an instance-method object as combining a callable and a class instance. Its method.__self__ attribute refers to the instance to which the method is bound. Calling the bound method effectively supplies that instance as the first argument to the underlying function.

That makes these registrations materially different:

finalize(owner, owner.close)

and:

finalize(owner, release, state)

In the first form, the stored callable itself points back to owner. In the second, the callable is a top-level function and its argument is an independent state dictionary. The second arrangement is safe for this laboratory only because the dictionary is defined not to contain the owner, a bound method, a closure over the owner, a traceback, or another object that leads back to the owner.

Replacing a bound method with a free function is therefore not a universal repair. This remains defective:

finalize(owner, release_owner, owner)

because args now retain the owner directly. So does owner=owner in kwargs, and so can a closure cell. The review question is not “is the callback a free function?” It is “does the complete reachable callback payload preserve a strong path back to the referent?” Python’s documentation states exactly that direct-or-indirect constraint.

3. Freeze a noninteractive CPython laboratory

The qualification target is a single-threaded, noninteractive CPython 3.13-series script using only the standard library. The exact runtime is unknown until execution. Documentation rendered as Python 3.13.18 on the review date, but the documentation version must never be copied into an execution record as though it were observed locally.

A later run should retain both shell-level and JSON-level runtime evidence:

python3.13 -VV
python3.13 -c "import platform, sys; print(sys.executable); print(sys.version); print(platform.platform())"
python3.13 weakref_finalize_lab.py | tee weakref_finalize_lab.json

The executable record below captures platform.python_implementation(), sys.version, sys.executable, platform.platform(), platform.system(), platform.release(), and platform.machine(). It also computes SHA-256 identities for the actual script bytes and for the canonical JSON representation of the literal expected manifest.

Before execution, the article’s evidence header is intentionally incomplete:

{
  "batch_date": "2026-11-30",
  "execution_status": "EXPECTED / NOT EXECUTED",
  "executed": false,
  "observed": null,
  "runtime": null,
  "source_sha256": null,
  "manifest_sha256": null
}

Those null values are not omissions to fill with guesses. The source digest belongs to the exact file that is executed, not to an approximation copied from rendered article text. The executable computes both digest values at runtime so the retained JSON can be reconciled with the file actually qualified.

gc.collect() is used only as a controlled collection request. Python 3.13 documents that a no-argument call performs a full collection and returns the sum of collected and uncollectable objects; that integer is not a receipt for application resource cleanup.

The fixture does not use gc.get_referrers() or DEBUG_SAVEALL. The former is explicitly a debugging interface with incomplete visibility into some references, while DEBUG_SAVEALL causes collected objects to be retained in gc.garbage, which would change the lifetime experiment.

Tracing, debugger state, exception tracebacks, notebook result bindings, or saved inspection tuples can also alter reachability. Python’s data model specifically notes that tracing/debugging facilities and caught-exception information may keep objects alive.

4. Implement the literal manifest and primitive-only recorder

The expected manifest must be independently authored before observations are compared against it. It must not calculate its expected values from the state produced by the case under test.

The ten expected behaviors are:

Case

Controlled operation

Expected checkpoint

W01

bound owner.close; builder returns; collect

(true,true,0,false,[])

W02

owner passed positionally to free callback

(true,true,0,false,[])

W03

owner passed through callback kwargs

(true,true,0,false,[])

W04

lambda closes over owner

(true,true,0,false,[])

W05

repaired callback plus fixed self-cycle; collect

(false,false,1,true,["attempt","released"])

W06

explicit close twice while owner retained

first "RELEASED", second None; held (true,false,1,true,...)

W07

explicit callback failure

first raises; second None; (true,false,1,false,["attempt"])

W08

hold detach() tuple

held (true,false,0,false,[]); after tuple deletion owner dies

W09

hold peek() tuple

held (true,true,0,false,[]); tuple deletion allows cleanup

W10

closing(owner) with body failure

cleanup succeeds while owner remains retained

All are EXPECTED / NOT EXECUTED. The expectations follow the documented finalizer and method contracts; they are not presented as measurements.

The following is the proposed complete fixture:

import gc
import hashlib
import json
import platform
import sys
import weakref
from contextlib import closing
from pathlib import Path


class CleanupFailure(RuntimeError):
    pass


class BodyFailure(RuntimeError):
    pass


def fresh_state():
    return {
        "attempts": 0,
        "released": False,
        "events": [],
        "fail": False,
    }


def release(state):
    state["attempts"] += 1
    state["events"].append("attempt")
    if state["fail"]:
        raise CleanupFailure("release failed")
    state["released"] = True
    state["events"].append("released")
    return "RELEASED"


def release_owner(owner):
    return release(owner.state)


class PlainOwner:
    def init(self, state):
        self.state = state


class BadOwner:
    def init(self, state):
        self.state = state
        self._finalizer = weakref.finalize(self, self.close)
        self._finalizer.atexit = False

    def close(self):
        return release(self.state)


class ManagedOwner:
    def init(self, state):
        self.state = state
        self._finalizer = weakref.finalize(self, release, state)
        self._finalizer.atexit = False

    def close(self):
        return self._finalizer()


def checkpoint(probe, finalizer, state):
    return {
        "weak_alive": probe() is not None,
        "finalizer_alive": finalizer.alive,
        "attempts": state["attempts"],
        "released": state["released"],
        "events": list(state["events"]),
    }


EXPECTED = {
    "W01": {
        "checkpoints": {
            "after_collect": {
                "weak_alive": True, "finalizer_alive": True,
                "attempts": 0, "released": False, "events": []
            }
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 0, "released": False, "events": []
        },
    },
    "W02": {
        "checkpoints": {
            "after_collect": {
                "weak_alive": True, "finalizer_alive": True,
                "attempts": 0, "released": False, "events": []
            }
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 0, "released": False, "events": []
        },
    },
    "W03": {
        "checkpoints": {
            "after_collect": {
                "weak_alive": True, "finalizer_alive": True,
                "attempts": 0, "released": False, "events": []
            }
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 0, "released": False, "events": []
        },
    },
    "W04": {
        "checkpoints": {
            "after_collect": {
                "weak_alive": True, "finalizer_alive": True,
                "attempts": 0, "released": False, "events": []
            }
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 0, "released": False, "events": []
        },
    },
    "W05": {
        "checkpoints": {
            "after_collect": {
                "weak_alive": False, "finalizer_alive": False,
                "attempts": 1, "released": True,
                "events": ["attempt", "released"]
            }
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 1, "released": True,
            "events": ["attempt", "released"]
        },
    },
    "W06": {
        "checkpoints": {
            "while_held": {
                "weak_alive": True, "finalizer_alive": False,
                "attempts": 1, "released": True,
                "events": ["attempt", "released"]
            },
            "after_drop": {
                "weak_alive": False, "finalizer_alive": False,
                "attempts": 1, "released": True,
                "events": ["attempt", "released"]
            },
        },
        "returns": {"first": "RELEASED", "second": None},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 1, "released": True,
            "events": ["attempt", "released"]
        },
    },
    "W07": {
        "checkpoints": {
            "while_held": {
                "weak_alive": True, "finalizer_alive": False,
                "attempts": 1, "released": False,
                "events": ["attempt"]
            },
            "after_drop": {
                "weak_alive": False, "finalizer_alive": False,
                "attempts": 1, "released": False,
                "events": ["attempt"]
            },
        },
        "returns": {"second": None},
        "errors": {
            "first": {
                "type": "CleanupFailure",
                "message": "release failed"
            }
        },
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 1, "released": False,
            "events": ["attempt"]
        },
    },
    "W08": {
        "checkpoints": {
            "tuple_held": {
                "weak_alive": True, "finalizer_alive": False,
                "attempts": 0, "released": False, "events": []
            },
            "tuple_dropped": {
                "weak_alive": False, "finalizer_alive": False,
                "attempts": 0, "released": False, "events": []
            },
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 0, "released": False, "events": []
        },
    },
    "W09": {
        "checkpoints": {
            "tuple_held": {
                "weak_alive": True, "finalizer_alive": True,
                "attempts": 0, "released": False, "events": []
            },
            "tuple_dropped": {
                "weak_alive": False, "finalizer_alive": False,
                "attempts": 1, "released": True,
                "events": ["attempt", "released"]
            },
        },
        "returns": {},
        "errors": {},
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 1, "released": True,
            "events": ["attempt", "released"]
        },
    },
    "W10": {
        "checkpoints": {
            "after_context": {
                "weak_alive": True, "finalizer_alive": False,
                "attempts": 1, "released": True,
                "events": ["attempt", "released"]
            },
            "after_drop": {
                "weak_alive": False, "finalizer_alive": False,
                "attempts": 1, "released": True,
                "events": ["attempt", "released"]
            },
        },
        "returns": {},
        "errors": {
            "body": {
                "type": "BodyFailure",
                "message": "body failed"
            }
        },
        "teardown": {
            "weak_alive": False, "finalizer_alive": False,
            "attempts": 1, "released": True,
            "events": ["attempt", "released"]
        },
    },
}


def build_w01():
    state = fresh_state()
    owner = BadOwner(state)
    probe = weakref.ref(owner)
    return probe, owner._finalizer, state, {"retention": "bound_method"}


def build_w02():
    state = fresh_state()
    owner = PlainOwner(state)
    finalizer = weakref.finalize(owner, release_owner, owner)
    finalizer.atexit = False
    probe = weakref.ref(owner)
    return probe, finalizer, state, {"retention": "positional_owner"}


def build_w03():
    state = fresh_state()
    owner = PlainOwner(state)
    finalizer = weakref.finalize(
        owner, release_owner, owner=owner
    )
    finalizer.atexit = False
    probe = weakref.ref(owner)
    return probe, finalizer, state, {"retention": "keyword_owner"}


def build_w04():
    state = fresh_state()
    owner = PlainOwner(state)
    callback = lambda: release(owner.state)
    finalizer = weakref.finalize(owner, callback)
    finalizer.atexit = False
    probe = weakref.ref(owner)
    return probe, finalizer, state, {"retention": "closure_owner"}


def case_w01():
    probe, finalizer, state, = buildw01()
    gc.collect()
    first = checkpoint(probe, finalizer, state)
    finalizer.detach()
    gc.collect()
    return {
        "checkpoints": {"after_collect": first},
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w02():
    probe, finalizer, state, = buildw02()
    gc.collect()
    first = checkpoint(probe, finalizer, state)
    finalizer.detach()
    gc.collect()
    return {
        "checkpoints": {"after_collect": first},
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w03():
    probe, finalizer, state, = buildw03()
    gc.collect()
    first = checkpoint(probe, finalizer, state)
    finalizer.detach()
    gc.collect()
    return {
        "checkpoints": {"after_collect": first},
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w04():
    probe, finalizer, state, = buildw04()
    gc.collect()
    first = checkpoint(probe, finalizer, state)
    finalizer.detach()
    gc.collect()
    return {
        "checkpoints": {"after_collect": first},
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w05():
    state = fresh_state()
    owner = ManagedOwner(state)
    owner.cycle = owner
    probe = weakref.ref(owner)
    finalizer = owner._finalizer
    del owner
    gc.collect()
    first = checkpoint(probe, finalizer, state)
    gc.collect()
    return {
        "checkpoints": {"after_collect": first},
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w06():
    state = fresh_state()
    owner = ManagedOwner(state)
    probe = weakref.ref(owner)
    finalizer = owner._finalizer

    first_result = owner.close()
    second_result = owner.close()
    held = checkpoint(probe, finalizer, state)

    del owner
    gc.collect()
    dropped = checkpoint(probe, finalizer, state)

    return {
        "checkpoints": {
            "while_held": held,
            "after_drop": dropped,
        },
        "returns": {
            "first": first_result,
            "second": second_result,
        },
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w07():
    state = fresh_state()
    state["fail"] = True
    owner = ManagedOwner(state)
    probe = weakref.ref(owner)
    finalizer = owner._finalizer

    error = None
    try:
        owner.close()
    except CleanupFailure as exc:
        error = {
            "type": type(exc).__name__,
            "message": str(exc),
        }

    second_result = owner.close()
    held = checkpoint(probe, finalizer, state)

    del owner
    gc.collect()
    dropped = checkpoint(probe, finalizer, state)

    return {
        "checkpoints": {
            "while_held": held,
            "after_drop": dropped,
        },
        "returns": {"second": second_result},
        "errors": {"first": error},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w08():
    state = fresh_state()
    owner = ManagedOwner(state)
    probe = weakref.ref(owner)
    finalizer = owner._finalizer

    detached = finalizer.detach()
    del owner
    gc.collect()
    held = checkpoint(probe, finalizer, state)

    del detached
    gc.collect()
    dropped = checkpoint(probe, finalizer, state)

    return {
        "checkpoints": {
            "tuple_held": held,
            "tuple_dropped": dropped,
        },
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w09():
    state = fresh_state()
    owner = ManagedOwner(state)
    probe = weakref.ref(owner)
    finalizer = owner._finalizer

    peeked = finalizer.peek()
    del owner
    gc.collect()
    held = checkpoint(probe, finalizer, state)

    del peeked
    gc.collect()
    dropped = checkpoint(probe, finalizer, state)

    return {
        "checkpoints": {
            "tuple_held": held,
            "tuple_dropped": dropped,
        },
        "returns": {},
        "errors": {},
        "teardown": checkpoint(probe, finalizer, state),
    }


def case_w10():
    state = fresh_state()
    owner = ManagedOwner(state)
    probe = weakref.ref(owner)
    finalizer = owner._finalizer

    body_error = None
    try:
        with closing(owner) as alias:
            raise BodyFailure("body failed")
    except BodyFailure as exc:
        body_error = {
            "type": type(exc).__name__,
            "message": str(exc),
        }

    after_context = checkpoint(probe, finalizer, state)

    del alias
    del owner
    gc.collect()
    after_drop = checkpoint(probe, finalizer, state)

    return {
        "checkpoints": {
            "after_context": after_context,
            "after_drop": after_drop,
        },
        "returns": {},
        "errors": {"body": body_error},
        "teardown": checkpoint(probe, finalizer, state),
    }


CASE_ORDER = [
    "W01", "W02", "W03", "W04", "W05",
    "W06", "W07", "W08", "W09", "W10",
]

RUNNERS = {
    "W01": case_w01,
    "W02": case_w02,
    "W03": case_w03,
    "W04": case_w04,
    "W05": case_w05,
    "W06": case_w06,
    "W07": case_w07,
    "W08": case_w08,
    "W09": case_w09,
    "W10": case_w10,
}


def canonical_manifest_bytes():
    return json.dumps(
        EXPECTED,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")


def runtime_record():
    return {
        "implementation": platform.python_implementation(),
        "version": sys.version,
        "executable": sys.executable,
        "platform": platform.platform(),
        "system": platform.system(),
        "release": platform.release(),
        "machine": platform.machine(),
        "gc_debug": gc.get_debug(),
    }


def main():
    if len(CASE_ORDER) != len(set(CASE_ORDER)):
        raise SystemExit("duplicate case ID")

    expected_ids = set(EXPECTED)
    runner_ids = set(RUNNERS)
    ordered_ids = set(CASE_ORDER)

    if expected_ids != runner_ids or expected_ids != ordered_ids:
        raise SystemExit(
            "missing or unexpected case ID: "
            f"expected={sorted(expected_ids)!r} "
            f"runners={sorted(runner_ids)!r} "
            f"order={sorted(ordered_ids)!r}"
        )

    observed = {}
    matches = {}

    for case_id in CASE_ORDER:
        result = RUNNERS[case_id]()
        observed[case_id] = result
        matches[case_id] = result == EXPECTED[case_id]

    source_bytes = Path(__file__).read_bytes()

    output = {
        "batch_date": "2026-11-30",
        "executed": True,
        "runtime": runtime_record(),
        "source_sha256": hashlib.sha256(source_bytes).hexdigest(),
        "manifest_sha256": hashlib.sha256(
            canonical_manifest_bytes()
        ).hexdigest(),
        "case_order": list(CASE_ORDER),
        "expected": EXPECTED,
        "observed": observed,
        "matches_expected": matches,
        "all_expected": all(matches.values()),
    }

    print(json.dumps(output, indent=2, sort_keys=True))


if name == "__main__":
    main()

Observe liveness without retaining the subject

The recorder deliberately evaluates:

probe() is not None

inside the boolean expression. It does not assign probe() to a long-lived variable. Python’s weak-reference documentation recommends testing the referent by calling the weak reference and checking against None; in this single-threaded laboratory, the important additional rule is not to retain the returned owner while measuring its liveness.

The same discipline applies elsewhere. peek() and detach() return tuples containing the object, callback, positional arguments, and keyword arguments. Saving one of those tuples can therefore keep the subject alive. Exception handlers retain only the exception type name and message, then exit before subsequent collection.

Finally, CASE_ORDER, EXPECTED, and RUNNERS are reconciled as sets while duplicate entries in the ordered list are rejected separately. A ten-row report with one missing case and one accidental duplicate is not a qualified ten-case manifest merely because its row count still equals ten.

5. Reproduce retention after the builder returns

W01 tests the exact defective design:

self._finalizer = weakref.finalize(self, self.close)

The builder creates BadOwner, obtains a weak probe, and returns the probe, finalizer, state, and primitive metadata. The owner itself does not cross the builder boundary as an ordinary return value.

The controlled event is then one full gc.collect() request. The expected checkpoint is:

weak_alive       = true
finalizer_alive  = true
attempts         = 0
released         = false
events           = []

This expected result follows from the documented callback-retention warning and bound-method model: the finalizer’s callback data reaches the bound method, whose self reaches the owner. That owner is therefore still reachable through a strong path.

The collection request is not interpreted as “try harder until the object dies.” Python says unreachable objects may be garbage-collected and explains CPython’s reference-counting and cyclic-collection implementation, but a still-reachable object is outside that premise.

W01 is useful precisely because all three observables remain separate. weak_alive=true establishes that the probe can still reach the owner. finalizer_alive=true says the finalizer has not been invoked or detached. attempts=0 independently says the application callback did not begin.

Only after recording those facts does fixture teardown detach the finalizer without storing the returned tuple, then request collection again. That cleanup operation must not overwrite the first checkpoint. The state remains unreleased, because teardown is intended only to dismantle the synthetic retention path; there is no external resource requiring recovery.

A future run that instead produces weak_alive=false, a callback attempt, or any other mismatch should not be massaged into the authored expectation. Record the exact CPython build, preserve the output, and place W01 at HOLD pending reconciliation.

6. Audit positional, keyword and closure capture

W02 through W04 demonstrate why changing syntax without changing ownership does not solve the problem.

Case

Registration shape

Strong path expected to retain owner

W02

finalize(owner, release_owner, owner)

finalizer → positional args → owner

W03

finalize(owner, release_owner, owner=owner)

finalizer → kwargs → owner

W04

finalize(owner, lambda: release(owner.state))

finalizer → function → closure cell → owner

For W02 and W03, release_owner is a genuine top-level helper:

def release_owner(owner):
    return release(owner.state)

The function object itself is independent, but the callback data is not. Python’s finalize documentation warns about all three components (func, args, and kwargs) and explicitly includes indirect ownership.

Accordingly, both cases expect the same checkpoint as W01 after the builder returns and collection is requested:

(true, true, 0, false, [])

No cleanup attempt has begun because the referent remains strongly reachable.

W04 moves the edge into a closure. The lambda body reads owner.state, so the function needs the closure cell that refers to owner. The superficial API call now looks clean (no bound method and no explicit owner argument), but the reachable callback payload still returns to the referent.

These are controlled variations of one defect, not four unrelated leak categories. The review procedure is bounded: inspect the callable, its argument data, and any closure-owned objects for a path back to the owner. It is not a general-purpose heap investigation.

Keep the closure cell intact in the negative control

The W04 builder must return normally without executing:

del owner

inside that same closure-bearing scope.

Deleting the captured binding would empty the cell and create a different experiment. The intended negative control asks whether a closure that genuinely retains the owner can defeat finalization after the builder’s local scope ends. Ordinary function return removes the local execution frame; it does not rewrite the callback function’s captured cell so that the captured object magically disappears.

The executable case therefore creates the lambda, registers it, returns the weak probe and finalizer, and lets the closure itself be the retained path. After the expected defect is captured, teardown calls detach() without saving its result and requests collection.

That sequencing is important for reviewability: first preserve the defective design’s evidence; only then dismantle the diagnostic fixture.

7. Remove the owner from callback-owned data

The repair is small in code but structural in meaning:

class ManagedOwner:
    def init(self, state):
        self.state = state
        self._finalizer = weakref.finalize(self, release, state)
        self._finalizer.atexit = False

    def close(self):
        return self._finalizer()

release is top-level. state is created independently from the owner. The state contains only integers, booleans, strings, and a list of strings, and it never points back to the owner.

This is where evidence ownership matters. A recorder that saves an owner, bound method, traceback, closure, or returned diagnostic tuple can alter the very graph under test. The same broader principle appears in why mock call history retains argument references: evidence structures can preserve object references rather than independent historical values. That article concerns unittest.mock, not weakref; here the recorder therefore copies only primitive release fields at each checkpoint.

W05 adds a deliberate cyclic-collection control:

owner.cycle = owner

The self-cycle is fixed, not optional. After the builder’s ordinary owner reference is removed, a full collection is requested. The expected checkpoint is:

weak_alive       = false
finalizer_alive  = false
attempts         = 1
released         = true
events           = ["attempt", "released"]

This is an expectation for the stated CPython qualification environment, not a portable deadline for every Python implementation. Python’s data model explicitly says collection behavior is implementation-dependent and identifies CPython’s reference counting plus cyclic-garbage detection as an implementation detail.

Check the entire reachable callback payload

The repaired graph should look like:

finalizer
   |
   +--> callback: release
   |
   +--> state dictionary
           |
           +--> primitive values / list of strings

owner --weak finalizer referent relationship--> finalizer machinery

The important absence is a path from callback-owned data back to owner.

A top-level function is necessary for this fixture’s repair design but is not sufficient in isolation. This would recreate the defect:

state["owner"] = owner
finalize(owner, release, state)

because the supposedly independent argument graph would lead back to the referent. Python’s documented rule is about direct or indirect references, not callback naming conventions.

The fixture does not attempt to build an automated arbitrary-object graph auditor. Its contract is simpler and reviewable: the callback receives only the independent toy state, and that state is constrained to primitive evidence.

8. Invoke explicit close while the owner is still alive

W06 proves that deterministic resource release and object death are different events.

The caller deliberately retains owner, then calls:

first = owner.close()
second = owner.close()

Because ManagedOwner.close() delegates to self._finalizer(), the explicit path and fallback path share the same at-most-once gate. Python documents that invoking a live finalizer marks it dead and returns the callback’s result; invoking that finalizer again returns None.

The authored expectations are therefore:

first  == "RELEASED"
second == None

with the owner still retained:

weak_alive       = true
finalizer_alive  = false
attempts         = 1
released         = true
events           = ["attempt", "released"]

This is a useful counterexample to treating object death as the success predicate for deterministic cleanup. The resource-state receipt is already successful while the owner remains fully alive and callable.

After the ordinary owner binding is deleted and collection is requested, only the liveness field is expected to change:

weak_alive       = false
finalizer_alive  = false
attempts         = 1
released         = true
events           = ["attempt", "released"]

There must be no second release attempt.

Routing close() around the finalizer would weaken this contract. For example:

def close(self):
    return release(self.state)

could release once explicitly while leaving the finalizer live to release again later. The repaired API therefore does not merely provide both “close” and “finalize”; it makes them converge on one invocation gate.

That is the API-design point reviewers should preserve: explicit ownership determines when cleanup is requested, while the finalizer remains a fallback. The object can continue to exist after its resource has been deliberately released.

9. Verify exceptional context exit independently

W10 applies the same repaired owner through contextlib.closing:

try:
    with closing(owner) as alias:
        raise BodyFailure("body failed")
except BodyFailure as exc:
    ...

Python documents closing(thing) as effectively a try/finally wrapper that calls thing.close() when the block completes, including when its body exits with an exception.

The expected outcome after context exit is therefore two independent facts. First, BodyFailure survives as the body outcome:

{
  "type": "BodyFailure",
  "message": "body failed"
}

Second, cleanup has its own receipt:

weak_alive       = true
finalizer_alive  = false
attempts         = 1
released         = true
events           = ["attempt", "released"]

The owner remains alive because both owner and the as alias binding still exist after the with statement. Context exit is therefore not expected to make the weak probe dead. The deterministic boundary is the close() call, not object destruction.

This distinction resembles the discipline in Python transaction exit and connection closure, which separately verifies a transaction outcome and a connection-lifetime outcome. That article is about sqlite3, not weakref; the common engineering lesson is simply not to collapse independent postconditions into “the context manager worked.”

After the first checkpoint, W10 explicitly removes both:

del alias
del owner

and requests collection. The expected liveness field then becomes false with no additional release attempt.

The exception recorder stores only class name and message. Python notes that caught-exception state can prolong object lifetime, so the exception object and traceback are not preserved across the later collection checkpoint.

10. Preserve a failed cleanup instead of calling it complete

W07 deliberately changes only one resource-state field:

state["fail"] = True

The first explicit owner.close() enters the finalizer. release() increments attempts, appends "attempt", then raises:

CleanupFailure("release failed")

The documented weakref.finalize.__call__() contract says that if the finalizer is alive, it is marked dead and then the callback is invoked. The expectation therefore is that a callback exception does not restore the same finalizer to the live state for another attempt.

Until actually executed against a recorded runtime, the expected W07 checkpoint remains:

weak_alive       = true
finalizer_alive  = false
attempts         = 1
released         = false
events           = ["attempt"]

The first call is expected to raise CleanupFailure("release failed"). The second owner.close() is expected to return None, because it reaches the now-dead finalizer. Dropping the owner afterward is expected to change only weak_alive; no fallback retry should occur through that same finalizer.

This case is especially important because “at most once” is not “exactly once successfully.” The finalizer has consumed its invocation opportunity, but the resource receipt still reports failure.

A dead finalizer is not a successful release receipt

The three states can be summarized independently:

Situation

f.alive

attempts

released

successful explicit invocation

false

1

true

callback raised during explicit invocation

false

1

false

detach() without callback

false

0

false

Python documents all three mechanisms needed to make those distinctions: call() marks a live finalizer dead before callback evaluation, detach() marks it dead and returns its stored registration tuple, and alive reports registration state rather than application resource state.

A recovery policy therefore needs independently owned resource evidence. It cannot infer successful cleanup from not f.alive.

This laboratory does not prescribe a production retry system. Its bounded conclusion is narrower: if an explicitly invoked cleanup callback fails, preserve the failed release receipt, preserve only non-retaining exception metadata needed by the test, and do not rewrite the event as successful merely because the finalizer is dead.

11. Qualify the side effects of peek and detach

W08 and W09 qualify the observer itself.

For a live finalizer, Python documents:

detach() -> (obj, func, args, kwargs), while marking finalizer dead
peek()   -> (obj, func, args, kwargs), while leaving finalizer alive

Both tuples therefore contain a strong reference to obj while retained by the caller.

W08 saves the detach() tuple, deletes the ordinary owner binding, and requests collection. Its expected checkpoint is:

weak_alive       = true
finalizer_alive  = false
attempts         = 0
released         = false
events           = []

The tuple keeps the owner alive, while detach() has disabled the finalizer without calling release. When the saved tuple is explicitly deleted and collection is requested again, the expected owner liveness becomes false. The resource state remains unreleased.

W09 instead saves peek(). With the ordinary owner binding gone, the tuple again keeps the owner reachable:

weak_alive       = true
finalizer_alive  = true
attempts         = 0
released         = false
events           = []

Deleting the peek() tuple removes that diagnostic strong reference while the finalizer remains registered. The expected later checkpoint is therefore:

weak_alive       = false
finalizer_alive  = false
attempts         = 1
released         = true
events           = ["attempt", "released"]

These cases explain why diagnostic inspection must itself be included in the reference model. A saved peek() result can make a supposedly surprising liveness observation entirely self-inflicted.

Neither API should be presented as a production “retention fix.” detach() changes cleanup policy by unregistering the callback. peek() changes observation state by handing the caller a tuple containing the subject. Their role here is to establish boundary controls around the same reference-graph investigation.

12. Recover the fixture without erasing its first failure

A useful diagnostic does not leave its negative controls permanently retained.

For W01 through W04, recovery happens only after the defect checkpoint has been copied into primitive evidence:

finalizer.detach()
gc.collect()

The returned detach tuple is intentionally not saved. This removes the registration-owned path and allows the synthetic owner to disappear. The teardown record is separate from the original case checkpoint, so a clean laboratory ending cannot retroactively turn the defective registration into an acceptable design.

For W08 and W09, the saved diagnostic tuples are explicitly deleted before the final collection checkpoint. For W06, W07, and W10, retained owner bindings are deliberately deleted only after their “while alive” evidence has been captured.

If a result disagrees with the authored expectation, recovery does not mean editing the manifest. Preserve the unexpected JSON, interpreter identity, source digest, manifest digest, and case ID. Then run a fresh corrected owner in a fresh process if a rerun is warranted.

This laboratory’s in-memory state must also remain visibly separate from actual resource contracts. The neighboring article on temporary-file close and deletion boundaries needs filesystem observations, pathname lifetime, and platform-sensitive behavior because a real temporary file has obligations that released=True cannot represent.

Separate fallback, explicit ownership and shutdown

Every finalizer in this laboratory immediately sets:

finalizer.atexit = False

Python says live finalizers normally participate in interpreter shutdown unless atexit is false. The separate atexit documentation describes exit handlers as normal-termination/shutdown behavior and notes termination modes in which handlers are not called, including an unhandled signal that kills the process, a fatal Python error, and os._exit().

The Python 3.13 atexit page was last updated October 26, 2026 when checked.

Exit-time cleanup is deliberately disabled here because it could conceal the exact defect being tested. Suppose W01 retained its owner for the whole work unit and only ran cleanup during normal interpreter shutdown. That would not establish that fallback cleanup occurred when the caller released its ordinary owner reference.

This fixture does not add signal, forced-process-exit, thread, or subprocess experiments. Its ownership boundary ends before shutdown.

13. Turn the evidence into a maintainable review decision

The ledger should support five decisions rather than a single green/red label.

ACCEPT requires an actually executed, runtime-identified run in which every required case ID is present exactly once, every observed field matches the independently authored expectation, the repaired callback data contains no owner path under the fixture contract, explicit close uses the finalizer gate, and release evidence matches the required case outcome. The present article is not in this state because no execution was performed.

REPAIR applies when the defect is structurally identified and local: a bound callback, positional owner argument, keyword owner argument, closure capture, or supposedly independent callback state that leads back to the owner. Replace owner-bearing callback data with independently owned release state, then rerun the complete manifest.

RECONCILE applies when runtime observations conflict with the resource ledger even though the liveness/finalizer mechanics are understood, for example, a dead finalizer paired with an unexpectedly unreleased state outside the intentionally failing W07 or detached W08 controls. The resource evidence owns that discrepancy; f.alive must not override it.

RERUN applies when the experiment itself was contaminated: a debugger retained the subject, a peek() tuple escaped beyond its intended checkpoint, an exception or traceback was preserved, the script changed without a corresponding digest, case state was reused, or the wrong interpreter was invoked.

HOLD applies when an observation disagrees with the authored expectation and the cause is not yet established, when runtime or source identity is missing, when a case ID is absent, or when ownership of the real application resource cannot be stated. The publication-time fixture status is therefore HOLD: EXPECTED / NOT EXECUTED, not ACCEPT.

Each immutable evidence record should identify a named code/evidence owner in the surrounding engineering process, because maintaining resource ownership includes deciding who reconciles a failed cleanup rather than merely deciding who wrote the class. That operational responsibility sits comfortably beside the wider responsibilities of a backend developer, but that broader career page is context rather than technical authority for weakref.

The bounded review procedure is:

  1. Freeze the exact script, expected manifest, interpreter, platform, and digests.

  2. Establish the caller’s last intended strong owner reference.

  3. Inspect func, positional arguments, keyword arguments, and closure-owned data for any path back to the owner.

  4. Record probe() is not None, finalizer.alive, and primitive release evidence independently.

  5. Capture defect evidence before teardown.

  6. Remove diagnostic retention deliberately and record teardown separately.

  7. Compare all W01–W10 fields literally; do not transform an unexpected result into an expected one.

  8. Decide ACCEPT, REPAIR, RECONCILE, RERUN, or HOLD from the complete record.

This establishes a reference-graph repair, not a generic memory-leak diagnosis. It says nothing about heap growth rates, production leak frequency, operating-system resource guarantees, object resurrection, async cancellation, worker termination, or arbitrary graph traversal. Python itself recommends explicit resource release rather than depending on immediate finalization, which is why the repaired owner exposes deterministic close() in addition to fallback finalization.

14. Extend ownership skills through Refonte Learning

The engineering skill exercised here is broader than memorizing weakref.finalize: define ownership before implementation, make callback data independently reviewable, separate lifetime evidence from side-effect evidence, preserve failures without contaminating the next observation, and make a runtime qualification reproducible.

Refonte Learning’s Software Engineering Program currently lists a three-month duration and a dedication of 12–14 hours per week. Its published curriculum includes full-stack development, cloud computing and microservices, real-time processing, performance optimization, application security, scalable software, the software development lifecycle, software-engineering projects, and a capstone. The page also identifies an educational mentor and states that successful completion offers a Training Certificate and Certificate of Internship. It describes an internship as Potential Internship, not guaranteed placement.

The published page contains inconsistent prerequisite wording: one section accepts pursuing or completed related bachelor’s study, while another says applicants must be working toward a bachelor’s or higher-level degree. That ambiguity should be resolved directly with Refonte Learning for an individual applicant rather than silently inferred.

The page does not establish that the program teaches weakref, this exact lifetime laboratory, or a particular CPython release.

Developers who want to develop the broader software-design, lifecycle, cloud, security, performance, and project skills described in the curriculum can review the Software Engineering Program.