Zach Gates
Zach Gates

Reputation: 4130

Why won't exec define my variable?

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?

Upvotes: 3

Views: 2314

Answers (1)

aruisdante
aruisdante

Reputation: 9075

From the documentation

If only the first expression after in is 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.

Upvotes: 4

Related Questions