In this article

A function can return the right result once and still leak state into its next call. This payload-builder example separates a shared mutable default from mutation of a caller’s list, then tests that both ownership problems are repaired.

Start with the second call, not a bigger input

Suppose a notification helper builds a payload with a list of labels. Calling it once for “created” returns the expected result. Calling it next for “sent” unexpectedly returns both labels. More surprisingly, a previously saved payload now also appears to contain “sent”, even though no code explicitly edited that payload.

The smallest useful reproduction is two calls in the same Python process. Keep the function definition, make both calls, and inspect both returned values after the second call. Restarting the process for every case discards the history that triggers the defect. A single-call test with a longer label cannot reveal this particular failure.

Python evaluates a default argument when the function is defined, not on every call. If that default is a list and the function mutates it, later calls that omit the argument reuse the changed object. The Python tutorial explicitly demonstrates this behavior. Python tutorial: default argument values

    Separate shared defaults from caller-owned data

    There are two independent questions. First, does each omitted argument receive fresh working storage? Second, when the caller passes a list explicitly, may the helper modify that caller’s list? Replacing the default with None answers only the first question if the function still appends directly to an explicitly supplied list.

    Our contract is a payload containing a new list of labels for every call. The event and labels are strings. None means no starting labels. Existing labels keep their order, duplicates are allowed, and the event is appended last. The function must not mutate the input list or cause an earlier payload to change after a later call.

    A new dictionary alone does not satisfy that contract. Two dictionaries can contain references to the same list. Assignment creates a binding rather than copying an object, as Python’s copy documentation explains. Python: shallow and deep copy operations Inspect the nested object that actually changes instead of assuming a fresh outer container implies independent contents.

      Run the repeated-call reproduction and repair

      This complete script intentionally defines one broken helper and demonstrates both defects. The corrected helper allocates an empty list for omitted labels or copies a supplied list before appending. Run it in a fresh Python process with assertions enabled. It does not send notifications or make network requests; payloads are ordinary in-memory dictionaries.

      The checks preserve the first fixed result until after the second call, compare explicit caller data against its original value, and compare list identities as well as contents. Identity checks alone would miss a copied but incorrect result. Content checks alone could miss sharing until a later mutation exposes it.

      Reproduce list sharing and verify independent payloads
      Codepython
      def broken_payload(event, labels=[]):
          labels.append(event)
          return {"event": event, "labels": labels}
      
      
      first_bad = broken_payload("created")
      second_bad = broken_payload("sent")
      assert first_bad["labels"] is second_bad["labels"]
      assert first_bad["labels"] == ["created", "sent"]
      supplied_bad = ["priority"]
      broken_payload("queued", supplied_bad)
      assert supplied_bad == ["priority", "queued"]
      
      
      def payload(event, labels=None):
          # Contract: event is a string; labels is None or a list of strings.
          owned_labels = [] if labels is None else list(labels)
          owned_labels.append(event)
          return {"event": event, "labels": owned_labels}
      
      
      first = payload("created")
      second = payload("sent")
      assert first == {"event": "created", "labels": ["created"]}
      assert second == {"event": "sent", "labels": ["sent"]}
      assert first["labels"] is not second["labels"]
      
      supplied = ["priority"]
      third = payload("queued", supplied)
      assert third["labels"] == ["priority", "queued"]
      assert supplied == ["priority"]
      assert third["labels"] is not supplied
      third["labels"].append("reviewed")
      assert supplied == ["priority"]
      assert first["labels"] == ["created"]
      
      empty = []
      fourth = payload("queued", empty)
      assert empty == []
      assert fourth["labels"] == ["queued"]
      assert fourth["labels"] is not empty
      assert payload("queued", None)["labels"] == ["queued"]
      assert payload("priority", supplied)["labels"] == ["priority", "priority"]
      print("Mutable-default and ownership checks passed")

        Why a shallow copy is enough for this contract

        The new list owns its sequence of references. Appending to that list changes neither the supplied list nor another payload’s list. Because labels are strings, the function does not need to clone mutable label objects. The chosen fix matches the stated input domain rather than introducing a general object-copying framework.

        A shallow copy creates a new outer collection while retaining references to its elements; a deep copy recursively copies contained objects. Python: shallow and deep copy operations If labels later become dictionaries and the helper edits one of those dictionaries, this repair needs a new review. The outer-list guarantee cannot be silently extended to nested mutable contents.

        Do not add deepcopy simply to silence uncertainty about ownership. Decide which objects the helper may change, then test that promise with representative inputs. For this API, copying a list of m string labels takes O(m) reference copies and O(m) extra list space. It does not duplicate all the characters stored inside the strings.

          Review an AI fix against the full call sequence

          Give an assistant the two-call reproduction and the explicit-list case together. A useful request is: “Return a new labels list on every call, preserve caller data, keep duplicates and order, and explain why the first result changed.” That provides observable requirements instead of asking for a stylistic rewrite of the signature.

          Reject a patch that clears the shared list before appending. Clearing it still mutates the object held by earlier results. Reject a patch that allocates a list only when the supplied list is empty; nonempty caller lists would still be changed. Test the ownership promise for both empty and nonempty inputs rather than treating truthiness as ownership.

          The conventional None default works because the mutable allocation occurs in the function body. Python tutorial: default argument values But inspect the rest of the patch too: if it replaces None and then aliases an explicit list, it fixes repeated omitted arguments while preserving the caller-mutation bug. The tests need to distinguish those two outcomes.

          When the defect appears only in a larger service, record the order of helper calls and inspect whether their labels lists are identical. Use small synthetic labels for the reproduction. You do not need production notification contents to demonstrate that two results share one object. Once isolated, keep the regression at the helper boundary.

            Common questions about mutable defaults

            Is a mutable default always an accidental bug? Some functions intentionally retain state, but that lifetime must be part of their contract. This payload builder promises independent results, so retaining a shared list violates its purpose. If you need a persistent accumulator, make the state owner visible instead of hiding it inside an optional parameter.

            Would a tuple default solve the issue? An immutable empty tuple can be a suitable default for an iterable-based API, provided the body still builds a new list before appending. It would not by itself settle whether an explicitly supplied mutable list may be changed. The output and ownership requirements remain the useful review target.

            Why did my tests pass individually? A test runner or fixture may recreate the function’s module between cases, or each case may make just one call. Keep the paired-call sequence inside one regression so the relevant lifetime is preserved. Also retain the earlier returned object: checking only the latest result can hide a different sharing failure.

            What should I practice next? Apply the same ownership questions to a dictionary of options or a cache entry. Identify who creates the object, who can mutate it, and how long callers retain references. The related guides below extend that reasoning to stale cache values and small reproductions of stateful bugs.

              Sources & editorial notes

              This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.

              1. Python tutorial: default argument values

                Python tutorial on definition-time default evaluation and mutable arguments. Checked November 4, 2026.

              2. Python: shallow and deep copy operations

                Python copy documentation on object bindings and shallow versus deep copying. Checked November 4, 2026.

              nrml promotion

              Put the reading into practice

              Work through an existing repository, review AI suggestions, and test the decisions behind your changes.

              Explore practice problems