how to print 'user imported' module name and version in python

Viewed 107

I want to print imported module name & version in colab
This is my code

import numpy as np
....and so on....

ref_dict = {'pd': 'pandas', 'np': 'numpy', 'sns': 'seaborn', 'plt': 'matplotlib'}
as_name =[x for x in set(sys.modules) & set(globals())]
as_ref = [ref_dict[x] for x in dir() if x in ref_dict.keys()]
module_list= as_name + as_ref
a, na=[], []

print('--module name & versions imported by user--\n')
for name in module_list:
    try: a.append('{}: {}'.format(name, sys.modules[name].__version__))
    except: na.append('{}: {}'.format(name, 'Not available'))

print(*a,'\n-----\n', *na, sep='\n')

this is the result

--module name & versions imported by user--

torch: 1.8.0+cu101
re: 2.2.1
tqdm: 4.41.1
sklearn: 0.22.2.post1
numpy: 1.19.5
pandas: 1.1.5
matplotlib: 3.2.2
seaborn: 0.11.1

-----

os: Not available
sys: Not available
__main__: Not available

As seen above, ref_dict specifies module imported by alias, which I don't want to do so.
is there any better way to see imported module versions and names?

1 Answers

This gives you a list of all the imported modules

{value.__name__ for value in globals().values() if inspect.ismodule(value)}

So it's similar to what you are using, but instead of using the aliased name in global(), it gets the actual name of the module.

Notice that it requires you to import inspect, so inspect and builtins are part of the list as well

In [1]: import inspect

In [2]: import pandas as pd

In [3]: {value.__name__ for value in globals().values() if inspect.ismodule(value)}
Out[3]: {'builtins', 'inspect', 'pandas'}
Related