Suggestions for good programming practices?
brueckd at tbye.com
brueckd at tbye.com
Tue Jun 25 10:39:05 EDT 2002
On 25 Jun 2002, Chris Liechti wrote:
> >> * Avoid exec, execfile, eval, and input.
> >
> > Might one ask why? What do you have to know to use them successfully?
>
> where does the string you exec come from? from the user: is he a python
> programmer? could he make subtle errors that break your code and then blame
> you? could it be somebody that like to play tricks with others and insert
> harmful expression or satements (like os.system('rm -fR * /*')? How do you
> handle exceptions, as any exception could be raised by the unknown code
> (hint: 'try: ... except: pass' is bad too...)?
>
> if you don't want to deal with such problems, avoid exec* and eval. they
> are fine for a throw away script, and they're needed when you embedd a
> python interpreter in your app (for this case there is code.interact and
> even better reexec). for all the other cases they're a risk.
This view is a overly extreme. Rather than teaching people to fear certain
features like eval/exec, it's better to explain the risks so that they can
make informed decisions as to when it's wise to use them.
For example, eval/exec are incredibly useful in building mini-languages
based on Python, in which you execute user code in some dictionary that
includes your set of custom functions (you basically end up with a
context-specific superset of Python). I've found this to be very useful in
several production systems (not 'throw away script[s]') as well as in
creating programmable test harnesses for the QA department (the
non-programmer QA engineers aren't scared off because they don't realize
it's programming, and the more technical QA engineers are pleased that
you've built them such a "rich" test harness language...hehehe). Can
malicious users do malicious things? Of course! But that's like saying
Guido should disable os.system!
So... rather than teaching "avoid W!", let's say "be careful with W
because of X, Y, and Z". I still wouldn't use eval/exec on code posted
through a web form, for example, but there are times when they are very
useful and I can use them in good confidence because I understand their
risks.
-Dave
More information about the Python-list
mailing list