Creating Your Own Modules
Overview
You can build your own modules by defining functions, variables, or classes in separate .py files. This lesson shows how to import those custom modules into other scripts to reuse code and maintain consistency across multiple programs, helping you organize your projects better.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Creating modules: How to create a Python file that can be imported as a module.
- Importing custom modules: How to import modules you've created yourself.
- Module organization: How to organize functions and variables in modules.
- Best practices: How to structure modules for reusability and clarity.
Why This Matters
As your programs grow, you'll want to reuse code across multiple files. Creating your own modules lets you write functions once and use them in many programs. This saves time, reduces errors, and makes your code more organized. Instead of copying and pasting the same functions everywhere, you can create a module and import it!
Step 1: Creating a Simple Module
Any Python file (ending in .py) can be a module. To create a module, simply create a Python file with functions, variables, or classes:
# File: greetings.py (this becomes a module)
def say_hello(name):
"""Greet someone by name."""
return f"Hello, {name}!"
def say_goodbye(name):
"""Say goodbye to someone."""
return f"Goodbye, {name}!"
# Module-level variable
GREETING_MESSAGE = "Welcome to Python!"
Create a Python File
Create a file called greetings.py. The filename (without .py) becomes the module name.
Add Functions or Variables
Define functions, variables, or classes in the file. These will be available when the module is imported.
Save in Same Directory
Save the module file in the same directory as the file that will import it, or in a location Python can find.
Key Concept: When you create a file called greetings.py, Python treats it as a module named greetings. You can then import it using import greetings and use its functions with greetings.say_hello()!
Mini Practice #1: Understanding Module Creation
Try It YourselfIn a real project, you would create a separate file. For this practice, we'll simulate it:
What happened? In a real project, you would save these functions in a file called greetings.py. Then, in another file, you could write import greetings and use greetings.say_hello("Alice"). This lets you reuse the same functions across multiple programs!
Step 2: Importing Your Custom Module
Once you've created a module file, you can import it just like built-in modules:
# File: main.py
import greetings
# Use functions from the module
message = greetings.say_hello("Alice")
print(message) # Output: Hello, Alice!
# Access module variables
print(greetings.GREETING_MESSAGE) # Output: Welcome to Python!
Import Statement
Use import greetings to load your custom module. Python looks for greetings.py in the current directory.
Use Module Functions
Call functions using greetings.say_hello(). The dot notation tells Python which module the function belongs to.
Access Variables
Access module-level variables like greetings.GREETING_MESSAGE using the same dot notation.
File Location Matters
Python looks for modules in:
- The directory containing your script
- Directories in
sys.path - Standard library locations
For simple projects, keep your module files in the same folder as your main script!
Step 3: Selective Import from Custom Modules
You can also import specific functions from your custom modules:
# Import only what you need
from greetings import say_hello
# Use directly without module prefix
message = say_hello("Bob")
print(message) # Output: Hello, Bob!
Remember: When you use from greetings import say_hello, you can call say_hello() directly without the greetings. prefix. This is convenient but can cause naming conflicts if you have another function with the same name!
Mini Practice #2: Module Organization
Try It YourselfCreate functions that could be in a math utilities module:
What happened? In a real project, you would save these functions in math_utils.py. Then in other files, you could write import math_utils and use math_utils.add(5, 3). This keeps related functions together and makes your code more organized!
Step 4: Best Practices for Creating Modules
Follow these guidelines when creating your own modules:
Use Descriptive Names
Name your module files clearly. math_utils.py is better than stuff.py.
Group Related Functions
Put related functions together. A string_helpers.py module should contain string-related functions.
Add Docstrings
Document your functions with docstrings so others (and you) know what they do.
Keep Modules Focused
Each module should have a clear purpose. Don't mix unrelated functions in one module.
End-of-Lesson Exercises
Exercise 1: Create a Simple Module
Create functions for a calculator.py module: add(a, b) and subtract(a, b). Then use them to calculate 10 + 5 and 10 - 5. Print both results.
Define the functions, then call them with the values.
Exercise 2: Import and Use Module Functions
Simulate importing from a module: create a function greet(name) that returns "Hello, {name}!". Then use it to greet "Python" and print the result.
Define the function, then call it with "Python".