Creating Your Own Modules
Creating Your Own Modules
Python includes many built-in modules.
But you can also create your own modules to organize your code.
This is useful when projects become bigger.
What Is Your Own Module?
Your own module is simply a .py file you create that stores reusable code.
It can contain:
- functions
- variables
- classes
Why Create Your Own Modules?
They help you:
- reuse code
- keep files smaller
- organize projects
- separate responsibilities
Example Project
Instead of one large file:
main.py
Use:
main.py
helpers.py
Create a Module
Create a file named:
helpers.py
Add:
def greet(name):
print("Hello", name)
def add(a, b):
return a + b
Use the Module
Create:
main.py
Add:
import helpers
helpers.greet("Tom")
print(helpers.add(2, 3))
Output
Hello Tom
5
Import Specific Functions
from helpers import greet
greet("Sara")
Output
Hello Sara
Module with Variables
# settings.py
theme = "dark"
language = "English"
Use it:
import settings
print(settings.theme)
Output
dark
Module with Classes
# users.py
class User:
def hello(self):
print("Welcome")
Use it:
from users import User
u = User()
u.hello()
Output
Welcome
Common Beginner Errors
Wrong File Name
The file name is the module name.
Typing Code Outside the File
Make sure code is saved inside the module file.
Circular Imports
Do not make two files import each other yet.
Code Along
Create math_tools.py with:
double(n)square(n)
Use both in main.py.
Mini Challenge
Create:
messages.py
Add:
hello()bye()
Import both functions and run them.
Expected output:
Hello
Goodbye
Real World Use Case
Real apps use custom modules for users, payments, reports, settings, database tools, and utilities.
Quiz
- What is a custom module?
- Why create your own modules?
- Can modules store classes?
- What is the module name if the file is
tools.py?
Assignment
Create a module with two functions and one variable, then import and use all three.
Summary
You learned how to create your own Python modules and organize reusable code into separate files.