I have this class:
class MyClass:
def __init__(self):
self.execute()
def execute(self):
exec('self.myVar = 1') in MyClass()
When I try to call
exec('self.myVar = 1') in MyClass()
I get:
TypeError: exec: arg 2 must be a dictionary or None
What am I doing wrong?
From the documentation
If only the first expression after
inis specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, both must be dictionaries and they are used for the global and local variables, respectively.
So basically, the expressions after in are supposed to be globals() and locals() with any additional keys you want to be in scope during the exec statement. Essentially, you use in to define an execution scope for exec, as in execute this statement in these namespaces.
Semantically, it's equivalent to eval(statement, globals, locals)
In your case, you can just leave out the in MyClass() clause completely.
Note that eval/exec leave you vulnerable to arbitrary code execution if you're not the one constructing the statement string (I assume your code example is a toy sample meant to illustrate your problem), so keep that in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With