4 ms·
Everything is by value. Passing by reference means this is possible: def change_param(ab): ab = 768 x = 12 print(x) change_param(x)
by pjmlp 2y ago
Everything is by value.
Passing by reference means this is possible:
def change_param(ab):
ab = 768
x = 12
print(x)
change_param(x)
print(x)
Expected output in reference parameters, 12 followed by 768.
Otherwise it is always a value, even if the value happens to be a reference to an heap allocated object.
Python has no mechanism to change the contents of the x variable used as parameter on call site.
- graemep 2y agoYou can do that if the parameter is a list: def change(l): l[1] = 'x' >>> foo = [1,2,3] >>> foo [1, 2, 3] >>> changel(foo) >>> foo [1, 'x', 3]
- pansa2 2y agoYou can't change which list `foo` refers to, though. Only the contents of that list. `foo` is a reference to a list, and that reference is passed by value.
- pjmlp 2y agoNow make foo point to another list, not change contents of the list foo points to. Passing by reference requires changing the variable itself, used on the call site.
- zahlman 2y agoThis does a fundamentally different thing with similar syntax. Assignment in Python is fundamentally a rebinding operation; slice assignment rebinds a reference internal to the object, whereas ordinary assignment rebinds the name. The classic test: in Python you cannot write a generic "swap function" - you could only possibly write a function to swap the internal states of the arguments, presuming them to be compatible.
- pansa2 2y ago> even if the value happens to be a reference to an heap allocated object IIRC in CPython, the value is always a reference to an object. Other implementations might pass immutable objects directly by value, but the semantics is the same as passing a reference to the object by value.
- zahlman 2y agoYou are correct. (I'd be surprised if other implementations passed immutable objects by value, partly because representing an "object" coherently requires several words of memory and partly because of the importance of certain object identity semantics.) Python uses pass-by-value (if you prefer, pass-by-assignment) of variables which have reference semantics. Just like non-primitive types in Java, or class types in C#.
- pansa2 2y ago> I'd be surprised if other implementations passed immutable objects by value I'm thinking of MicroPython here - it supports several pointer-tagging schemes, in which "references" might be actual pointers or might instead be immutable values stored directly. For example, using the NaN-boxing scheme, MicroPython references might actually be inline `float`s, small `int`s, or constants like `None`, `True` or `False`.