Why Returned Dictionaries Share Mutations in a Backtest
Summary
This debugging example shows why three variables assigned from repeated calls to a function can display the same final dictionary contents. The function updates a global dictionary and returns that same mutable object each time. Each local variable therefore refers to one shared dictionary, so later calls overwrite the value written by earlier calls. The printed results all reflect the final mutation rather than separate snapshots.
The author notes that using a local dictionary avoids the observed behavior and asks for an explanation. The core lesson is object identity and mutation: returning a reference does not create a copy. This matters in backtests or other iterative research code when each result is expected to preserve values from a different run or timeframe. The example is limited to this Python behavior; it does not discuss trading logic or provide a complete comparison of fixes such as constructing a fresh dictionary or copying the object.
Key ideas
- The function returns the same global dictionary object on every call.
- Each subsequent assignment mutates that shared object, changing what all returned references show.
- Returning a mutable object does not automatically make an independent copy.
- Backtest code can produce misleading stored results when separate runs share mutable state.
- Creating a new object or copying data can preserve distinct results across calls.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.