What If I Could Make My Own Module?
The problem...
You have functions that work. Functions you've tested, functions you trust.
And you keep copying them from one script to another.
There's a better way.
The idea!
Any Python file can be a module.
You already import from Python's standard library — import random, import math. Those are just Python files sitting somewhere on your machine.
Your files work the same way. Write a function in one file. Import it in another. Use it anywhere.
Making it real
Create a file called utils.py:
# utils.py
def greet(name):
return f"Hello, {name}."
def celsius_to_fahrenheit(c):
return c * 9/5 + 32
Now in another file — same folder:
# main.py
import utils
print(utils.greet("Raven"))
print(utils.celsius_to_fahrenheit(100))
Output:
Hello, Raven.
212.0
That's it. utils.py is your module. main.py imports it.
from import — bring in one function
from utils import greet
print(greet("Wolf"))
No prefix needed. Just the function name.
Why this matters
One function. Ten scripts that need it. You write it once — in one place. You fix it once. You test it once.
That's not just convenience. That's how real projects are structured. Logic lives in modules. Scripts import what they need. Nothing is duplicated.
The rule
The module file must be in the same folder as the script that imports it — or Python won't find it.
project/
utils.py ← your module
main.py ← imports from utils
if __name__ == "__main__"
When Python imports a file, it runs it. If your module has code outside functions — it runs on import too. That's usually not what you want.
The fix:
# utils.py
def greet(name):
return f"Hello, {name}."
if __name__ == "__main__":
print(greet("Raven")) # only runs when utils.py is run directly
# not when it's imported
This block runs only when the file is executed directly — not when imported. Use it for tests, demos, or any code you don't want running on import.
Heads up!
- The module file must be in the same folder as the importing script
- Don't name your module the same as a standard library module —
random.pywould shadow Python's ownrandom - Code outside functions runs on import — use
if __name__ == "__main__"to protect it - Any
.pyfile is a potential module — no special setup needed
The mindset shift
Stop thinking: "I'll write everything in one file."
Start thinking: "What belongs together? What will I reuse? That goes in its own module."
What you should understand now
- Any
.pyfile can be imported as a module import utils— access withutils.function()from utils import function— use directly- Module must be in the same folder as the importing script
if __name__ == "__main__"protects code from running on import