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!
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.
literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With