Reputation: 10507
I tried to modify the value of a string inside a function, like below:
>>> def appendFlag(target, value):
... target += value
... target += " "
...
>>> appendFlag
<function appendFlag at 0x102933398>
>>> appendFlag(m,"ok")
>>> m
''
Well, seems the "target" is only changed within the function, but how to make the new value viable outside the function? Thanks.
Upvotes: 8
Views: 42485
Reputation: 1
Make a new class and set the target as the member of class. Then try setattr(class, 'target', value).
Upvotes: 0
Reputation: 27
Mutable data types, such as lists or dictionaries, can be changed from within the function without returning:
def duplicate_last(l):
l.append(l[-1])
l = [1, 2, 3]
duplicate_last(l)
The reason for that is different memory management for mutable and immutable objects in python.
Upvotes: 3
Reputation: 941
The variables inside the function has got only function scope, if you change the value of the variable from inside the function it wont get reflected outside the function. If you want to change the value of the global variable m, update it from outside the function as follows
def appendFlag(target, value):
target += value
target += " "
return target
m=''
m=appendFlag(m,'ok')
Upvotes: 1
Reputation: 7510
This is handled in python by returning.
def appendFlag(target, value):
target += value
target += " "
return target
you can use it like this:
m = appendFlag(m,"ok")
you can even return several variables like this:
def f(a,b):
a += 1
b += 1
return a,b
and use it like this:
a,b = f(4,5)
Upvotes: 5
Reputation: 94
You need to use an object that can be modified
>>> m = []
>>> def appendFlag(target, value):
... target.append(value)
... target.append(" ")
...
>>> appendFlag(m, "ok")
>>> m
['ok', ' ']
Upvotes: 3
Reputation: 511
Your function needs to return the new value.
The target
variable only has scope within the appendFlag
function.
def appendFlag(target, value):
...
return target
m = appendFlag(m, "ok")
Upvotes: 0