-2
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?

Nikky Leed
  • 1
  • 1
  • 2
  • you need to use a `return` to bring value outside function. or `global` – Mahrkeenerh Nov 10 '21 at 13:11
  • 1
    All arguments are passed by value. – khelwood Nov 10 '21 at 13:13
  • See [changing global variables within a function in python](https://stackoverflow.com/q/51564669/3890632) – khelwood Nov 10 '21 at 13:13
  • 1
    Objects are always "passed by reference", as far as that description even makes sense in Python. However, strings are *immutable* so it's entirely impossible to do what you want. – MisterMiyagi Nov 10 '21 at 13:14
  • Note that it's very important to say whether you expect ``arg3=="new_value"`` to work because the string *assigned to* ``arg3`` was mutated or because ``arg3`` was assigned a new object. – MisterMiyagi Nov 10 '21 at 13:20

2 Answers2

2

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"
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

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)
Mahrkeenerh
  • 1,104
  • 1
  • 9
  • 25