- How do I find the current module name in Python?
- Example
- Output
- Example
- Output
- Example
- Output
- Example
- Output
- Programming for beginners
- Python check module name
- # Table of Contents
- # Check if a Python package is installed
- # Installing the module if it isn’t already installed
- # Check if a Python package is installed using find_spec
- # Installing the package if it isn’t already installed
- # Checking if the module isn’t installed
- # Additional Resources
How do I find the current module name in Python?
A module can find out its own module name by looking at the predefined global variable __name__. If this has the value ‘__main__’, the program is running as a script.
Example
def main(): print('Testing…. ') ... if __name__ == '__main__': main()
Output
Modules that are usually used by importing them also provide a command-line interface or a selftest, and only execute this code after checking __name__.
The__name__ is an in-built variable in python language, we can write a program just to see the value of this variable. Here’s an example. We will check the type also −
Example
print(__name__) print(type(__name__))
Output
Example
def myFunc(): print('Value of __name__ = ' + __name__) if __name__ == '__main__': myFunc()
Output
Value of __name__ = __main__
Example
Now, we will create a new file Demo2.py. In this we have imported Demo and called the function from Demo.py.
import Demo as dm print('Running the imported script') dm.myFunc() print('\n') print('Running the current script') print('Value of __name__ = ' + __name__)
Output
Running the imported script Value of __name__ = Demo Running the current script Value of __name__ = __main__
Programming for beginners
Every module in python has predefined attribute ‘__name__’. If the module is being run standalone by the user, then the module name is ‘__main__’, else it gives you full module name.
def sum(a,b): return a+b print("Module name : ",__name__)
import arithmetic print("Module name : ",arithmetic.__name__)
Observe the output, module name printed twice. A module can contain executable statements. These statements are executed; only the first time the module name is encountered in an import statement. So executable statement in arithmetic.py is also executed.
def sum(a,b): return a+b if(__name__=="__main__"): print("This program is run by itslef") else: print("This module called by other module")
Python check module name
Last updated: Feb 23, 2023
Reading time · 3 min
# Table of Contents
# Check if a Python package is installed
To check if a Python package is installed:
- Import the package in a try block.
- Use an except block to handle the potential ModuleNotFoundError .
- If the try block runs successfully, the module is installed.
Copied!try: import requests print('The requests module is installed') except ModuleNotFoundError: print('The requests module is NOT installed')
We used a try/except block to check if a module is installed.
If the try block doesn’t raise an exception, the module is installed.
If the module isn’t installed, a ModuleNotFoundError error is raised and the except block runs.
# Installing the module if it isn’t already installed
You can also extend the try/except statement to install the module if it isn’t installed.
Copied!import sys import subprocess try: import requests print('The requests module is installed') except ModuleNotFoundError: print('The requests module is NOT installed') # 👇️ optionally install module python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL ) finally: import requests
If you need to check if a package is installed using pip , use the pip show command.
The pip show module_name command will either state that the package is not installed or show a bunch of information about the package, including the location where the package is installed.
You can also use the following one-liner command.
Copied!python -c 'import pkgutil; print(1 if pkgutil.find_loader("module_name") else 0)'
Make sure to replace module_name with the actual name of the module you are checking for.
The command returns 1 if the module is installed and 0 if it isn’t but this can be easily adjusted.
# Check if a Python package is installed using find_spec
An alternative approach is to use the importlib.util.find_spec method.
The find_spec() method will return a spec object if the module is installed, otherwise, None is returned.
Copied!import importlib.util module_name = 'requests' spec = importlib.util.find_spec(module_name) if spec: print(f'The module_name> module is installed') else: print(f'The module_name> module is NOT installed')
The importlib.util.find_spec method finds the spec for a module.
The spec for a module is a namespace containing the import-related information used to load the module.
If no spec is found, the method returns None.
# Installing the package if it isn’t already installed
You can optionally install the package if it isn’t already installed.
Copied!import importlib.util import sys import subprocess module_name = 'requests' spec = importlib.util.find_spec(module_name) if spec: print(f'The module_name> module is installed') else: print(f'The module_name> module is NOT installed') # 👇️ optionally install the module if it's not installed python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL )
# Checking if the module isn’t installed
If you need to check if the module isn’t installed, check if the spec variable stores a None value.
Copied!import importlib.util import sys import subprocess module_name = 'requests' spec = importlib.util.find_spec(module_name) if spec is None: print(f'The module_name> module is NOT installed') # 👇️ optionally install the module if it's not installed python = sys.executable subprocess.check_call( [python, '-m', 'pip', 'install', 'requests'], stdout=subprocess.DEVNULL ) print(f'The module_name> module is now installed')
Which approach you pick is a matter of personal preference. I’d use the try/except statement because I find it quite direct and easy to read.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.