Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval calling lambda don't see self

Tags:

python

Here is a simple code illustrating the essence of a problem:

class test:
    def __init__(self):
        self.var = 0
    def set(self, val):
        self.var = val
        print eval('map(lambda x: self.var*x, [1,2,3,4,5])')
f = test()
f.set(10)

It says

NameError: global name 'self' is not defined

I know many people don't like eval but in my case I have to use it because it executes a math formula from the string entered by a user during programm execution. Any suggestions is highly appreciated! Thanks in advance!

like image 206
aliko Avatar asked Sep 08 '11 14:09

aliko


People also ask

What does eval () do in Python?

Understanding Python's eval() You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.

What can I use instead of eval in Python?

literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.

Is eval safe to use Python?

overall, "eval" security, in any language, is a big issue. SQL injection attacks are just an example of such a security hole. Perl Safe has had security bugs over the years - most recent one I remember, it was safe, except for destructors on objects returned from the safe eval.

How do you enter a list in eval?

First, we define a string, that carries the syntax of a list. Next, we use eval to evaluate it. Finally, we can show that it has the properties of a Python list. Another example, where we allow the user to input the string to be evaluated.


1 Answers

Try:

eval('map(lambda x, self=self: self.var*x, [1,2,3,4,5])')

The odd self=self will create a copy of self from the outer context into the inner context (the "body" of the lambda expression).

like image 59
Aaron Digulla Avatar answered Sep 18 '22 15:09

Aaron Digulla