Learn Python
>>> modules_packages.custom_modules

Creating Custom Modules in Python

#concept

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.

#how it works
1

Save a file with the code it should provide

Like helpers.py, containing whatever functions, classes, or variables belong together.

2

Import it like any standard library module

From another file in the same folder: import helpers.

3

Access anything it defines

Through helpers.thing, exactly like any other imported module.

4

from helpers import specific_function

Brings just that one thing in directly, the same as with any built-in module.

5

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.

#example
# helpers.py
def greet(name):
return f"Hello, {name}!"
 
PI_APPROX = 3.14
 
 
# main.py
import helpers
 
print(helpers.greet("Ada"))
print(helpers.PI_APPROX)
Output
Hello, Ada!
3.14
1helpers.py defines a function and a variable — nothing marks it as special, it's a perfectly ordinary Python file.
2main.py, in the same folder, imports it with import helpers, exactly as it would import any built-in module.
3helpers.greet("Ada") and helpers.PI_APPROX both work through the module prefix, accessing what the other file defined.
#use cases
Splitting a growing program into logically organized files, instead of one enormous script
Sharing a set of common utility functions across several different scripts in the same project
Keeping configuration values or constants in one dedicated file, imported wherever they're needed
Using if __name__ == '__main__': to let a file work both as a standalone script and as an importable module

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.