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 tim@ksr.com
not speaking for Kendall Square Research Corp