Hi,
Is there any way I can convert a string into a variable name in the client code?
I was able to do so in the sever code with globals():
globals()[‘sam’] = 5
print(sam)
However, this didn’t work in the celint code, I got this error:
NameError: name ‘sam’ is not defined
I even tried:
globals()[‘self.sam’] = 5
print(self.sam)
and I got this error:
AttributeError: ‘Form1’ object has no attribute ‘sam’
I have also tried exec():
from math import *
x=‘sam’
exec(“%s = %d” % (x,5))
print(sam)
which didn’t work in both (the server and client codes):
NameError: name ‘exec’ is not defined
Any help is appreciated…
…to solve what problem?
There’s usually more than one way to solve a problem. If we understand the problem, we may be able to offer a workable suggestion.
Well, multiple things, for example: calling a client method using a string (instead of writing multiple lines of code to call a method. Also, it will allow to generating variables dynamically…
on the client globals is read only and exec is not supported. (It should be clearer that globals is read only because in python changing the globals object works)
So I’d create a dictionary object rather than trying to turn strings into variables.
You could use self.__dict__
if you want to add them directly to the form. Or use the self.tag
property.
Or just create a global dict somewhere.
1 Like