1

I can change a variable by it's name using globals():

k = 2 
def intercommunicationstep(xname, value):
    globals()[xname]=value
    return 1 - q**(k-1)

q = 0.2  
print(intercommunicationstep('k',1))

but for some reason the code is not working with locals() or vars():

def intercommunicationstep(xname, value):
    k = 2
    locals()[xname]=value
    print(locals())
    return 1 - q**(k-1)

q = 0.2 
print(intercommunicationstep('k',1))

it outputs 0.8 instead of 1. I don't want to bother global variables, and prefer to handle this inside function, but alas, I cannot figure this out.

Nick
  • 45
  • 8

1 Answers1

1

It does not look like it's possible for optimization reasons : Any way to modify locals dictionary?.

If you absolutely need to have access to variables by key, you should probably create a dictionary inside of your function instead.

Axnyff
  • 9,213
  • 4
  • 33
  • 37