Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find which Python modules are being imported from a package?
A module in Python is a file containing Python code, functions, classes, or variables. Packages are collections of modules organized in directories. When working with large applications, it's often useful to know which modules are currently imported and available in your Python environment.
In this article, we will discuss various methods to find which Python modules are being imported from a package.
Using sys.modules with List Comprehension
The sys.modules dictionary contains all currently loaded modules. We can use list comprehension to extract module names efficiently.
Example
The following example returns all imported module names in a sorted list using sys.modules −
import sys
# Get all loaded module names
output = [module.__name__ for module in sys.modules.values() if module]
output = sorted(output)
print('The list of imported Python modules are:', output[:10]) # Show first 10
The list of imported Python modules are: ['__main__', '_bootlocale', '_codecs', '_collections', '_functools', '_heapq', '_imp', '_locale', '_operator', '_signal']
Using pip freeze Command
The pip freeze command shows all globally installed packages with their versions. This is useful for checking installed packages rather than currently imported modules.
Example
Open terminal and run the following command −
pip freeze
Output
The terminal displays installed packages −
aspose-cells==22.7.0 click==8.1.3 colorama==0.4.5 numpy==1.22.4 pandas==1.4.3 python-dateutil==2.8.2 scipy==1.9.1
Using dir() Method
The dir() function returns all attributes and methods of an object. When called without arguments, it returns names in the current local scope.
Example
The dir() method returns names in the current namespace −
import os
import sys
modules = dir()
print('Names in current scope:', modules)
Names in current scope: ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os', 'sys']
Using inspect Module
The inspect module provides functions to get information about live objects. We can use it to find modules within a specific package.
Example
The following example finds modules imported within the os package −
import inspect
import os
# Get all members of os module and filter for modules
members = inspect.getmembers(os)
modules = filter(lambda m: inspect.ismodule(m[1]), members)
print("Modules in os package:")
for name, module in modules:
print(f"- {name}: {module}")
Modules in os package: - abc: <module 'abc' from '/usr/lib/python3.9/abc.py'> - errno: <module 'errno' (built-in)> - path: <module 'posixpath' from '/usr/lib/python3.9/posixpath.py'> - stat: <module 'stat' from '/usr/lib/python3.9/stat.py'> - sys: <module 'sys' (built-in)>
Using sys.modules Dictionary
The sys.modules dictionary maps module names to loaded modules. You can examine its keys to see all imported modules.
Example
The following example shows how to access the sys.modules dictionary −
from datetime import datetime
import sys
# Show currently loaded modules
module_names = list(sys.modules.keys())
print(f"Total loaded modules: {len(module_names)}")
print("First 15 modules:", module_names[:15])
Total loaded modules: 45 First 15 modules: ['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'zipimport', 'encodings', 'codecs', '_codecs']
Comparison of Methods
| Method | Use Case | Scope | Output Format |
|---|---|---|---|
sys.modules |
Currently loaded modules | All imported modules | Module names or objects |
pip freeze |
Installed packages | Global environment | Package==version |
dir() |
Current namespace | Local scope | Names in scope |
inspect |
Modules within package | Specific package | Detailed module info |
Conclusion
Use sys.modules to find currently loaded modules, pip freeze for installed packages, and inspect to explore modules within a specific package. Choose the method based on whether you need runtime imports or installed packages.
