How to Check If a Module Is Imported in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a module is imported in Python. The lab covers module importing basics, including creating and importing a simple module. You'll learn how to use the import statement to bring modules into your program and access their functions and variables.

The lab then explores the sys.modules dictionary, which stores all imported modules in the current Python session. You will also learn how to use the importlib module to verify if a module has been imported.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/creating_modules("Creating Modules") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") subgraph Lab Skills python/importing_modules -.-> lab-559543{{"How to Check If a Module Is Imported in Python"}} python/creating_modules -.-> lab-559543{{"How to Check If a Module Is Imported in Python"}} python/standard_libraries -.-> lab-559543{{"How to Check If a Module Is Imported in Python"}} python/catching_exceptions -.-> lab-559543{{"How to Check If a Module Is Imported in Python"}} end

Learn About Module Importing

In this step, you will learn about module importing in Python. Modules are files containing Python definitions and statements. The import statement is used to bring modules into your current program, allowing you to use the functions and variables defined within them.

First, let's create a simple module. Open the VS Code editor in the LabEx environment and create a new file named my_module.py in the ~/project directory.

## ~/project/my_module.py
def greet(name):
    return f"Hello, {name}!"

PI = 3.14159

This module defines a function greet and a variable PI. Now, let's create another Python file to import and use this module. Create a new file named main.py in the ~/project directory.

## ~/project/main.py
import my_module

name = "LabEx User"
greeting = my_module.greet(name)
print(greeting)
print("PI =", my_module.PI)

In this main.py file, we use the import my_module statement to bring in the my_module we created earlier. We then access the greet function and the PI variable using the dot notation (my_module.greet, my_module.PI).

To run this code, open a terminal in the LabEx environment (it should already be open in the bottom panel of VS Code). Make sure your current directory is ~/project. If not, navigate to it using the cd command:

cd ~/project

Now, execute the main.py script using the python command:

python main.py

You should see the following output:

Hello, LabEx User!
PI = 3.14159

This demonstrates how to import a module and use its contents in another Python file.

Check sys.modules Dictionary

In this step, you will explore the sys.modules dictionary, which is a crucial part of Python's module import system. sys.modules is a dictionary that holds all the modules that have been imported into the current Python session. Understanding this dictionary can help you understand how Python manages modules.

To begin, let's create a Python script named check_modules.py in the ~/project directory. This script will import the sys module and print the keys of the sys.modules dictionary.

## ~/project/check_modules.py
import sys

print("Modules currently in sys.modules:")
for module_name in sys.modules.keys():
    print(module_name)

import my_module

print("\nModules after importing my_module:")
for module_name in sys.modules.keys():
    print(module_name)

This script first imports the sys module. Then, it iterates through the keys of the sys.modules dictionary and prints each module name. After that, it imports the my_module created in the previous step and prints the sys.modules dictionary again to show the newly imported module.

Now, run the script using the python command in the terminal:

cd ~/project
python check_modules.py

You will see a list of modules that are already loaded when the Python interpreter starts, followed by the same list with my_module added after the import my_module statement. The output will look something like this (the exact list of modules may vary):

Modules currently in sys.modules:
builtins
sys
_frozen_importlib
_imp
_warnings
_io
... (many more modules)

Modules after importing my_module:
builtins
sys
_frozen_importlib
_imp
_warnings
_io
... (many more modules)
my_module

Notice that my_module is added to the sys.modules dictionary after the import statement. This dictionary acts as a cache, so if you try to import the same module again, Python will simply retrieve it from sys.modules instead of reloading it from disk. This optimization improves performance.

Use importlib to Verify

In this step, you will learn how to use the importlib module to programmatically import modules and verify their existence. importlib is part of Python's standard library and provides a way to interact with the import system.

Let's create a Python script named verify_import.py in the ~/project directory. This script will use importlib to import my_module and check if it was successfully imported.

## ~/project/verify_import.py
import importlib

module_name = "my_module"

try:
    module = importlib.import_module(module_name)
    print(f"Module '{module_name}' imported successfully.")
    print(f"Greeting: {module.greet('LabEx')}")
except ImportError:
    print(f"Failed to import module '{module_name}'.")

In this script, we use importlib.import_module() to import my_module. If the module is found and imported successfully, the script prints a success message and calls the greet function from the module. If the module is not found, an ImportError is raised, and the script prints an error message.

Now, run the script using the python command in the terminal:

cd ~/project
python verify_import.py

You should see the following output:

Module 'my_module' imported successfully.
Greeting: Hello, LabEx!

If you were to change module_name to a non-existent module, such as "nonexistent_module", and run the script again, you would see:

Failed to import module 'nonexistent_module'.

This demonstrates how to use importlib to dynamically import modules and handle potential import errors. This is particularly useful in situations where you need to load modules based on user input or configuration files.

Summary

In this lab, you learned about module importing in Python. You created a module named my_module.py containing a function greet and a variable PI. Then, you created main.py to import my_module and use its contents, demonstrating how the import statement brings modules into your program and how to access functions and variables within them using dot notation.

You also started to explore the sys.modules dictionary, which holds all the modules that have been imported into the current Python session, a crucial part of Python's module import system.