Lesson 12 of 20 · 16m
Bytes and Encodings: The Boundary That Corrupts Silently
str and bytes split at encode/decode, open() silently uses the locale encoding, and normalization decides whether two identical-looking names are actually equal.
Every byte your program touches was encoded by someone. .encode() turns str into bytes; .decode() turns octets back into code points — and the line between them is where the bugs live, because str is a sequence of Unicode code points and bytes is a sequence of octets and pretending they are the same thing is exactly what Python 2 did, badly.
The discipline that holds: decode at the boundary, str inside, encode at the boundary. Everything between is Unicode.
The trap that ships: open()
open(path) without encoding= uses locale.getpreferredencoding(False) — UTF-8 on a modern Linux box, cp1252 on a Western Windows machine. A file written in UTF-8 and read as cp1252 produces mojibake — café becomes café — and no error, so it sails through CI. The other direction fails loudly: cp1252 bytes like the smart quotes 0x93/0x94 are invalid UTF-8 sequences and raise UnicodeDecodeError. Same source, different result, machine-dependent — the worst class of bug there is.
PEP 540's -X utf8 flag and PYTHONUTF8=1 (3.7) force UTF-8 for open, stdin, stdout regardless of locale; PEP 686 makes UTF-8 mode the default in Python 3.15. Until you're on 3.15: encoding="utf-8" on every open(), every time.
errors= decides what bad bytes do
strict raises — the right default for data you trust. replace emits �. ignore deletes the offending characters silently — a data-corruption machine wearing a convenience flag. surrogateescape (PEP 383) smuggles undecodable bytes into lone surrogates so a filename that isn't valid UTF-8 round-trips byte-for-byte; it's how os.listdir survives filesystems that store arbitrary bytes in names.
Two type traps live at the boundary. str(b"data") returns "b'data'" — a repr, not a decode; the quotes are literally in the string. bytes("data") raises TypeError because the encoding argument is mandatory. Both bugs hide in code that appears to work.
os.fsencode/os.fsdecode are the filesystem-flavored wrappers — they use the filesystem encoding with surrogateescape, which is what makes sys.argv and os.environ survive hostile bytes. And sys.stdin/sys.stdout are TextIOWrappers with their own encoding attribute, set from the locale — PYTHONIOENCODING=utf-8 is the fix when a cron job's stdout mojibakes while the interactive shell looks fine.
Normalization: identical-looking is not equal
"café" can be one code point é (NFC) or e plus a combining acute (NFD) — identical glyphs, different strings, == fails. macOS stores filenames decomposed; a name written on Linux and compared on a MacBook mismatches. unicodedata.normalize("NFC", s) before comparing. NFKC additionally flattens compatibility characters — ② to 2, ligatures to letters — useful for matching, lossy for data. For caseless comparison use casefold(), not lower(): "Straße".casefold() produces "strasse"; lower() leaves ß untouched.
The security version is confusables. Cyrillic а is U+0430; Latin a is U+0061 — pixel-identical in most fonts. Xudong Zheng's 2017 аррӏе.com demo showed a browser rendering a Cyrillic lookalike domain as a trusted one; browsers now display punycode (xn--) for mixed-script IDNs, but your application's username checks do no such thing. Normalize plus a confusable check is the difference between a moderator's name and someone wearing it.
Binary boundaries
struct.pack("<I", n) and int.to_bytes(4, "little") make endianness explicit — wire formats demand it; memoryview gives zero-copy slices for parsing buffers without allocating. utf-8-sig is the codec nobody knows until it bites: writing adds a \ufeff BOM, and a BOM'd file parsed as plain UTF-8 leaves ufeff glued to the first character — json.loads fails on it with an error that blames the wrong thing.
The practice
Decode at the boundary and work in str. Explicit encoding="utf-8" on every open. normalize("NFC") plus casefold() before comparing names. surrogateescape when filesystem bytes must round-trip. -X utf8 on Windows until 3.15. Mojibake is never the file's fault — it is an implicit encoding you didn't write down.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.
What is Python? Enterprise, Data Science, and the Backend of the Web
Python runs Instagram, Dropbox, Netflix, Spotify, and Reddit. It trains the models that power modern AI. It processes petabytes of data in enterprise pipelines. And I ignored it for years because I thought it was just for academics. Here is what changed my mind.
What Python 3.13 Shipped
The first release of Python 3.13 is now here as a Beta Release. This article is a rundown of all of the important changes and features that are being released in Python 3.13, along with what they mean for Python Developers. Please remember that this can change between
What Python 3.11 Actually Changed
The Python Programming Language releases a new version every year, with a feature-locked beta release in the first half of the year and the final release toward the end of the year. The feature set for Python 3.11 has just been finalized, with a beta version available for testing.