7

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.

joel
  • 6,359
  • 2
  • 30
  • 55
  • Pyflakes, pylint or similar are useful tools for checking for unused imports (plus other things) – Chris_Rands Aug 11 '19 at 10:31
  • You can also just run your code with coverage (https://coverage.readthedocs.io/en/v4.5.x/), but that naturally won't be 100% accurate either. – AKX Aug 11 '19 at 10:37
  • Oh, and if it helps, you can also use `gc.get_objects()` to get a list of every single object known by the interpreter's garbage collector. – AKX Aug 11 '19 at 10:41

1 Answers1

1

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.

Tim
  • 2,510
  • 1
  • 22
  • 26
  • @joel, if you got how to do it, can you please share? Tim, it would help to expand your solution to provide the full method. Thanks in advance – vpshastry May 05 '21 at 01:26