whos and clear (as in matlab) functionality

Oren Tirosh oren-py-l at hishome.net
Thu Mar 20 06:44:41 EST 2003


On Thu, Mar 20, 2003 at 02:02:57AM -0800, Thomas Knudsen wrote:
> I'm a python newbie, currently in the process of moving
> parts of my work from Matlab to python + Numeric.
> 
> When using python interactively, I  often need something
> like the Matlab "whos" command.
> 
> In Matlab "whos" returns a list of all variables:
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
> >> a = 4;
> >> b = [1 2 3; 4 5 6];
> >> whos
>   Name      Size                   Bytes  Class
> 
>   a         1x1                        8  double array
>   b         2x3                       48  double array
> 
> Grand total is 7 elements using 56 bytes
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
> 
> is there any way of doing something similar in python?
> A recent post by Michael Chermside, in the thread
> "How to get the 'name' of an int" suggests the following for
> the slightly different task of listing names and values:
> 
>             for name, value in locals().iteritems():
>                 print "%s = %s" % (name, value)
> 
> any suggestions of how I could change this to name, type?

    for name, value in locals().iteritems():
        print "%s : %s" % (name, type(value))

You can also use type(value).__name__ for a more compact output.

> On a related note, the Matlab commands "clear all; pack"
> clears all variables in the current namespace and starts
> garbage collection. Is there a corresponding python idiom?

Not really. You can do vars().clear() but then you will lose important 
reserved variables like __builtins__. I guess you could do something 
like the following one-liner abomination:

[vars().__delitem__(_k) for _k in vars().keys() if not _k.startswith('_')]

The equivalent of pack would be 'import gc; gc.collect()' but it's 
rarely necessary because reference counting usually disposes of 
garbage immediately.

    Oren






More information about the Python-list mailing list