4

I create the file mymod.py :

def myfunc():
    s = """
users = ['root','service']
flag = True
c_list_with_test = [ u for u in users if flag ]
print(c_list_with_test)
"""
    exec(s)
    print('ok')

With python2 there is no problem :

$ python2
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.myfunc()
['root', 'service']
ok

But with python3 list comprehension test variable is undefined :

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.myfunc()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/elapouya/tmp/mymod.py", line 8, in myfunc
    exec(s)
  File "<string>", line 4, in <module>
  File "<string>", line 4, in <listcomp>
NameError: name 'flag' is not defined
>>>

Why ? What is the workaround ?

Note : if I do not use import or exec, all is working fine. This is really the combinaison import+exec that creates the problem.

Eric
  • 4,821
  • 6
  • 33
  • 60
  • 3
    https://stackoverflow.com/questions/15086040/behavior-of-exec-function-in-python-2-and-python-3 – Rakesh Jun 20 '19 at 08:37
  • 1
    Look carefully : in my case, both `users` and `flag` variables are set only in exec : the variable `users` is seen as defined but not `flag` : why ? the question you proposed does not answers. it does not speak about importing neither. – Eric Jun 20 '19 at 08:52
  • @Eric I want to say, in the [list comprehension in exec with empty locals: NameError](https://stackoverflow.com/questions/45132645/list-comprehension-in-exec-with-empty-locals-nameerror) , [this answer](https://stackoverflow.com/a/45196415/7025361) is better than the accepted one. – LiuXiMin Jun 20 '19 at 10:50

0 Answers0