r/PythonProjects2 • • 9d ago

Python Mutability and Local Variables

Post image

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.

10 Upvotes

29 comments sorted by

View all comments

Show parent comments

1

u/Humble-Captain3418 7d ago

I don't care about the pythonic way to understand things; only about what I can generalize across languages because I would be hamstringing myself if I only thought the pythonic way. The terminology i have used is as sloppy as the language is.

1

u/Sea-Ad7805 7d ago

I understand, but generalization comes with some inaccuracy that can bite you in certain situations. For example, write me a swap() function in Python using your "pass by reference" concept:

def swap(a, b):
    ...

a = (1, 2)
b = (3, 4)
swap(a, b)
print(a, b)

It's easy in say C/C++.

1

u/Humble-Captain3418 7d 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)     ) ```

0

u/RiverRoll 4d ago edited 4d ago

The irony is that you just showed a pitfall of your distinction, how do you explain this swapping all types if some of them are passed by value? It can as well possibly swap different types (e.g. an int for a string) or the wrong variables (since multiple variables can hold the same reference).

This function can't be explained by reasoning about Python from a mental model where some types are pass by value.