Skip to content Skip to sidebar Skip to footer

Using Exec To Define A Variable, Raises An Nameerror When Referencing It

I'm now running an error (first off I already know that using exec isn't the best option but I'd rather not get into that right now) about a variable being undefined when referenci

Solution 1:

Based on your traceback and previous post, you are using exec within a method of a class like so:

classFoo:
    defbar(self):
        exec('x = "Hello World"')
        print(x)

When exec is executed within a function definition without a parameter for globals, any variables it creates is assigned to a new, temporary namespace, which cannot be accessed. Essentially, your time variable was made in an inner scope (which gets thrown away after exec finishes), and so you cannot access it outside of that scope.

>>> Foo().bar()
Traceback (most recent call last):
  ... 
  File "..\main.py", line 4, in bar
    print(x)
NameError: name 'x' is not defined

Why your previous exec() used to work before is because it only accessed oneMileMark and mutated the list with .append(), and didn't try to assign something new to the variable.

To solve this, you can use eval instead of exec so you can evaluate the expression while keeping your variable assignment remaining in the same scope:

for i in range(numOfRunners):
    if i%4 == 0:
        time_ = eval(f'entry{i}.get()')
        minutes,seconds=time_.split(':')
        ... 

Note: If you were to use exec in the module level (outside of function or class definitions), any variable assignments will work on the global namespace:

>>>exec('x = "Hello World"')>>>x
'Hello World'

Post a Comment for "Using Exec To Define A Variable, Raises An Nameerror When Referencing It"