Hard to understand 'eval'

Discussion in 'Python' started by TheSaint, Jun 14, 2008.

  1. TheSaint

    TheSaint Guest


    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)
    if value:
    cnfg= 'cfl[wchkey][nn]= _%s(value)' %nn

    And the output on pdb:

    (Pdb) p cnfg
    (Pdb) p cfl[wchkey][nn]
    (Pdb) eval('cfl[wchkey][nn]= _append(value)')
    *** SyntaxError: invalid syntax (<string>, line 1)
    (Pdb) p value
    (Pdb) p nn

    Obviously I've an _append() function to convert into decimal the given value.

    Other "eval" before this not issuing problems and also rather complicated,
    but I'm not seeing the error here.
    I'd like to study a class that might get a string and convert it into
    function, once it's found inside the program.
    TheSaint, Jun 14, 2008
    1. Advertisements

  2. Hem... Not obvious from this snippet, but what's wrong with
    getattr(cp, nn) ?
    bruno.desthuilliers, Jun 14, 2008
    1. Advertisements

  3. TheSaint

    TheSaint Guest

    The learning curve to get into these programming ways.
    Does gettattr run the snippet passed in?
    Considering that nn is a name of function, which will be called and (cfl,
    value) are the parameters to passed to that function.

    I'll spend some bit on getattr use.
    TheSaint, Jun 15, 2008
  4. TheSaint

    TheSaint Guest

    The program don't complain wrong indentation, I mostly sure a wrong
    copy-paste error.
    Error doesn't come up there.
    My mistake, I thought that was improving the loop.

    is it an if....elif....elif probing only the first matching case and drop the
    remaining checks?
    You got close, that's a dictionary of dictionaries and I'm trying to updating
    Append() is a conventional name regarding a file logging.
    There would be an option to set a quota of bytes size.
    it isn't so, the function look at the string to see if ending by K or M,
    which means Kbytes or Mbytes. It'll return the decimal conversion.
    If the value is set as boolean value, then it will do appending to the log
    when it True or stop appending when there's a quota.

    def _append(c, v):
    RE_BYTE= re.compile(r'^[\d]+(k|m)?$',re.I)
    # any number of digit followed by 0 or 1 (k or m), case insensitive
    if isinstance(v,bool):
    c['append']= v
    return c
    if RE_BYTE.match(value):
    k= 1024; M= k * k; v= int(value[:-1])
    if value[-1:] == 'k': v= v * k
    if value[-1:] == 'm': v= v * m
    c['append']= v
    return c

    All the code could be download at my web site ;)
    But this here it's a bit new concept.
    TheSaint, Jun 15, 2008
  5. The point here is that eval() use is general frowned upon. If you
    don't understand it or the alternatives, then you probably don't
    understand it well enough to make the call on using it or not.

    If you need just look up an attribute where the name of the attribute
    is in a variable, use getattr(obj, attribute_name). If you need to
    call a method somewhere, you should have both the name of the method
    and the list of arguments to call it with, such as getattr(obj,
    methname)(a, b, c). Does this make sense?
    Calvin Spealman, Jun 15, 2008
  6. TheSaint

    John Machin Guest

    Don't you mean "Unless the "compile/interpret pass is VERY VERY
    BROKEN", as in "omits to drop in a jump to the end of the 'if'
    statement after each chunk of action code"?
    John Machin, Jun 15, 2008
  7. TheSaint

    TheSaint Guest

    This is big enlightenment :) Thank you! :)

    I found problem with eval() when it comes to pass quoted strings.
    I circumvent that by encapsulating the strings in variable or tuple.
    The principle is to have a name which will refers a function somewhere in the
    program and to call that function, plus additional data passed in.

    In other word I'd expect something:

    function_list= ['add' ,'paint', 'read']
    for func in function_list:
    I tried getattr, and I saw that result. I only investigate a little, so I
    still have a small perplexity.
    TheSaint, Jun 16, 2008
  8. TheSaint

    TheSaint Guest

    That means either none or one letter, of which k or m are allowed.
    C is a dictionary, it might be omitted, but I'm still not sure if will lose
    its state.
    Not so apparent, it's doing that, buddy :)
    regexp did a fine check and case insensitive, but I like your idea too.
    That occupy only small variable and as long as python can accept anything not
    zero, false or none for an _if_ condition, that might be allowable, I think.
    Then if not zero will mean the log will be *appended* to an existing file and
    if the value is something that can be converted in decimal value, then this
    will set the quota for the log file, as well.
    Here below dbg is the log file and if it isn't None then s a valid file path
    should work.

    dbg= sttng['log']; mode= 'w' # normally write, it writes new
    if sttng['append'] > Path.getsize(dbg): mode= 'a'
    except (OSError, TypeError): # found a boolean or dbg is new file

    So 5 line of code can do me the job smartly, I think ;)
    TheSaint, Jun 16, 2008
  9. 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, Jun 16, 2008
  10. TheSaint a écrit :
    Nope, it just does what the name implies.
    Everything in Python's an object (at least anything you can bind to a
    name), including functions and methods. Once you have a callable object,
    you just have to apply the call operator (parens) to call it. In your
    case, that would be:

    func = getattr(cc, nn, None)
    if callable(func):
    result = func(cfl, value)
    Would be wise IMHO.
    Bruno Desthuilliers, Jun 16, 2008
  11. TheSaint a écrit :
    Can't work - function_list is a list of strings, not a list of
    functions. If the functions you intend to call are already bound to
    names in the current scope, you don't even need any extra lookup

    def add(*args):
    # code here

    from some_module import paint

    obj = SomeClass()
    read = obj.read

    functions = [add, paint, read]
    args = [1, 2]
    for func in functions:

    getattr is useful when you only have the name of the
    function/method/whatever attribute as a string. And a target object
    (hint: modules are objects too) of course - if the name lives either in
    the global or local namespace, you can access it by name using the dicts
    returned by resp. the globals() and locals() functions.

    Bruno Desthuilliers, Jun 16, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.