.py file, then import exactly what you need wherever you need it. This page takes you from importing a single function all the way to structuring a multi-file project.
What is a Module?
A module is any Python file with a.py extension. Every variable, function, and class defined in that file becomes part of the module’s namespace and can be imported by other files.
Suppose you create calculator.py:
main.py in the same directory:
Import Styles
- import module
- from module import name
- import module as alias
- from module import *
Imports the entire module. Access members using Best when you use many things from the module and want to keep the namespace clear.
module.name:The if __name__ == '__main__' Pattern
When Python runs a file directly, it sets the special variable __name__ to "__main__". When the file is imported by another module, __name__ is set to the module’s own name instead. This lets you guard code that should only run when the file is executed directly:
Built-in Standard Library Modules
Python ships with a comprehensive standard library — no installation needed.math — Mathematics
random — Random Numbers
datetime — Dates and Times
os — Operating System Interface
sys — System Information
Creating Your Own Module
1
Write your functions in a .py file
Create
utils.py in your project directory:2
Import and use it in another file
In
main.py (same directory):What is a Package?
A package is a directory that contains one or more module files plus a special file named__init__.py. The presence of __init__.py tells Python to treat the folder as an importable package.
Simple Package Structure
math_utils.py:
text_utils.py:
__init__.py — expose the most-used names at the package level:
main.py:
Realistic Multi-File Project Layout
As your project grows, a typical structure looks like this:Key Takeaways
Module = .py file
Any
.py file is a module. Break your code into files the moment a single file grows hard to navigate.Standard library first
Before installing a third-party package, check whether
math, datetime, os, random, or another built-in module already solves your problem.__init__.py controls the API
Use
__init__.py to decide which names are public. Import the most-used names there so consumers don’t need to know the internal file structure.if __name__ == '__main__'
Guard executable code with this pattern to keep modules both importable as a library and runnable as a script.