import module
from module import name
import module as alias
Example
import json
from pathlib importPathfrom collections import defaultdict,Counterimport numpy as np # common alias convention
data = json.dumps({"key":"value"})print(data)
Output
{"key": "value"}
Note Convention: standard library imports first, then third-party, then local. Separate groups with a blank line. Use isort to auto-format.
# my_module.pydefcompute_tax(price:float, rate:float=0.08)->float:return price * rate
if __name__ =="__main__":# Only runs when executed directly, not when imported
result =compute_tax(100)print(f"Tax: ${result:.2f}")
Output
Tax: $8.00
Note This guard prevents code from running when the module is imported by another file. Essential for reusable modules that also serve as scripts.
# utils.py
__all__ =["format_price","validate_email"]defformat_price(amount:float)->str:return f"${amount:,.2f}"defvalidate_email(email:str)->bool:return"@"in email
def_internal_helper():# not exportedpass
Note __all__ defines what 'from module import *' exports. It does not prevent direct imports of unlisted names. Prefix internal helpers with underscore by convention.
Note Relative imports only work inside packages (directories with __init__.py). They fail if you run the file directly as a script. Use -m flag: python -m package.module.
# myapp/# ├── __init__.py # makes it a package# ├── config.py# ├── models/# │ ├── __init__.py# │ └── user.py# └── utils/# ├── __init__.py# └── formatting.py# In __init__.py, expose public API:# from .config import Settings# from .models.user import User
Note __init__.py runs when the package is imported. Use it to define the package's public interface. It can be empty for simple packages.
import importlib
mod = importlib.import_module('name')
Example
import importlib
# Import module by string name
json_mod = importlib.import_module("json")
result = json_mod.dumps({"dynamic":True})print(result)# Reload a module during development# importlib.reload(my_module)
Output
{"dynamic": true}
Note Dynamic imports are useful for plugin systems and lazy loading. importlib.reload() re-executes the module but existing references to old objects are not updated.
dynamic importimportlibimport by stringreload moduleplugin system
# Install a package# pip install requests# Install specific version# pip install requests==2.31.0# Install from requirements file# pip install -r requirements.txt# Show installed packages# pip list# Show details about a package# pip show requests
Note Consider using pip-tools, poetry, or uv for reproducible dependency management. pip freeze captures transitive deps, which can be fragile across platforms.