Python Modules
Python Modules
A module in Python is a file containing Python definitions and statements. Modules allow you to logically organize your Python code into smaller, manageable files. A module can define functions, classes, and variables, and it can also include runnable code.
Using modules helps you to:
- Organize code in a modular way.
- Reuse code across multiple scripts.
- Keep the codebase clean and maintainable.
Types of Modules
- Built-in Modules: These come with Python and are available by default.
- User-defined Modules: These are created by the user, saving code into a
.pyfile. - Third-party Modules: These are external libraries or packages that can be installed using a package manager like
pip.
Importing Modules
To use a module, you need to import it into your script. There are several ways to import a module:
- Import the whole module:
import math print(math.sqrt(16)) # Output: 4.0 - Import specific items from a module:
from math import sqrt print(sqrt(16)) # Output: 4.0 - Import with an alias:
import math as m print(m.sqrt(16)) # Output: 4.0 - Import all items from a module (not recommended):
from math import * print(sqrt(16)) # Output: 4.0
Creating a User-defined Module
You can create your own module by writing functions, variables, and classes in a separate .py file. This file can be imported into other Python scripts.
Example of creating and using a module:
- Create a file called
my_module.py:
# my_module.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
- Now, in another Python script, you can import and use this module:
# main.py
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
print(my_module.add(10, 20)) # Output: 30
In this example:
my_module.pyis the module.- The functions
greet()andadd()are imported and used inmain.py.
The __name__ Variable
The special built-in variable __name__ can help you check if a module is being run directly or imported. This is commonly used to allow or prevent parts of code from being run when the module is imported.
- If a module is being run directly,
__name__is set to'__main__'. - If the module is being imported,
__name__is set to the module’s name.
Example:
# my_module.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print("This is the main program!")
print(greet("Alice"))
If you run my_module.py directly, you will see:
This is the main program!
Hello, Alice!
But if you import the module into another script, the if __name__ == "__main__": block won’t execute:
# main.py
import my_module
Python Standard Library Modules
Python comes with a standard library that contains a vast collection of modules for various tasks, such as math operations, string manipulation, file I/O, and more.
Commonly Used Built-in Modules:
- math: Provides mathematical functions like
sqrt(),sin(),cos(), etc.import math print(math.sqrt(16)) # Output: 4.0 - os: Provides functions for interacting with the operating system, such as file manipulation and environment variables.
import os print(os.getcwd()) # Output: Current working directory - sys: Provides access to system-specific parameters and functions, such as command-line arguments and Python’s runtime environment.
import sys print(sys.version) # Output: Python version - datetime: Allows manipulation of dates and times.
import datetime print(datetime.datetime.now()) # Output: Current date and time - random: Used to generate random numbers.
import random print(random.randint(1, 10)) # Output: Random integer between 1 and 10
Installing Third-party Modules
Many third-party modules are available via Python Package Index (PyPI). You can install these modules using pip, Python’s package manager.
Example of Installing a Third-party Module:
To install the popular requests module (used for making HTTP requests), run:
pip install requests
After installation, you can use it in your Python program:
import requests
response = requests.get("https://www.example.com")
print(response.text) # Output: The HTML content of the page
Organizing Modules
For larger projects, you may want to organize your modules into directories, often referred to as packages. A package is a collection of Python modules in a directory, and it must contain an __init__.py file (even if it’s empty) to be recognized as a package.
Example of Organizing Modules into a Package:
Directory structure:
my_package/
__init__.py
module1.py
module2.py
In module1.py:
# module1.py
def greet(name):
return f"Hello, {name}!"
In module2.py:
# module2.py
def add(a, b):
return a + b
In __init__.py (can be empty, or you can import necessary functions here):
# __init__.py
from .module1 import greet
from .module2 import add
Now, in another script:
# main.py
from my_package import greet, add
print(greet("Alice")) # Output: Hello, Alice!
print(add(10, 20)) # Output: 30
Summary of Key Concepts
- Module: A Python file containing definitions, functions, and statements.
- Importing Modules: Use
importto include the functionality of a module in your program. __name__variable: Differentiates whether the module is run directly or imported.- Standard Library: Python comes with built-in modules like
math,os, andsysfor various tasks. - Third-party Modules: External modules installed using
pipfrom PyPI. - Packages: Organizing multiple modules in directories, and packages must contain an
__init__.pyfile.