#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2005
    Location
    Bay area
    Posts
    9
    Rep Power
    0

    using = in eval()


    There must be a good reason this doesn't work...
    Code:
    >>> x = 1 
    >>> eval("x = 2")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "<string>", line 1
        x = 2
          ^
    SyntaxError: invalid syntax
    >>>
    Any thoughts?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2004
    Location
    Regensburg, Germany
    Posts
    147
    Rep Power
    16
    The eval() function executes expressions like e.g. "x+1" or "y==47.11".

    The eval() function fails for "x = 2" because this is a statement and not an expression.

    For dynamic statement execution use the exec statement. E.g.
    Code:
    exec "x=2"
    exec "a = x-7\nb=a**2"
    assigns the value 2 to x, -5 to a and 25 to b.
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Where you can't use eval() to assign the value of an expression to a variable, the value of evaluating the expression can be assigned to the variable like so:

    Code:
    >>> x = 1
    >>> x = eval('2')
    >>> x = eval('x + 1')
    >>> x
    3
    >>>
    Note: that it isn't safe to use exec and to a lesser extent eval() on user input since both can be used to execute arbitrary commands on the system, which could result to someone taking over the computer or even whipping the hard drive! Keep these in mind and you should be fine .

    Hope this helps,

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo