As your Python programs grow larger, putting all your code in a single file becomes unwieldy. Modules provide a way to organize your code into separate .py files, making your programs more manageable, reusable, and readable. A module is simply a file containing Python definitions and statements.
What are Modules?
- A module is a
.pyfile that contains Python code (functions, classes, variables, etc.). - When you import a module, you gain access to its contents in your current script.
- Python has a rich standard library of built-in modules (e.g.,
math,random,datetime). - You can also create your own modules.
Creating Your Own Module
Let's create a simple module. Save the following code in a file named my_calculator.py:
python# my_calculator.py def add(a, b): """Returns the sum of two numbers.""" return a + b def subtract(a, b): """Returns the difference of two numbers.""" return a - b def multiply(a, b): """Returns the product of two numbers.""" return a * b def divide(a, b): """Returns the division of two numbers, handles division by zero.""" if b == 0: return "Error: Cannot divide by zero!" return a / b PI = 3.14159
Importing Modules
To use the functions and variables defined in my_calculator.py in another Python script (e.g., main_app.py), you need to import it. Make sure both files are in the same directory for Python to find my_calculator.py easily.
import module_nameThis is the most common way. It imports the entire module, and you access its contents usingmodule_name.item_name.
main_app.py:
pythonimport my_calculator print(my_calculator.add(10, 5)) # Output: 15 print(my_calculator.subtract(10, 5)) # Output: 5 print(my_calculator.PI) # Output: 3.14159 # Using a function that handles an error print(my_calculator.divide(10, 0)) # Output: Error: Cannot divide by zero!
import module_name as aliasIf the module name is long, or you want to avoid name clashes, you can give it an alias.
pythonimport my_calculator as mc print(mc.add(7, 3)) print(mc.multiply(4, 2))
from module_name import item1, item2, ...This imports specific functions or variables directly into your current namespace. You can then use them without themodule_name.prefix.
pythonfrom my_calculator import add, PI print(add(100, 20)) print(PI) # print(subtract(50, 10)) # This would cause a NameError, as subtract was not imported
from module_name import *(Avoid in most cases) This imports all public names from the module into your current namespace. While convenient, it can lead to name clashes (where a function in the module has the same name as one you defined or imported elsewhere) and makes it harder to tell where a function or variable came from. It's generally discouraged in production code.
pythonfrom my_calculator import * print(add(2, 2)) print(subtract(5, 1)) print(PI)
Python Standard Library Modules
Python comes with many useful built-in modules.
For example:
math: Provides mathematical functions (e.g.,sqrt,ceil,floor,pi).random: For generating random numbers (e.g.,random.randint,random.choice).datetime: For working with dates and times.
pythonimport math import random print(math.sqrt(16)) # Output: 4.0 print(math.pi) # Output: 3.141592653589793 print(random.randint(1, 10)) # Output: A random integer between 1 and 10 (inclusive)
Modules are essential for building larger, well-structured applications. They promote code reusability and maintainability by allowing you to break your programs into logical, self-contained units.
Key Takeaways:
- Modules (
.pyfiles) help organize Python code into reusable units. - Use
import module_nameto access module contents viamodule_name.item. - Use
import module_name as aliasfor shorter names. - Use
from module_name import itemto bring specific items into the current namespace directly. - Avoid
from module_name import *due to potential name clashes. - Leverage Python's extensive standard library (e.g.,
math,random).