Skip to content

Module 14 · Python Modules and Packages — topic 2 of 13

Creating modules

Writing your own modules: putting functions, classes and constants in a file, the if __name__ == "__main__" guard, private helpers with underscores, __all__, and module documentation.

Beginner 10 min read·Lesson 210 of 306 in Python Programming

Learning objectives

  • Write a reusable module
  • Use the __main__ guard correctly
  • Control a module's public interface with naming and __all__

Definition

Creating a module means writing a .py file whose top-level functions, classes and constants are meant to be imported by other code. Code that should only run when the file is executed directly goes under if __name__ == "__main__":.

Introduction

Once you've written a useful function twice, it's time to put it in a module. A well-written module can be imported anywhere and also run on its own for testing or demos.

Why it matters

Good modules are the building blocks of larger programs: easy to import, free of surprising side effects, and clear about what they offer.

Detailed explanation

Put definitions at the top level: functions, classes and constants (UPPER_CASE). Importing then makes them available as module.name.

Avoid code that does work at import time (printing, reading files, network calls). Importing should be fast and silent.

Code under if __name__ == "__main__": runs only when the file is executed directly (python tool.py), not when it is imported — ideal for demos, quick tests and command-line entry points.

Names starting with an underscore (_helper) are internal by convention and are not imported by from module import *.

__all__ = ["name1", "name2"] lists the public names exported by from module import *.

A module docstring and function docstrings document the interface; help(module) displays them.

Keep the module importable from where it will be used: in the same folder as the main script, or inside a package (see Packages).

Syntax

Python
"""Utility functions for numbers."""
__all__ = ["square"]
def square(x):
return x * x
def _internal():
...
if __name__ == "__main__":
print(square(5)) # only when run directly
  • Top-level definitions become the module's interface.
  • __main__ guard for run-only code.
  • _names and __all__ control what is public.

Code examples

A module of helpers

Python
from pathlib import Path
import importlib
Path("mathutils.py").write_text('''def square(x):
return x * x
def average(values):
return sum(values) / len(values)
''', encoding="utf-8")
importlib.invalidate_caches()
import mathutils
print(mathutils.square(7), mathutils.average([2, 4, 9]))
Output
49 5.0

The __main__ guard

Python
from pathlib import Path
import importlib
import subprocess
import sys
Path("tool.py").write_text('''def double(x):
return x * 2
if __name__ == "__main__":
print("running tool.py directly")
print(double(21))
''', encoding="utf-8")
importlib.invalidate_caches()
import tool
print("imported, __name__ is", tool.__name__, "->", tool.double(5))
result = subprocess.run([sys.executable, "tool.py"], capture_output=True, text=True)
print(result.stdout, end="")
Output
imported, __name__ is tool -> 10
running tool.py directly
42

More examples

Public and private names

Python
from pathlib import Path
import importlib
Path("shapes.py").write_text('''"""Area helpers for simple shapes."""
import math
__all__ = ["circle_area", "rectangle_area"]
UNITS = "cm"
def _check(*values):
if any(v < 0 for v in values):
raise ValueError("sizes must be non-negative")
def circle_area(r):
_check(r)
return round(math.pi * r * r, 2)
def rectangle_area(w, h):
_check(w, h)
return w * h
''', encoding="utf-8")
importlib.invalidate_caches()
from shapes import *
print(circle_area(2), rectangle_area(3, 4))
print("UNITS" in dir(), "_check" in dir())
import shapes
print(shapes.UNITS, shapes.__doc__)
try:
shapes.rectangle_area(-1, 2)
except ValueError as e:
print(e)
Output
12.57 12
False False
cm Area helpers for simple shapes.
sizes must be non-negative

Step-by-step explanation

  • from shapes import * imports only the names in __all__.
  • UNITS and _check are not star-imported but are still reachable as shapes.UNITS and shapes._check.
  • The private helper validates inputs for both public functions.

Expected output

Running “Public and private names” prints exactly:

TextOutput
12.57 12
False False
cm Area helpers for simple shapes.
sizes must be non-negative

Practical applications

  • A utils.py module shared by several scripts.
  • Command-line tools whose functions are also importable.

Best practices

  • Keep import side-effect free.
  • Use the __main__ guard for demos and CLIs.
  • Document the module and mark internals with _.

Common mistakes

Work at import time

Avoid

# report.py
data = load_huge_file()
print("report ready")

Prefer

def build_report():
data = load_huge_file()
...
if __name__ == "__main__":
build_report()

Importing the module would be slow and print unexpectedly.

Important notes

  • python -m module_name runs a module as a script with __name__ set to "__main__".

Key takeaways

  • A module is a file of reusable definitions.
  • __main__ guard separates running from importing.
  • _names and __all__ define the public interface.

Try it yourself

  1. 1
    Create a validators.py module with is_email and is_phone and a __main__ demo.
  2. 2
    Add __all__ to a module and check what from module import * brings in.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateCode under if __name__ == "__main__": runs when…
Practise this topic