Writing Your Own Modules
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Any .py file you write is already a module. Put useful functions in one file, then import that file from another. Python also lets a file know whether it was started directly or imported.
A file is a module
Own module is a .py file you write yourself. Another file in the same folder can import it by its file name, without the .py ending.
Copy-pasting a function into five programs means five places to fix. Put it in one file, such as shop_tools.py, and import it. Both files sit in the same folder.
# shop_tools.pydef total_with_tax(price, rate): return price * (1 + rate)# main.py (same folder)import shop_toolsprint(shop_tools.total_with_tax(200, 0.18))The file name without .py becomes the module name. Running main.py prints 236.0. To run it yourself, save the two files side by side and run python main.py.
The main guard
Main guard is the line if __name__ == "__main__":. Code under it runs only when the file is started directly, not when another file imports it.
When you import a file, Python runs it from top to bottom. A test line at the bottom would then run on every import. Python sets __name__ to tell the two cases apart.
def greet(name): return f"Welcome, {name}"
print(__name__)if __name__ == "__main__": print(greet("Asha"))Example 1 · A reusable function with a guard
def total_with_tax(price, rate): return round(price * (1 + rate), 2)
if __name__ == "__main__": print(total_with_tax(200, 0.18)) print(total_with_tax(99.5, 0.05))236.0 104.48
What this code does
- The function is the part other files can import and reuse.
- The two print lines run only when this file is started directly.
round(..., 2)keeps two decimal places.
Example 2 · What __name__ holds
import math
print(__name__)print(math.__name__)__main__ math
What this code does
- The file you run is
__main__. - An imported module reports its own name.
math.__name__ismath.
Run directly, __name__ is "__main__", so the guarded line runs. When another file imports this one, __name__ is the file name instead, and the guarded block is skipped.
Where Python looks for a module
Import path is the ordered list of places Python searches for a module. It is kept in sys.path. The first match wins, and no match is an error.
When you write import report, Python searches in a fixed order: the folder of your script first, then the standard library, then installed packages. The first match wins.
try: import report_2026except ModuleNotFoundError as err: print(err)Example 3 · A missing module is an ImportError
try: import billing_reportsexcept ImportError as err: print(type(err).__name__) print(err.name)
print(issubclass(ModuleNotFoundError, ImportError))ModuleNotFoundError billing_reports True
What this code does
ModuleNotFoundErroris a more specific kind ofImportError, soexcept ImportErrorcatches it.- The error's
nameattribute holds the module that was missing.
If no place has the module, Python raises ModuleNotFoundError. Do not name your own file random.py or math.py: your folder is searched first, so your file would hide the real module.
Next step
Check your understanding
9 quick questions