Using Exec To Define A Variable, Raises An Nameerror When Referencing It
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"