[Tutor] question about listing variables defined since session started

Steven D'Aprano steve at pearwood.info
Tue May 1 02:38:48 CEST 2012


Robert Sjoblom wrote:
> On 30 April 2012 23:25, Comer Duncan <comer.duncan at gmail.com> wrote:
>> Hi,
>>
>> I have a newbie type question.  Say I have started a python (or
>> ipython) session and have done some imports and have also defined some
>> new variables since the session started.  So, I have in my current
>> namespace a bunch of things. Suppose I  want to list just those
>> variable  names which have been defined since the session started but
>> not include the names of the objects that who and whos will return.
>> How to do that?
> 
> Not entirely sure, but something like this might work (untested):
> for name in dir():
>     myvalue = eval(name)
>     print name, "is", type(name), "and is equal to ", myvalue

Please do not use eval unless you know what you are doing, and certainly don't 
encourage newbies to use it without a word about the risks.

(I really wish eval and exec were hidden inside a module that you had to 
import, to discourage people from using them unnecessarily.)

My advice is:

Never use eval.
For experts only: hardly ever use eval.

eval is slow. eval is tricky to use correctly for all but the simplest uses. 
eval is dangerous.

In this *specific* case, using eval is probably safe. But as a matter of best 
practice, you should not use eval when there is a simpler and safer alternative:

for name in dir():
     print name, "is", vars()[name]


You can replace vars() with globals() if you prefer.

Possibly better still:

from pprint import pprint
pprint(vars())



Why is eval so dangerous?

Because it executes code.

The risk with eval is not using it at the interactive interpreter. If you want 
to destroy your own data, there are easier ways than using eval. But the risk 
is that you write a function that uses eval, and then some day that function 
gets used in your web application, and you collect text from users on the 
Internet who feed your application something that causes eval to execute code. 
Suddenly, your web server is under their control and they can do *anything*.

Sound far-fetched? But it happens, and very frequently. Code injection attacks 
are now the *most* common security vulnerability, more common than even buffer 
overflows. Whenever you hear about some website being compromised, or a virus 
or trojan horse taking over people's desktops, there is a high probability 
that it is because some coder used the equivalent of "eval" incorrectly.

Here is a humorous look at the issue of code injection:

http://xkcd.com/327/


and a more serious discussion:

http://en.wikipedia.org/wiki/Code_injection



-- 
Steven


More information about the Tutor mailing list