python - exec() with nested loop in list comprehension inside function error -


exec() inside function gives different output, pass parameter needed function. consider code:

def list_filter(expr,datalist,includelist) :     exec(expr)     print outlist   datalist=['try kill me','black image'] includelist=['me'] expr="outlist = [i in datalist if  all(j in j in includelist)  ]" exec(expr) print outlist list_filter(expr,datalist,includelist) 

i have checked similar case here : how exec work locals?

but different error, i'm using version 2.7.13 , check under general condition, exec() has no error @ all. found problem shows when there's 'nested loop' inside list comprehension statement, such using all() or any(). in case , if remove if condition list comprehension (make expr = "outlist = [i in datalist ]") correct output usual.

any idea why?

almost it's bad idea use exec in case shouldn't use @ all.

but since asked: works correctly if pass in variables local scope:

def list_filter(expr, datalist, includelist):     exec(expr, locals())     print outlist 

i'm not familiar scope rules exec found need pass in variables explicitly (especially if exec isn't in global scope).

in case pass them in explicitly:

def list_filter(expr, datalist, includelist):     exec(expr, {'datalist': datalist, 'includelist': includelist})     print outlist 

it's stated in documentation may need pass variables scope exec:

the built-in functions globals() , locals() return current global , local dictionary, respectively, may useful pass around use exec.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -