This might helps you How to list imported modules?, but you have to send the scope where your modules are imported to the function with locals()
or globals()
, otherwise:
This won't return local imports
Non-module imports like from x import y
won't be listed because it can be any python object (variables of any types, classes, functions, etc).
# check_version.py
from types import ModuleType
def all_libraries(scope):
return [f'{value.__name__}=={getattr(value, "__version__", "NA")}' for _, value in scope.items()
if isinstance(value, ModuleType) and value.__name__ != 'builtins']
from check_version import all_libraries
def foobar():
# print globals imports
for modules_version in all_libraries(globals()):
print(modules_version)
# time = NA
# random = NA
# print locals imports
import PIL
import sys
for modules_version in all_libraries(locals()):
print(modules_version)
# sys=NA
# PIL=5.1.0
foobar()