So now hekevintran has asked and quickly posted an answer 3 times in the last 24 hours. Looking forward to the next one... clearly he/she has prepared an entire series! :-)
– Jarret HardieMar 31 '09 at 16:26

7

The correct answer, of course, is almost always “don't!”.
– bobinceMar 31 '09 at 16:28

23

@S. Lott: Haven't read the FAQ recently? "It's also perfectly fine to ask and answer your own programming question, but pretend you're on Jeopardy: phrase it in the form of a question". This is not a bad question. +1
– Devin JeanpierreMar 31 '09 at 17:48

48

@S.Lott: You don't. You don't need to. If the question isn't on the site already, then it's fair game (according to the FAQ, as already pointed out). Just answer every question as though the OP needs help. They might not, but the next guy who reads their question probably will. Just my 2 cents.
– Bill the LizardApr 2 '09 at 18:13

However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.

but how about the scope of the code executed by 'exec'? is it nested?
– jondinhamMar 6 '12 at 10:24

18

A common case where someone wants to use 'exec' is something like if s=='foo': x.foo = 42 elif s=='bar': x.bar = 42 etc, which they may then write as exec ("x.%s = 42" % s). For this common case (where you only need to access an object's attribute that is stored in a string), there is a much faster, cleaner and safer function getattr: just write getattr(x, s) = 42 to mean the same thing.
– ShreevatsaRApr 19 '12 at 19:18

5

How is exec any slower than the python interpreter?
– Cris StringfellowFeb 6 '13 at 16:36

@Tanner: Hmm. Yes indeed setattr(x, s, 42) is the right syntax. Surprised it took so long for that error to be caught. Anyway, the point is that getattr and setattr are an alternative to exec when all you want is to get an arbitrary member, looked up by string.
– ShreevatsaROct 11 '13 at 19:01

eval and exec are the correct solution, and they can be used in a safer manner.

As discussed in Python's reference manual and clearly explained in this tutorial, the eval and exec functions take two extra parameters that allow a user to specify what global and local functions and variables are available.

@NedBatchelder: this is no more dangerous than anything. in your link rm /rf is mentioned. so should we say that bash is dangerous because we can also do that ? the only problem is elevation attacks. But we care not about this if the script is not a remote service (i.e. if it is just something executed by you).
– v.oddouJan 13 '15 at 3:41

2

@v.oddou I was responding to alan's statement, "eval and exec .. can be used in a safe manner." This is false. If someone said, "bash can be used in a safe manner," that would also be false. Bash is dangerous. It is a necessary danger, but dangerous nevertheless. Claiming that eval can be made safe is simply wrong.
– Ned BatchelderJan 13 '15 at 15:10

1

@NedBatchelder yes indeed. and the link you point to is good material. with power comes responsibility, so the point is simply to be aware of the potential power of eval. and if we decide that power=danger.
– v.oddouJan 14 '15 at 2:08

1

@NedBatchelder Many pieces of code written in Python can be dangerous as well, but why are you assuming that eval or exec are intended to be used as exec(input("Type what you want"))? There are many cases where a program may write a procedure or a function as a result of a computation; resulting functions will be as safe and as fast (once evaluated) as any other part of a good and well-written program. An unsafe program containing exec is not more dangerous than an unsafe program doing the damage by itself as exec doesn't give any new privilege to the program.
– Thomas BaruchelNov 16 '16 at 10:46

Avoid exec and eval

Using exec and eval in Python is highly frowned upon.

There are better alternatives

From the top answer (emphasis mine):

For statements, use exec.

When you need the value of an expression, use eval.

However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.

It is not idiomatic

Python is not PHP

Don't try to circumvent Python idioms because some other language does it differently. Namespaces are in Python for a reason and just because it gives you the tool exec it does not mean you should use that tool.

It is dangerous

So eval is not safe, even if you remove all the globals and the builtins!

The problem with all of these attempts to protect eval() is that they are blacklists. They explicitly remove things that could be dangerous. That is a losing battle because if there's just one item left off the list, you can attack the system.

So, can eval be made safe? Hard to say. At this point, my best guess is that you can't do any harm if you can't use any double underscores, so maybe if you exclude any string with double underscores you are safe. Maybe...

It is hard to read and understand

First, exec makes it harder to human beings to read your code. In order to figure out what's happening, I don't just have to read your code, I have to read your code, figure out what string it's going to generate, then read that virtual code. So, if you're working on a team, or publishing open source software, or asking for help somewhere like StackOverflow, you're making it harder for other people to help you. And if there's any chance that you're going to be debugging or expanding on this code 6 months from now, you're making it harder for yourself directly.

"my best guess is that you can't do any harm if you can't use any double underscores" - You could construct a string containing double underscores, and then call eval that string.
– Stanley BakOct 11 '16 at 16:11

It's worth mentioning, that' exec's brother exist as well called execfile if you want to call a python file. That is sometimes good if you are working in a third party package which have terrible IDE's included and you want to code outside of their package.

Ok .. I know this isn't exactly an answer, but possibly a note for people looking at this as I was. I wanted to execute specific code for different users/customers but also wanted to avoid the exec/eval. I initially looked to storing the code in a database for each user and doing the above.

I ended up creating the files on the file system within a 'customer_filters' folder and using the 'imp' module, if no filter applied for that customer, it just carried on

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).