Modules, Imports, and Common Standard Libraries
One of Python's strengths is its rich standard library. Many needs don't require writing from scratch -- thinking first about "does the standard library already have this?" can usually save a lot of time.
Basic import syntax
import math
import json
Access functions from a module using the module name:
print(math.sqrt(16))
You can also import only the objects you need:
from math import sqrt, pi
If a module name is long, you can alias it:
import numpy as np
import pandas as pd
Modules and packages
- A single
.pyfile can be considered a module. - A directory containing multiple modules can typically be considered a package.
When files start multiplying, I prefer splitting by responsibility rather than piling all functions into one script.
if __name__ == "__main__"
The purpose of this check is to make a file both importable and directly runnable:
def main():
print("run as script")
if __name__ == "__main__":
main()
Common scenarios:
- When imported: only reuse functions, don't execute test code
- When run directly: execute demos, debugging, or command-line entry points
Frequently Used Standard Libraries
1. math
Suitable for basic math operations:
import math
print(math.sqrt(9))
print(math.floor(3.8))
print(math.pi)
2. collections
My most commonly used items:
Counter: Countingdeque: Double-ended queuedefaultdict: Dictionary with default values
from collections import Counter, deque, defaultdict
print(Counter("banana"))
queue = deque([1, 2, 3])
mapping = defaultdict(list)
3. pathlib
For handling paths in modern Python, I recommend pathlib over string concatenation everywhere:
from pathlib import Path
root = Path("data")
file_path = root / "users.csv"
print(file_path.exists())
4. json
Suitable for handling JSON files and API responses:
import json
payload = {"name": "alice", "score": 95}
text = json.dumps(payload, ensure_ascii=False)
restored = json.loads(text)
5. itertools
This module is great for handling combinations, permutations, and iterators:
from itertools import product
for pair in product([1, 2], ["a", "b"]):
print(pair)
When to write your own vs. check the standard library first
My current habit:
- First determine if it's a common problem: paths, counting, queues, JSON, time, combinations, random numbers
- If so, check the standard library first
- Only when the standard library isn't enough, bring in third-party libraries