list comprehension with test in exec after import does not work in python3

Viewed 54

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.

0 Answers
Related