[Tutor] What's in a name?

Steven D'Aprano steve at pearwood.info
Sat Jan 4 05:59:19 CET 2014


On Fri, Jan 03, 2014 at 12:29:34AM -0500, Keith Winston wrote:
> Hmm, maybe I stumbled upon at least one approach, turning the problem
> around. Make it something like:
> 
> for i in ["alist", "blist", "clist"]
>     i[3] = "okey dokey "
>     print(eval(i)[3], i)
> 
> Of course I've been staring at this for a while, but as soon as I post I
> find a way... this is my first use of eval()

And now that you've discovered eval(), do yourself a favour and forget 
all about it.

- eval is dangerous. The number one cause of software vulnerabilities 
  (i.e. bugs which can be used by viruses and malware) today is code 
  ejection, which is a fancy way of saying "somebody screwed up with
  eval or the equivalent".

- eval is slow. In Python, at least, using eval("something()") is
  about ten times slower than just calling something(). That's because
  the slow process of parsing and compiling the text into executable
  code takes place at run-time instead of compile-time.

- eval is confusing. While it's possible to use eval in simple, easy
  to understand ways, there's (usually) not much point in that. So 
  eval normally only gets used in ways which are tricky to write and
  tricky to understand.

- There is very little that cannot be done without eval. It is rarely 
  the best solution, and even more rarely the only solution.


My recommendation is, any time you get the urge to use eval in code, 
go take a cold shower until the urge goes away. Exceptions can be made 
for experts and for interactive use at the REPL.

Your code above is probably better written something like this:

for name in ["alist", "blist", "clist"]:
    thelist = vars()[name]
    thelist[3] = "okey dokey "
    print(name, "=", thelist)



-- 
Steven


More information about the Tutor mailing list