Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to pass a reference to a function

Tags:

python

IMO python is pass by value if the parameter is basic types, like number, boolean

func_a(bool_value):
    bool_value = True

Will not change the outside bool_value, right?

So my question is how can I make the bool_value change takes effect in the outside one(pass by reference?

like image 530
Bin Chen Avatar asked Sep 03 '25 14:09

Bin Chen


2 Answers

You can use a list to enclose the inout variable:

def func(container):
    container[0] = True


container = [False]
func(container)
print container[0]

The call-by-value/call-by-reference misnomer is an old debate. Python's semantics are more accurately described by CLU's call-by-sharing. See Fredrik Lundh's write up of this for more detail:

  • Call By Object
like image 83
ars Avatar answered Sep 05 '25 15:09

ars


Python (always), like Java (mostly) passes arguments (and, in simple assignment, binds names) by object reference. There is no concept of "pass by value", neither does any concept of "reference to a variables" -- only reference to a value (some express this by saying that Python doesn't have "variables"... it has names, which get bound to values -- and that is all that can ever happen).

Mutable objects can have mutating methods (some of which look like operators or even assignment, e.g a.b = c actually means type(a).__setattr__(a, 'b', c), which calls a method which may likely be a mutating ones).

But simple assignment to a barename (and argument passing, which is exactly the same as simple assignment to a barename) never has anything at all to do with any mutating methods.

Quite independently of the types involved, simple barename assignment (and, identically, argument passing) only ever binds or rebinds the specific name on the left of the =, never affecting any other name nor any object in any way whatsoever. You're very mistaken if you believe that types have anything to do with the semantics of argument passing (or, identically, simple assignment to barenames).

like image 41
Alex Martelli Avatar answered Sep 05 '25 14:09

Alex Martelli