import module
from module import name
import module as alias
example
import json
from pathlib import Path
from collections import defaultdict, Counter
import 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.
import modulefrom importimport asalias import
__name__ == '__main__' Guard
syntax
if __name__ == '__main__':
...
example
# my_module.pydef compute_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.
Note __all__ defines what 'from module import *' exports. It does not prevent direct imports of unlisted names. Prefix internal helpers with underscore by convention.
__all__export controlpublic apistar import
Relative Imports
syntax
from . import sibling
from .. import parent_module
from .sibling import name
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.