Python Modules
Python Modules: Importing Files, Packages, and Entry Guards
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.
Importing Modules and Using Aliases
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}")
The if __name__ == "__main__": Guard
When 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"))
Common Mistakes to Avoid
- Using wildcard imports (
from module import *): Star imports pollute your namespace and make it impossible to tell where functions came from. - Circular imports: File A importing File B while File B imports File A at top level triggers
ImportError; move shared helpers into a third module. - Naming local files after standard modules: Calling your script
email.pyormath.pyshadows the standard library.
Frequently Asked Questions
What does __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.
Where does Python search when importing modules?
Python checks sys.modules cache first, then the script's directory, PYTHONPATH, and installed site-packages listed in sys.path.
How do I inspect functions inside an unfamiliar module?
Run dir(module_name) to list its attributes or help(module_name) in the interactive shell.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.