How to enumerate all imported modules? E.g. I would like to get ['os', 'sys'] for from this code:
You can leverage Python std library sys.modules:
An approximation of getting all imports for the current module only would be to inspect globals() (Return a dictionary representing the current global symbol table. This is always the dictionary of the current module) for modules:
This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you usedimport module as alias; yield name instead if you want the alias.