Home > database >  Python How to Pass string to function by reference
Python How to Pass string to function by reference

Time:11-11

def foo(arg1,arg2,arg3)
   arg3="new_value"
   return arg1 arg2
arg3=""
foo(1,2,arg3)

And I still get "" in arg3 after calling foo(). I want to get arg3=="new_value". How do I do that?

CodePudding user response:

Python always receives parameters by value, so assigning a new value to a parameter variable inside the body of a function won't affect the caller.

If the value is mutable, then mutating it inside the body of the function will affect the caller, but strings are immutable (there's no method you can call on a string that will change its contents, only return a new string).

In general, the way to approach the situation you describe is to simply return multiple values:

def foo(arg1,arg2,arg3)
   arg3="new_value"
   return arg1 arg2, arg3
arg3=""
_, arg3 = foo(1, 2, arg3)

If you need an immutable argument to be mutable, though, an easy workaround (that doesn't involve using global) is to wrap it in a mutable container, like a list:

def foo(arg1,arg2,arg3)
   arg3[0]="new_value"
   return arg1 arg2
arg3=[""]
foo(1,2,arg3)
# arg3[0] is now "new_value"

CodePudding user response:

To manipulate an outside-function variable, you either have to return it, or use it as a global variable:

return

def foo(arg1, arg2, arg3):

    arg3 = "new_value"
    return arg1   arg2, arg3

arg3 = ""
first_return, arg3 = foo(1, 2, arg3)

global

def foo(arg1, arg2):
    
    global arg3
    arg3 = "new_value"
    return arg1   arg2

arg3 = ""
first_return = foo(1, 2)
  • Related