A Python module is simply any .py file containing functions, classes, or constants that other files can import and reuse. Grouping related modules inside a directory creates a package, keeping large codebases structured and testable.
Python ships with a rich standard library of built-in modules (os, pathlib, json, datetime), and import lets you load both standard modules and your own files.
You can import an entire module, pick specific symbols with from ... import, or give long module names a short alias with as.
import math
from datetime import date as dt_date
radius = 5
area = math.pi * (radius ** 2)
print(f"Area on {dt_date.today()}: {area:.2f}")
if __name__ == "__main__": GuardWhen Python imports a file, it executes top-level code inside that file. Wrapping script entry code inside if __name__ == "__main__": ensures test code runs only when you execute the file directly, not when another module imports it.
def format_slug(text: str) -> str:
return text.strip().lower().replace(" ", "-")
if __name__ == "__main__":
print(format_slug("Python Modules"))
from module import *): Star imports pollute your namespace and make it impossible to tell where functions came from.ImportError; move shared helpers into a third module.email.py or math.py shadows the standard library.__init__.py do inside a folder?__init__.py marks a directory as a regular Python package and lets you expose selected package exports in one place.
Python checks sys.modules cache first, then the script's directory, PYTHONPATH, and installed site-packages listed in sys.path.
Run dir(module_name) to list its attributes or help(module_name) in the interactive shell.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.