assigning variable with exec in class method gives NameError

Viewed 15

I am trying to run this code inside a function:

def method(self, data, **kwargs):

     # parse kwargs thetas to namespace
     for theta, val in kwargs.items():
         print(theta,val)
         exec(f"{theta}={val}")

     print(kwargs)
     print(theta1,theta2)

     # ...

     return 

This gives the following output and then an error:

theta1 0.0001
theta2 0.0001
{'theta1': 0.0001, 'theta2': 0.0001}
NameError: name 'theta1' is not defined

I am running the main code inside a jupyter notebook. And I have no idea why this doesn't work. I thought that exec will define the variable theta1, theta2 and so on. I also tried exec(f"{theta}={val}",globals(),locals()). Didn't work either.

Thanks!

1 Answers

You are getting that error because theta1 and theta2 are not variables, they are keys in kwargs. This is because kwargs is a dictionary. If you want to print the theta values outside the loop the you could use

print(kwargs['theta'], kwargs['theta2'])

instead of

print(theta1,theta2)
Related