views:

680

answers:

9

There is an eval function in Python I stumbled upon while playing around.

I cannot think of a case when this function is needed, except maybe as syntactic sugar.

Can anyone give an example?

Thanks :)

+4  A: 

The Wikipedia article on eval is pretty informative, and details various uses.

Some of the uses it suggests are:

  • Evaluating mathematical expressions
  • Compiler bootstrapping
  • Scripting (dynamic languages in general are very suitable to this)
  • Language tutors
Noldorin
I looked at this article and still don't understand... This is rather like a calculate function which calculates an arithmetic expression!
ooboo
@ooboo: `eval` can run *any* code in theory (hence the security risks pointed out in the article).
Noldorin
A: 

eval() is not normally very useful. One of the few things I have used it for (well, it was exec() actually, but it's pretty similar) was allowing the user to script an application that I wrote in Python. If it were written in something like C++, I would have to embed a Python interpreter in the application.

Zifre
+1  A: 

In a program I once wrote, you had an input file where you could specify geometric parameters both as values and as python expressions of the previous values, eg:

a=10.0
b=5.0
c=math.log10(a/b)

A python parser read this input file and obtained the final data evaluating the values and the expressions using eval().

I don't claim it to be good programming, but I did not have to drive a nuclear reactor.

Stefano Borini
+1  A: 

In the past I have used eval() to add a debugging interface to my application. I created a telnet service which dropped you into the environment of the running application. Inputs were run through eval() so you can interactively run Python commands in the application.

Andre Miller
I've done similar scripting the COM interface to Enterprise Architect to try out different queries
Pete Kirkham
+4  A: 

You may want to use it to allow users to enter their own "scriptlets": small expressions (or even small functions), that can be used to customize the behavior of a complex system.
In that context, and if you do not have to care too much for the security implications (e.g. you have an educated userbase), then eval() may be a good choice.

Roberto Liffredo
A: 

Hi

Eval is a way to interact with the Python interpreter from within a program. You can pass literals to eval and it evaluates them as python expressions.

For example -

print eval("__import__('os').getcwd()")

would return the current working directory.

cheers

Andriyev
A: 

I use it as a quick JSON parser ...

r='''
{
    "glossary": {
        "title": "example glossary"
        }
}
'''

print eval(r)['glossary']['title']
don't do it. `eval("""{"glossary": {"death" : false}}""")` --> `NameError: name 'false' is not defined`
SilentGhost
@SilentGhost: that's a great point, I've used your example in an answer to a question; http://stackoverflow.com/questions/1083250/running-json-through-pythons-eval/1083302
Kiv
Using a *real* JSON parser would be less buggy and more secure.
Mike Graham
+6  A: 

eval and exec are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &c.

For example, if I had to deal with such dynamic Python sources, I'd reach for the ast module -- ast.literal_eval is MUCH safer than eval (you can call it directly on a string form of the expression, if it's a one-off and relies on simple constants only, or do node = ast.parse(source) first, then keep the node around, perhaps munge it with suitable visitors e.g. for variable lookup, then literal_eval the node) -- or, once having put the node in proper shape and vetted it for security issues, I could compile it (yielding a code object) and build a new function object out of that. Far less simple (except that ast.literal_eval is just as simple as eval for the simplest cases!) but safer and preferable in production-quality code.

For many tasks I've seen people (ab-)use exec and eval for, Python's powerful built-ins, such as getattr and setattr, indexing into globals(), &c, provide preferable and in fact often simpler solutions. For specific uses such as parsing JSON, library modules such as json are better (e.g. see SilentGhost's comment on tinnitus' answer to this very question). Etc, etc...

Alex Martelli
A: 

I use exec to create a system of plugins in Python.

    try:
        exec ("from " + plugin_name + " import Plugin")
        myplugin = Plugin(module_options, config=config)
    except ImportError, message:
        fatal ("No such module " + plugin_name + \
               " (or no Plugin constructor) in my Python path: " + str(message))
    except Exception:
        fatal ("Module " + plugin_name + " cannot be loaded: " + \
               str(sys.exc_type) + ": " + str(sys.exc_value) + \
               ".\n    May be a missing or erroneous option?")

With a plugin like:

class Plugin:

    def __init__ (self):
        pass

    def query(self, arg):
         ...

You will be able to call it like:

    result = myplugin.query("something")

I do not think you can have plugins in Python without exec/eval.

bortzmeyer
This is not good. You should use the `__import__` builtin function, which is called by the `from ... import ...` statement.
gahooa