Re: Help identifying

Tim Peters (
Sun, 08 May 94 00:02:41 -0400

> [skip]
> ...
> import __main__
> for n in dir(__main__):
> try:
> dir(n)
> except TypeError:
> print `n`, 'is not a module'
> As output, I got:
> '_' is not a module
> '__builtin__' is not a module
> '__main__' is not a module
> '__name__' is not a module
> 'posix' is not a module
> 'sys' is not a module
> ...
> I imagine I got TypeErrors for all n because the result of "dir(__main__)"
> is a list of strings,

Exactly right!

> not a list of attributes.

More precisely, dir's argument must have a __dict__ attribute, else you
get a TypeError. Strings don't have a __dict__ attribute; modules do (&
so do some other things).

> How do I get what I want?

Since you're looking for modules specifically, sys.modules is a dict that
contains all the name->module mappings the system has loaded at any given
time. So the straightforward solution is

for n in dir(__main__):
if sys.modules.has_key(n):
print n, dir(sys.modules[n])

A more general trick is to use 'eval' to map a variable's name (a string)
to the variable's current binding. E.g.,

module_type = type(__main__)
for n in dir(__main__ ):
value = eval(n)
if type(value) is module_type:
print n, dir(value)

Or if you wanted to do dir() on *everything* with a __dict__,

for n in dir(__main__):
value = eval(n)
if hasattr(value, '__dict__'):
print n, dir(value)

Do resist the temptation to write that last as:

def f(n): print n, dir(eval(n))
map(f, filter(lambda n:hasattr(eval(n),'__dict__'),dir(__main__)))

the-obfuscated-python-contest-is-closed<wink>-ly y'rs - tim

Tim Peters
not speaking for Kendall Square Research Corp