How to find which Python modules are being imported from a package?


A file containing Python code, definitions of statements, functions, or classes is known as a module. A module with the name "module" that we will construct is a file named module.py.

To break down complex programmes into smaller, easier-to-understand parts, we use modules. Code reuse is another benefit of modules.

In this article, we will discuss various ways to find which Python modules are being imported from a package.

Using List Comprehension

To iterate over each element in the Python list, a list comprehension is made out of brackets carrying the expression, which is then run for each element.

Python List comprehension offers a much shorter syntax for creating a new list from the elements of an existing list.

Example

The following example returns all imported local module names by default in an unsorted list using the sys library with List Comprenehsion.

Using __name__ (also known as a dunder), this code iterates through sys.modules.values() to check if an item is a locally scoped module. If so, ‘output’ is saved with the module name. For readability, this code arranges the ‘output’ variable and saves it back to itself. List formatted output of these ‘output’ is sent to the terminal.

import sys output = [module.__name__ for module in sys.modules.values() if module] output = sorted(output) print('The list of imported Python modules are :',output)

Output

Following is an output of the above code −

The list of imported Python modules are : ['__main__', '_bootlocale', '_codecs', '_collections', '_functools', 
'_heapq', '_imp', '_locale', '_operator', '_signal', 
'_sitebuiltins', '_stat', 
'_sysconfigdata_m_linux_x86_64-linux-gnu', '_thread', 
'_warnings', '_weakref', '_weakrefset', 'abc', 
'builtins', 'codecs', 'collections', 'collections.abc', 'collections.abc', 'contextlib', 'encodings', 
'encodings.aliases', 'encodings.latin_1', 
'encodings.utf_8', 'errno', 'functools', 'genericpath', 
'heapq', 'importlib', 'importlib._bootstrap', 
'importlib._bootstrap', 'importlib._bootstrap_external', 
'importlib._bootstrap_external', 'importlib.abc', 
'importlib.machinery', 'importlib.util', 'io', 'io', 
'itertools', 'keyword', 'marshal', 'mpl_toolkits', 
'operator', 'os', 'posix', 'posixpath', 'posixpath', 
'reprlib', 'site', 'stat', 'sys', 'sysconfig', 'types', 
'warnings', 'weakref', 'zipimport']

Using pip freeze command

This function shows a list of all names and versions of imported global modules, by default arranged alphabetically.

Example

Enter the below command by opening the terminal window in an IDE. In order to execute, press the Enter key −

C:\Users\Lenovo>pip freeze

Output

The terminal receives the output −

aspose-cells==22.7.0
click==8.1.3
cloudpickle==2.1.0
colorama==0.4.5
dask==2022.7.0
et-xmlfile==1.1.0
fsspec==2022.5.0
genno==1.11.0
ixmp==3.5.0
JPype1==1.4.0
llvmlite==0.38.1
locket==1.0.0
message-ix==3.5.0
modcall==0.1.0
mysql-connector-python==8.0.29
namespace==0.1.4
native==0.0.0.0a0.dev20210615
numba==0.55.2
numpy==1.22.4
openpyxl==3.0.10
packaging==21.3
pandas==1.4.3
partd==1.2.0
Pint==0.19.2
protobuf==4.21.2
psycopg2==2.9.3
pycparser==2.21
pyparsing==3.0.9
python-dateutil==2.8.2
python-dotenv==0.20.0
python-magic==0.4.27
pytz==2022.1
PyYAML==6.0
scipy==1.9.1
six==1.16.0
sparse==0.13.0
toolz==0.12.0
walk==0.3.5
workbook==1.1
xarray==2022.3.0
xlrd==2.0.1
xlutils==2.0.0
xlwt==1.3.0

Using dir() method

The dir() function returns all of the given object's properties and methods, but not their related values. This function will even return built-in attributes that are the default for all objects.

Example

The dir() method is used in the following example to return a sorted list of all local module names −

module = dir() print('The list of imported Python modules are :',module)

Output

The output shown below demonstrate that this script only shows names relevant to our local scope −

The list of imported Python modules are : ['__annotations__', '__builtins__', '__cached__', 
'__doc__', '__file__', '__loader__', '__name__', 
'__package__', '__spec__']

Using inspect.getmember() and a Lambda

A number of helpful functions are offered by the inspect module to help in gathering data on active objects such modules, classes, methods, functions, tracebacks, frame objects, and code objects. It can assist you in examining a class's contents, retrieving a method's source code, extracting and formatting a function's argument list, or gathering all the data required to display a detailed traceback, among other things.

An anonymous, short function is known as a lambda. Although a lambda function can have only one expression, it can have any number of arguments.

Example

The following example returns the imported local modules in a sorted format using inspect.getmember() and a Lambda.

The names of the imported local modules and where they are located on the system are returned by this code as an iterable object. This is iterated through and printed as one line using a for loop.

import inspect import os modules = inspect.getmembers(os) results = filter(lambda m: inspect.ismodule(m[1]), modules) for o in results: print('The list of imported Python modules are :',o)

Output

Following is an output of the above code −

The list of imported Python modules are : ('abc', <module 'abc' from '/usr/lib64/python3.6/abc.py'>)
The list of imported Python modules are : ('errno', <module 'errno' (built-in)>)
The list of imported Python modules are : ('path', <module 'posixpath' from '/usr/lib64/python3.6/posixpath.py'>)
The list of imported Python modules are : ('st', <module 'stat' from '/usr/lib64/python3.6/stat.py'>)
The list of imported Python modules are : ('sys', <module 'sys' (built-in)>)

Using sys module

The sys.modules dict can be used to discover all the Python modules from a specific package that are being utilised by an application. A dictionary that links module names to modules is called sys.modules. To see imported modules, you can look at its keys.

Example

Following is an example to find the imported modules from a package using sys module

from datetime import datetime import sys print (sys.modules.keys())

Output

Following is an output of the above code −

dict_keys(['builtins', 'sys', '_frozen_importlib', 
'_imp', '_warnings', '_thread', '_weakref', 
'_frozen_importlib_external', '_io', 'marshal', 'posix', 
'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', 
'__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', '_bootlocale', '_locale', 'site', 'os', 
'errno', 'stat', '_stat', 'posixpath', 'genericpath', 
'os.path', '_collections_abc', '_sitebuiltins', 
'sysconfig', '_sysconfigdata_m_linux_x86_64-linux-gnu', 'types', 'functools', '_functools', 'collections', 
'operator', '_operator', 'keyword', 'heapq', '_heapq', 'itertools', 'reprlib', '_collections', 'weakref', 
'collections.abc', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'warnings', 
'importlib.util', 'importlib.abc', 'importlib.machinery', 'contextlib', 'mpl_toolkits', 'datetime', 'time', 'math', 
'_datetime'])

Updated on: 23-Nov-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements