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.

3
  • Use a class instead. Commented Jul 26, 2019 at 12:33
  • what are you even trying to achieve by doing this? wouldn't k = intercommunicationstep(k, 1) work? Commented Jul 26, 2019 at 12:34
  • Possible duplicate of Dynamically set local variable Commented Jul 26, 2019 at 17:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.