Exec command does not work in python

1

Well, I am not able to execute external functions (with exec) that will change global lists so that it is used in my main function, follows code:

m = []
n = []

def mp((a,b),p):
   c = [n[0] for n in p]
   d = [z.index for z in c if (a == z)]

   if len(d) == 1 and ((((sum(p) - p[d[0]]) + b) % 5) == 0 ):
           return m.append((((sum(p) - p[d[0]]) + b),d[0]))
   elif len(d) > 1 :
       return ( m.append((((sum(p) - p[d[i]]) + b),d[i])) for i in d if ((sum(p) - p[d[i]]) + b) % 5 == 0 ) 
   elif ( len(d) == 0 ):
       return m.append(None)

def mp2((a,b),p):
   c = [n[0] for n in p]
   e = [k.index for k in c if (b == z)]

   if len(e) == 1 and ((((sum(p) - p[e[0]]) + a) % 5) == 0 ):
       return  n.append((((sum(p) - p[e[0]]) + a),e[0]))
   elif len(e) > 1 :
       return ( n.append((((sum(p) - p[e[i]]) + a),e[i])) for i in e if ((sum(p) - p[e[i]]) + a) % 5 == 0 ) 
   elif ( len(e) == 0 ):
       return n.append(None)

def maior_ponto((a,b),p):
   g = mp((a,b),p)
   h = mp2((a,b),p)
   exec(g)
   exec(h)
   u = (m+n)
   return(r[1] for r in u if max(r[0]))

The error returned in the terminal is:

python bloco313.py
  File "bloco313.py", line 71
    exec(g)
SyntaxError: unqualified exec is not allowed in function 'maior_ponto' it contains a nested function with free variables

What is the problem with the function? I did not identify problem variables. I'm using python 2.7.5 on the Ubuntu terminal

    
asked by anonymous 27.08.2014 / 07:13

1 answer

1

In Python 2.x, the exec function can not appear in functions that have "functions" with free variables. A generating expression implicitly defines an object code for the code that must be executed at each iteration of that function. In the maior_ponto function you call the "free variable" max() within the generating expression ( max within return , in that case), which prevents this function from using exec .

The following code (without max ), for example, works:

def maior_ponto((a,b),p):
   g = mp((a,b),p)
   h = mp2((a,b),p)
   exec(g)
   exec(h)
   u = (m+n)
   return(r[1] for r in u if r[0])

In Python 3.x, the exec function has changed and you should no longer have this type of error.

Response from StackOverflow in English: Explanation of exec behavior

    
27.08.2014 / 08:05