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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With