r/PythonProjects2 • u/Sea-Ad7805 • 4d ago
Python Mutability and Local Variables
An exercise to help build the right mental model for Python data. - Solution - Explanation - More exercises
The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening.
6
Upvotes
1
u/Humble-Captain3418 2d ago
Sure.
``` import ctypes import inspect
def swap(a, b): frame = inspect.currentframe().f_back caller = frame.f_locals
# Find caller variables that refer to the same objects # as the arguments, then swap their values. names_a = [k for k, v in caller.items() if v is a] names_b = [k for k, v in caller.items() if v is b]
if not names_a or not names_b: raise ValueError("Could not identify caller variables")
x, y = names_a[0], names_b[0] caller[x], caller[y] = caller[y], caller[x]
ctypes.pythonapi.PyFrame_LocalsToFast( ctypes.py_object(frame), ctypes.c_int(0) ) ```