0

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!

  • I would personally avoid using exec and just access the data like `kwargs['theta1']`, is there a reason why you can't do that? – SitiSchu Sep 12 '22 at 13:11
  • I suggest that you don't pursue this avenue in programming. Please see the answers to this [question](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – quamrana Sep 12 '22 at 13:12
  • `theta1`, `theta2` are not defined. – D.L Sep 12 '22 at 13:51

1 Answers1

0

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)
  • i removed the asterisks in the signature, not sure if that's what you meant, but it does not change anything. whats even more puzzling is that further below, i assign the values of theta that i previously defined with exec to some other variables, again with exec: ```exec("someObject.attribute=theta1")```. This successfully runs and assigns the value. Just printing doesnt work. So, it seems exec is operating with the theta1 theta2 in some other namespace, where it recognizes them after defining them with exec, but they are not defined in the local scope? very strange to me.. – user19976975 Sep 12 '22 at 13:37