[Tutor] How to inspect variables in a module from the command line

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 26 Apr 2001 23:42:42 +0200


On  0, Phil Bertram <phil.bertram@clear.net.nz> wrote:
> I often develop my programs by writing a class in a module
> 
> class MyClass:
>     stuff here
> 
> if __name__ == '__main__' :
>     klass=MyClass()
>     klass.mutate()
>     print klass.attribute
> 
> to run and test scripts written in a module. With print statements for debugging. (I press f5 in PythonWin).
> 
> Is there a way to switch to the interpreter and inspect the variables in the module
> I've tried thinds like 
> 
> >>> __main__.klass.anotherAttribute
> 
> but can't seem to work it out.
> 
> Any ideas ?

I'm not sure what you mean so I'll just put some suggestions here.

The current module's name is in __name__ (in the interactive interpreter,
it's usually '__main__'). You can use that name to look up
the module, in the dictionary sys.modules.

The dir() function shows a list attributes of a module (or class, or other
object).

With getattr(object, name) you can get the value of some object

So something like this is possible:

import sys
mod = sys.modules[__name__] # Get current module
for attr in dir(mod):
   print attr, "=", repr(getattr(mod, attr))

This is what we call neat introspection abilities :)

Similarly, mod.klass is the class klass in the module mod, and you can
look at its attributes with dir() and getattr(), exactly the same way.

Instead of mod, you can also use some module you just imported, like
your script.

With the command line option -i you can run a script first, then go into the
interactive interpreter to inspect things (I don't have much Idle experience).

Hmm, I hope I've written down enough random thoughts now to get to something
useful :-)

-- 
Remco Gerlich