Imports & Modules in Python

From the Python cheat sheet ยท Modules & Virtual Environments ยท verified Jul 2026

Imports & Modules

Import standard library and custom modules; structure runnable scripts.

python
import os
from pathlib import Path
from datetime import datetime, timedelta
from collections import defaultdict, Counter
import json

# Alias
import numpy as np

# Import specific names
from math import sqrt, pi

# Script entry point โ€” only runs when invoked directly,
# not when the module is imported
def main():
    print("Running as a script")

if __name__ == "__main__":
    main()
๐Ÿ’ก A module is just a .py file โ€” a package is a directory with __init__.py
โšก Always wrap script entry logic in if __name__ == "__main__": so imports stay clean
๐Ÿ“Œ Avoid "from x import *" in production โ€” it makes it unclear where names come from
๐ŸŸข Use relative imports (from . import) inside packages, absolute imports elsewhere
importsmodulespackages

More Python tasks

Back to the full Python cheat sheet