Handbooks / Python / Chapter 3
Errors and the Standard Library
7 pages · ~5 min✓ Reviewed
Builds on Functions and Closures.
Exception Handling Mental Model
1. Raise, Unwind, Run Order
- An exception is an object raised at runtime
- It unwinds the call stack to the first matching
except - Uncaught: the program ends with a traceback
finallyruns even afterreturn,breakor an uncaught error
- tryrun body
- exceptonly if raised
- elseonly if no error
- finallyalways
python
def f(): try: return "try" finally: print("finally") print(f())
finally runs before the return value is delivered
output
finally try
Raising and Custom Exceptions
1. Raising and Chaining
raise ValueError('msg')raises a new exception- Bare
raiseinsideexceptre-raises the current one, traceback intact
| Form | Sets | Traceback |
|---|---|---|
raise B from A |
Collections: Counter, defaultdict, deque
1. Counter
Counter(iterable)counts hashables.most_common(n)gives the top n(item, count)pairs- A missing key gives 0, not
KeyError +and-combine counters;-drops counts of 0 or less
python
from collections import Counter c = Counter('banana') print(c.most_common(2), c['z']) print(c + Counter('an'))
output
[('a', 3), ('n', 2)] 0 Counter({'a': 4, 'n': 3, 'b': 1})
pathlib and json
1. Paths and files
Path('data') / 'file.txt'joins with /Path.cwd(),Path.home();.parent.name.stem.suffixbeat slicingread_text(encoding='utf-8')andwrite_text(s): whole fileexists(),is_file(),glob('*.py'),mkdir(parents=True, exist_ok=True)
python
from pathlib import Path p = Path('out') / 'log.txt' p.parent.mkdir(parents=True, exist_ok=True) p.write_text('hi', encoding='utf-8') print(p.read_text(encoding='utf-8'), p.stem, p.suffix)
Typing Basics and the GIL
1. Type Hints
- Hints annotate only; Python never enforces them at runtime
mypyandpyrightcheck them
python
def f(x: int, y: str = 'a') -> bool: return x > 0
| Form | Meaning |
|---|---|
list[int] |
Python Essentials Cheat Sheet
1. Errors
elseruns on success,finallyalwaysexceptorder: specific before general- Bare
raisere-raises;raise X from echains from Nonehides the chain,__context__is still keptclass AppError(Exception); catchException, notBaseException
python
try: run() except KeyError as e: raise AppError("bad") from e else: ok() finally: close()
Check yourself
What does this print?
fin, thentry- finally runs before the function actually returns
def f(): try: return 'try' finally: print('fin') print(f())
After d = defaultdict(int) and a read of d['a'], what is len(d)?
1: reading a missing key inserts it- Test safely with
d.get('a')or'a' in d