eval() and local variables

Discussion in 'Python' started by Peter Luciak, Apr 20, 2004.

  1. Peter Luciak

    Peter Luciak Guest

    Hi,
    I need to do something like this:

    def my():
    a,b=1,2
    func = "lambda x: a*x+b"
    map(eval(func),[1,2,3])

    my()

    NameError: global name 'a' is not defined

    Why do I have to make a,b global for this to work?

    Thanks,
    P.
    --
    Peter `cuco' Luciak jabber://
    http://www.luciak.org/
    Peter Luciak, Apr 20, 2004
    #1
    1. Advertising

  2. Peter Luciak

    Peter Otten Guest

    Peter Luciak wrote:

    > Hi,
    > I need to do something like this:
    >
    > def my():
    > a,b=1,2
    > func = "lambda x: a*x+b"
    > map(eval(func),[1,2,3])
    >
    > my()
    >
    > NameError: global name 'a' is not defined
    >
    > Why do I have to make a,b global for this to work?


    You don't:

    >>> def my():

    .... a, b = 1, 2
    .... return map(eval("lambda x: a*x+b", locals()), [1,2,3])
    ....
    >>> my()

    [3, 4, 5]

    That makes my's local variables eval's globals.
    However, it's not clear to me why you need eval() at all:

    >>> def my():

    .... a, b = 1, 2
    .... func = lambda x: a*x+b
    .... return map(func, [1,2,3])
    ....
    >>> my()

    [3, 4, 5]

    Peter
    Peter Otten, Apr 20, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. DataBinder.Eval and Eval.

    , Jun 16, 2006, in forum: ASP .Net
    Replies:
    1
    Views:
    520
    Karl Seguin [MVP]
    Jun 16, 2006
  2. Replies:
    16
    Views:
    190
    Sean O'Halpin
    Nov 10, 2007
  3. ara howard

    setting local variables via eval

    ara howard, Mar 11, 2008, in forum: Ruby
    Replies:
    15
    Views:
    316
    Robert Dober
    Mar 12, 2008
  4. FangQ
    Replies:
    3
    Views:
    88
    Ilya Zakharevich
    May 15, 2006
  5. Liang Wang
    Replies:
    8
    Views:
    123
    Ben Morrow
    Feb 2, 2008
Loading...

Share This Page