I thought Python passed everything by reference?

Take the following code

#module functions.py def foo(input, new_val): input = new_val #module main.py input = 5 functions.foo(input, 10) print input 

I thought the input would be now 10. Why is this not?

+6
source share
4 answers

Everything is passed by value, but this value is a reference to the original object. If you modify the object, the changes are displayed to the caller, but you cannot reassign the names. Moreover, many objects are immutable (ints, float, strings, tuples).

+13
source

Inside foo, you bind the local name input to another object ( 10 ). In the calling context, the name input still refers to object 5 .

+8
source

Assignment in Python does not change the object in place. It restores the name so that after input = new_val local variable input receives a new value.

If you want to change the "external" input , you have to wrap it inside a mutable object, such as a list of one element:

 def foo(input, new_val): input[0] = new_val foo([input]) 

Python does not pass by reference in the same way that a C ++ link works. In this case, at least it's more, as if each argument was a pointer in C / C ++:

 // effectively a no-op! void foo(object *input, object *new_val) { input = new_val; } 
+5
source

Python is neither the default nor the call; it is Call By Object .

"Arguments are passed through sharing, similar to call-by-value, except that the arguments are objects and can only be changed if they are mutable."

+3
source

Source: https://habr.com/ru/post/901810/


All Articles