In Python, a module is a file that contains Python code. It can define functions, classes, and variables, and it can also include runnable code. Modules allow you to organize and reuse code, making it easier to manage large projects and applications.
A module is simply a Python file with the .py
extension. It can contain functions, classes, variables, and runnable code. Modules are designed to help in organizing the Python code logically into multiple files.
You can create your own module by creating a Python file with a .py
extension and then importing it into other scripts.
Let's say you have a Python file named math_operations.py
:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
This file is now a module, and you can import it into other Python files to use the add
and subtract
functions.
To use a module, you must import it. Python provides several ways to import modules.
import math_operations
result = math_operations.add(5, 3)
print(result) # Output: 8
In this case, the entire math_operations
module is imported, and you access its functions using dot notation (module_name.function_name
).
You can import specific functions from a module to avoid using the module name each time:
from math_operations import add
result = add(5, 3)
print(result) # Output: 8
You can also use an alias to shorten the module name:
import math_operations as mo
result = mo.add(5, 3)
print(result) # Output: 8
Using *
, you can import all the functions from a module, but this is generally discouraged because it can lead to naming conflicts.
from math_operations import *
result = add(5, 3)
print(result) # Output: 8
There are several types of modules in Python:
Python comes with a standard library of built-in modules. These modules provide functionalities that are commonly needed in various applications. Some examples include math
, os
, sys
, random
, and datetime
.
math
Moduleimport math
result = math.sqrt(16)
print(result) # Output: 4.0
These are modules that are not part of Python's standard library but are available via package managers like pip
. Examples include modules like requests
, numpy
, and pandas
.
requests
moduleimport requests
response = requests.get('https://api.example.com')
print(response.status_code)
You need to install external modules using pip
before using them:
pip install requests
These are modules that you or other developers create for specific projects. Custom modules allow for code reuse and better organization of large codebases.
# my_module.py
def greet(name):
return f"Hello, {name}!"
Now, you can import and use the custom module in another Python script:
import my_module
message = my_module.greet("Alice")
print(message) # Output: Hello, Alice!
A package is a collection of modules organized in a directory structure. A package may contain sub-packages and modules. A package is simply a directory containing an __init__.py
file (which can be empty).
my_package/
__init__.py
module1.py
module2.py
To use the modules from the package, you can import them like this:
from my_package import module1
module1.some_function()
Modules help you to break your Python program into smaller, manageable, and reusable components. To use a module, follow these general steps:
.py
file with functions, classes, or variables.import
or from ... import
to access its content.You can specify the path where Python looks for modules by modifying the sys.path
list.
import sys
sys.path.append('/path/to/your/modules')
This will allow Python to search for modules in the specified path.
If you modify a module after importing it, you can use importlib.reload()
to reload the module.
import math_operations
import importlib
# Modify math_operations.py manually or programmatically
importlib.reload(math_operations) # Reload the module to reflect changes
This is particularly useful during development when you want to test changes to the module without restarting the entire program.
__name__
VariableEvery Python module has a built-in variable __name__
. This variable is set to '__main__'
when the module is run directly (not imported). You can use this to write code that runs only when the module is executed directly, not when it is imported.
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
greet("John")
If you run mymodule.py
directly, it will call the greet
function. But if you import it into another script, nothing will happen automatically.
If you're working within a virtual environment, make sure the environment is activated before importing modules installed in it. This ensures that the correct version of the module is used and that there are no conflicts with the system-wide installation.
If you are using a virtual environment and have installed modules locally, ensure the virtual environment is activated before running your script. If not activated, Python will look for modules in the global environment instead of the virtual environment.
Objective: Learn to create and use custom, built-in, and external Python modules.
Create a Custom Module:
utilities.py
.multiply(a, b)
that returns the product of two numbers.# utilities.py
def multiply(a, b):
return a * b
Import and Use the Module:
multiply
function from utilities.py
.multiply(4, 5)
and print the result.# main.py
from utilities import multiply
print(multiply(4, 5)) # Output: 20
Using Built-in Modules:
math
module and use the math.pow(x, y)
function to calculate x
raised to the power of y
.import math
result = math.pow(2, 3)
print(result) # Output: 8.0
Install and Use an External Module:
requests
module using pip
.pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.json()) # Output: GitHub API response
Create a Package:
Create a package named math_operations
with two modules, addition.py
and subtraction.py
.
In addition.py
, define a function add(a, b)
:
# math_operations/addition.py
def add(a, b):
return a + b
In subtraction.py
, define a function subtract(a, b)
:
# math_operations/subtraction.py
def subtract(a, b):
return a - b
Import both functions and use them in a new Python file.
# main.py
from math_operations.addition import add
from math_operations.subtraction import subtract
print(add(10, 5)) # Output: 15
print(subtract(10, 5)) # Output: 5
By using modules, you can better structure your Python projects, promote code reuse, and improve maintainability. Modules are an essential concept in Python programming, and understanding how to use them effectively is key to becoming a proficient Python developer.