Reputation: 4099
The main problem I'm running into (specific to Python, don't mark as duplicate for another language please) is that I don't know how to modify a string variable inside a function, with a nested function, if that makes any sense. This code should do a much better job explaining what I mean.
def insideAFunction():
variableToMod = "test"
def modFunc():
if 1 > 0:
variableToMod = "TEST"
print("before: " + variableToMod)
modFunc()
print("after: " + variableToMod)
def insideAFunction2():
variableToMod = "test"
def modFunc():
global variableToMod
if 1 > 0:
variableToMod = "TEST"
print("before: " + variableToMod)
modFunc()
print("after: " + variableToMod)
insideAFunction()
insideAFunction2()
Output:
before: test
after: test
before: test
after: test
The desired output would be:
after: TEST
I know I can get it to work by just defining variableToMod
outside the insideAFunction() and make the global call like in insideAFunction2(), but I want to know if it's possible to do it completely inside the function.
Upvotes: 1
Views: 55
Reputation: 153
Use return function works fine on me:
def insideAFunction():
variableToMod = "test"
def modFunc():
if 1>0:
variableToMod = "TEST"
return variableToMod
print("before: " + variableToMod)
variableToMod = modFunc()
print("after: " + variableToMod)
insideAFunction()
the output is:
before: test
after: TEST
Upvotes: 0
Reputation: 1044
So it will always print the same. You need to return a value from modFunc and assign it to outer variableToMod before printing. This way the result will be
before: test after: TEST
def insideAFunction2(): variableToMod = "test"
def modFunc():
if 1 > 0:
variableToMod = "TEST"
return variableToMod
print("before: " + variableToMod)
variableToMod = modFunc()
print("after: " + variableToMod)
Upvotes: 1
Reputation: 1763
You are probably using Python 3.x (I don't believe this is an issue in Python 2.x), which means you need to use the nonlocal
keyword in your inner functions.
I'm guessing the version using global
doesn't work because you've already defined a local variable with the same name, which would shadow any global variable with that name.
EDIT:
Actually, Python 2.x does have this same behavior, but it doesn't support the nonlocal
statement it seems. I guess one solution might be to pass in the local() dictionary and change the entries in that inside your inner function, but I'm not sure that would work. I'd have to try it out.
Upvotes: 0