Hard to understand 'eval'
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Jun 16 01:24:32 EDT 2008
En Sat, 14 Jun 2008 05:31:35 -0300, TheSaint <fc14301589 at icqmail.com> escribió:
> It seems to be strange that give me syntax error inside an eval statement.
> I'm looking at it carefully but I can't see any flaw.
>
> Here it's part of the code:
>
> for nn in stn_items:
> value= eval('cp.%s' %nn)
> if value and (nn in 'log, trash, multithread, verbose, download'):
> cfl[wchkey][nn]= chkbool(value)
> continue
> if value:
> cnfg= 'cfl[wchkey][nn]= _%s(value)' %nn
> eval(cnfg)
>
> And the output on pdb:
>
> (Pdb) p cnfg
> 'cfl[wchkey][nn]=_append(value)'
> (Pdb) p cfl[wchkey][nn]
> False
> (Pdb) eval('cfl[wchkey][nn]= _append(value)')
> *** SyntaxError: invalid syntax (<string>, line 1)
Others have already remarked that your general approach is bad ("don't use eval!", in short). But none has pointed out the actual error in your code: eval can accept only an *expression*, not a statement. eval("x=1") gives the same SyntaxError.
(`exec` is the way to execute statements, but the same caveats apply, so: don't use exec either, use getattr/setattr instead)
--
Gabriel Genellina
More information about the Python-list
mailing list