So far, you've been using Python's built-in functions and libraries. But what if you create code that you want to reuse across multiple projects, or share with others? That's where creating your own modules comes in! A Python module is simply a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Think of it as a custom toolbox for your Python code.
Let's start by creating a simple module. Imagine you're building a calculator and want to have separate functions for addition, subtraction, multiplication, and division. We can put these into a file named calculator.py.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero!"
return a / bNow that we have our calculator.py file, we can use it in another Python script. To do this, we use the import statement. You can import the entire module, or specific functions from it.
Here's how you would import and use our calculator module in a separate file (let's call it main_app.py):
import calculator
result_add = calculator.add(10, 5)
print(f"10 + 5 = {result_add}")
result_divide = calculator.divide(20, 4)
print(f"20 / 4 = {result_divide}")
result_divide_by_zero = calculator.divide(10, 0)
print(f"10 / 0 = {result_divide_by_zero}")When you run main_app.py, you'll see the results of the calculations. The import calculator line tells Python to look for a file named calculator.py (or a compiled version of it) in the same directory or in its search path and make its contents available.
You can also import specific functions using from ... import .... This can make your code slightly more concise, as you don't need to prefix the function calls with the module name.