Hello everyone! I hope this video has helped solve your questions and issues. This video is shared because a solution has been found for the question/problem. I create videos for questions that have solutions. If you have any other issues, feel free to reach out to me on Instagram: / ky.emrah
Below, you can find the text related to the question/problem. In the video, the question will be presented first, followed by the answers. If the video moves too fast, feel free to pause and review the answers. If you need more detailed information, you can find the necessary sources and links at the bottom of this description. I hope this video has been helpful, and even if it doesn't directly solve your problem, it will guide you to the source of the solution. I'd appreciate it if you like the video and subscribe to my channel!exec inside a function and generator
I need to write a custom exec function in python (for several purposes but this is not the problem here, so this custom exec which is called myExec will do exactly as exec for now).
myExec
exec
I went into this problem :
def myExec(code):
exec(code)
code = """
a = 1
print(a)
u = [a for x in range(3)]
print(u)
"""
myExec(code)
def myExec(code):
exec(code)
code = """
a = 1
print(a)
u = [a for x in range(3)]
print(u)
"""
myExec(code)
Running this program gives
1
Traceback (most recent call last):
File "___.py", line 12, in module
myExec(code)
File "___.py", line 2, in myExec
exec(code, globals(), locals())
File " string ", line 4, in module
File " string ", line 4, in listcomp
NameError: name 'a' is not defined
1
Traceback (most recent call last):
File "___.py", line 12, in module
myExec(code)
File "___.py", line 2, in myExec
exec(code, globals(), locals())
File " string ", line 4, in module
File " string ", line 4, in listcomp
NameError: name 'a' is not defined
So print(a) went without any problems. But the error occurs with the line u = [a for x in range(3)]. When the generator object is converted into a list, the name a seems undefined.
print(a)
u = [a for x in range(3)]
a
Note that if the line were u = [a, a, a], then, no error is raised. Nor if we use exec instead of myExec.
u = [a, a, a]
exec
myExec
Any reason why and how to solve this ?
Tags: python,generator,execSource of the question:
https://stackoverflow.com/questions/7...
Question and source license information:
https://meta.stackexchange.com/help/l...
https://stackoverflow.com/