2

I have a python file with imports as this:

from a import z
from b import y
from c import x
# ....  

I have a string representation of each of this modules, but I want to get the string representation from all the imported modules without having to list all of them. In short I want to do something like for name in something_to_repr_all_imported_modules ....

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
kijana
  • 332
  • 2
  • 15

2 Answers2

3

There is sys.modules which is a mapping of all imported modules thus far ... Not sure if that's what you're looking for though ...

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

A VERY crude way of doing this is something like:

>>> import sys
>>> [x for x in locals().keys() if isinstance(locals()[x], type(sys)) and not x.startswith('__')]

You'll have to exclude sys from the result, but you get the picture.

I'm not sure if this is the best way of achieving what you want, but I'm pretty sure it works at least.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
  • There might be a cleaner solution involving `inspect.getmembers` and `inspect.ismodule`. Of course, then you're back to using `sys.modules` to get a reference to the current module object ... – mgilson Feb 18 '13 at 13:11
  • There is probably a cleaner solution, yes, mine is quite cumbersome, but I admit I don't have that much experience manipulating imports and such. – pcalcao Feb 18 '13 at 13:14