Python for Polyglots
Lesson 9 · Core

Errors, files & with

Python's style is to try the operation and handle the failure, rather than checking everything up front. This is called EAFP: easier to ask forgiveness than permission.

try:
    value = int(text)
except ValueError as e:      # catch specific exceptions (like catch in Java/JS/PHP)
    value = 0
else:
    print("runs only if no exception")
finally:
    print("always runs")

raise ValueError("bad input")   # Python says raise where you'd say throw

Context managers: with

with runs setup, hands you a resource, and always runs cleanup, even when an exception is thrown. It's Python's version of Java's try-with-resources.

with open("in.txt") as f:          # f.close() is guaranteed
    for line in f:                  # a file is iterable, line by line
        print(line.rstrip("\n"))

It's not just for files. Locks, database transactions, temporary directories and timers all use it. Under the hood, with x calls x.__enter__() at the start and x.__exit__() at the end.

Read a file safely
with open("data.txt") as f:
    first = f.readline()
Files work here too (in-memory)
with open("notes.txt", "w") as f:
    f.write("alpha\nbeta\ngamma\n")

with open("notes.txt") as f:
    for n, line in enumerate(f, start=1):
        print(n, line.rstrip("\n"))

for text in ["42", "4.2", None]:
    try:
        print(int(text))
    except (ValueError, TypeError) as e:
        print(type(e).__name__, "->", e)
Quiz: Which exception does int("3.5") raise?
int("3.5")
Exercise 24: Safe int conversion

Convert text to an int, or return default if it can't be converted.

safe_int("42") → 42; safe_int("abc") → 0; safe_int(None) → 0

Exercise 25: Count lines in a file

Return the number of lines in the text file at path.

Exercise 26: Longest line

Return the longest line in the file, without its trailing newline. Return "" for an empty file.