Python Modules
Python · Functions & OOP
Theory
A module is simply a .py file containing functions, classes and variables that other code can import. A package is a folder of modules. import math loads the module and gives you the name math, so you write math.sqrt(16); from datetime import datetime brings one name in directly; import pandas as pd adds a short alias.
When you import, Python first checks whether the module is already loaded (sys.modules), then searches the folders listed in sys.path - your script's folder, the standard library and installed packages. The module's code runs once on first import and the result is cached. The standard library (math, json, datetime, re, os) ships with Python; third-party packages like pandas are installed with pip.
Why we use it
Modules let you split a large program into organised files and reuse code - your own or thousands of ready-made libraries - instead of writing everything from scratch.
When to use it
Import a module whenever you need its functionality, and move your own reusable functions into a module once a script grows. Avoid from module import *, which hides where names came from and can overwrite your own names.
How it works
- import math
- Already in sys.modules? Yes: Reuse the cached module. No: Search the folders in sys.path.
- Module file found? Yes: Run its code once and cache it. No: Raise ModuleNotFoundError.
- Bind the name math in your namespace
- Use math.sqrt(16) -> 4.0
Syntax
import module_name
from module import nameExample
import pandas as pd
from datetime import datetimeKey points
- pip installs third-party modules/packages
- Standard library modules ship with Python by default
- A module's code runs only once per program, on first import
- Use aliases like import numpy as np for readability
- if __name__ == '__main__': keeps test code from running on import