top | item 41220165

(no title)

azundo | 1 year ago

Is python no longer a modern language? Objects are certainly not copied when passed to a function.

discuss

order

jerf|1 year ago

Python copies references by value.

    $ python3
    Python 3.12.3 (main, Jul 31 2024, 17:43:48) [GCC 13.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def x():
    ...     v = 1
    ...     y(v)
    ...     print(v)
    ... 
    >>> def y(val):
    ...     val += 1
    ... 
    >>> x()
    1
A pass-by-reference language would print 2.

Everything in a modern language is passed by copy. Exactly what is copied varies and can easily be pointers/references. But there were languages once upon a time that didn't work that way. It's a dead distinction now, though, unless you go dig one of them up.

If you want a specific one to look at, look at Forth. Note how when you call a function ("invoke a word", closest equivalent concept), the function/word doesn't get a copy of anything. It directly gets the actual value. There is no new copy, no new memory location, it gets the actual same memory as the caller was using, and not as a "pointer"... directly. Nothing works like that any more.

rtpg|1 year ago

C++ is a live language, C# has out parameters.... there's stuff out there.

The classic example of "pass by copy-reference is less expressive" is you can't have pass a reference to number and have the caller modify it. You have to explicitly box it. I understand you understand this, but it's worth considering when thinking about whether the distinction means absolutely nothing at all.

froh|1 year ago

uh I'd not say it like that

Python passes primitive types by value, out rather "as if by value", because it copies them on write.

if you modify your experiment to pass around a dict or list and modify that in the 'y', you'll see y is happily modified.

so Python passes by reference, however it either blocks updates (tuple) or copies on write (int, str, float) or updates in place (dict, list, class)