Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of modules imported by a python module

I want to access some kind of import dependency tracking in Python, if there is any.

I decided to add to my module a __dependencies__ dict describing versions of all modules imported by the module.

I want to have an automated way of obtaining a list of modules imported by my module. Preferably in the last line of the module.

ModuleFinder (as suggested by How to list imports within a Python module? ) would not work since the inspection shall be performed for already loaded module.

Another problem with ModuleFinder is that it inspects a Python script (with if __name__ == '__main__' branch), not a module.

If we consider a toy script script.py:

if __name__ == '__main__':
    import foo

then the result is:

>>> mf = ModuleFinder
>>> mf.run_script('script.py')
>>> 'foo' in mf.modules
True

which should be False if script is imported as a module.

I do not want to list all imported modules - only modules imported by my module - so sys.modules (suggested by What is the best way of listing all imported modules in python?) would return too much.

I may compare snapshots of sys.modules from the beginning and the end of the module code. But that way I would miss all modules used by my module, but imported before by any other module.

It is important to list also modules from which the module imports objects.

If we consider a toy module example.py:

from foo import bar
import baz

then the result should be like:

>>> import example
>>> moduleImports(example)
{'foo': <module 'foo' from ... >,
 'baz': <module 'baz' from ...>}

(it may contain also modules imported recursively or foo.bar given bar is a module).

Use of globls() (according to How to list imported modules?) requires me to deal with non-module imports manually, like:

from foo import bar
import bar

How can I avoid that?

There is another issue with my solution so far. PyCharm tends to clean up my manual imports on refactoring, which makes it hard to keep it working.

like image 436
abukaj Avatar asked Oct 19 '17 18:10

abukaj


People also ask

How do I list all methods in a Python module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

How do I display the contents of a Python module?

The dir() functions shows all members a module has.


1 Answers

You can use the inspect moudule

For example:

import inspect
import os
m = inspect.getmembers(os) # get module content
filter(lambda x: inspect.ismodule(x[1]), m) # filter dependant modules

Here you have a live example

If you want the local modules imported just use:

filter(lambda x: inspect.ismodule(x[1]), locals().items()) # filter dependant modules

Another live example

like image 110
Netwave Avatar answered Sep 19 '22 19:09

Netwave