Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the python import tree [closed]

I'm trying to find out how much different parts of my code base are used. How best to traverse the import tree and find out what imports what? Ideally the resulting data could tell me

  • which objects are imported
  • the files in which the imported objects are defined
  • the files the objects are imported to

Note: One option is to run all the tests and profile using this post. However, tests are not even across the code base, with some areas having no tests, so this wouldn't be hugely representative.

like image 547
joel Avatar asked Aug 11 '19 10:08

joel


1 Answers

Since all objects inherit from object you can get a list of all imported objects with:

>>> object.__subclasses__()
[<class 'type'>, <class 'weakref'>, ...]

To find the module an object is first defined in use the __module__ attribute:

>>> type.__module__
'builtins'

A dict of all imported modules is available from the sys module. Using the module name as the key, the module object can be retrieved, the file name can then be obtained from the __file__ attribute (for most modules).

>>> import sys
>>> import csv
>>> csv_module = sys.modules['csv']
>>> csv_module.__file__
'...lib/python3.6/csv.py'

Note: Not all modules include the __file__ attribute, notably the builtins module, be sure to use hasattr(module, "__file__") as a guard.

I'll leave how to put that together to get your tree up to you.

like image 113
Tim Avatar answered Oct 26 '22 19:10

Tim