Creating Custom Modules in Python
Any Python file can be imported as a module by another file — there's no special syntax needed to "declare" something a module. This is how a program's own code gets organized into multiple files, with related functions and classes grouped together and imported wherever they're needed.
Save a file with the code it should provide
Like helpers.py, containing whatever functions, classes, or variables belong together.
Import it like any standard library module
From another file in the same folder: import helpers.
Access anything it defines
Through helpers.thing, exactly like any other imported module.
from helpers import specific_function
Brings just that one thing in directly, the same as with any built-in module.
if __name__ == "__main__": guards run-only-when-direct code
Lets a file run some code only when executed directly, not when imported by another file.
# helpers.pydef greet(name): return f"Hello, {name}!" PI_APPROX = 3.14 # main.pyimport helpers print(helpers.greet("Ada"))print(helpers.PI_APPROX)Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.