Python Modules
Modules in Python are files containing Python code. They help organize code into manageable and reusable parts. Modules can contain functions, classes, variables, and runnable code. Python has a rich standard library of modules, and you can also create or install custom ones.
Types of Modules
- Built-in Modules:
- These are already installed by Python, for example:
math
,os
,sys
, etc. - You do not need to install them; they can be imported and used directly.
2. Standard Library Modules:
- Python offers a rich variety of modules that can accomplish most of the tasks involved, such as
datetime
,random
,json
, etc.
3. External Modules:
- Those are third-party modules. These modules are not within the reach of the standard library, examples including
numpy
,pandas
, etc. - These need to be installed with the help of an external package manager like
pip
.
4. User-defined Modules:
- These are modules that you develop to structure your personal code.
Using a Module
Importing a Module
You can import a module using the import
statement.
# Example: Importing the math module
import math
print(math.sqrt(16)) # Outputs 4.0
Importing Specific Items
You can import specific functions, classes, or variables.
from math import sqrt, pi
print(sqrt(25)) # Outputs 5.0
print(pi) # Outputs 3.141592653589793
Aliasing Modules
Use the as
keyword to assign an alias.
import math as m
print(m.sqrt(9)) # Outputs 3.0
Importing All Items
This imports everything from a module but is generally discouraged due to potential name conflicts.
from math import *
print(sin(0)) # Outputs 0.0
Creating a User-Defined Module
- Create a Python file with a
.py
extension. - Define functions, variables, or classes in it.
Example: Create a module named my_module.py
# my_module.py
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
Using the module in another file:
import my_module
print(my_module.greet("Alice")) # Outputs "Hello, Alice!"
print(my_module.pi) # Outputs 3.14159
Module Search Path
When you import a module, Python searches for it in the following order:
- Built-in modules, such as
math
. - Directories in the
sys.path
variable, including:- The directory of the current script.
- Directories listed in environment variables such as
PYTHONPATH
. - Standard library directories.
Example: Checking the search path
import sys
print(sys.path)
Packages: Modules Organized in Directories
A package is a collection of related modules grouped into a directory. It must contain an __init__.py
file (can be empty).
Example: Package structure
mypackage/
init.py
module1.py
module2.py
Using the package:
from mypackage import module1
Popular Built-in Modules
os
: Interact with the operating system.
import os
print(os.getcwd()) # Get current working directory
2. sys
: Access Python runtime information.
import sys
print(sys.version) # Python version
3. math
: Perform mathematical operations.
import math
print(math.factorial(5)) # Outputs 120
4. datetime
: Handle dates and times.
from datetime import datetime
print(datetime.now()) # Current date and time
5. random
: Generate random numbers.
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
Best Practices for Using Modules
- Use descriptive names for your custom modules to avoid conflicts.
- Do not
import module *
unless really needed. - Focus the modules on having a single responsibility.
- Use virtual environments for external modules to avoid dependency conflicts.