Python struct — ELI5
Imagine you’re packing a suitcase for a trip, but the airline has super strict rules: shoes go in a bag exactly this size, shirts must be folded to exactly that width, and everything has to fit in a precise order.
That’s what Python’s struct module does — but with data instead of clothes.
Computers store everything as raw bytes (just 1s and 0s). When Python wants to talk to hardware, read a file created by another language, or send data over a network, it can’t just send a nice Python dictionary. It has to pack the data into an exact byte layout the other side expects.
How it works
You give struct a recipe (called a format string) that says: “first put an integer here, then a float here, then two characters here.” The module packs your Python values into a tight blob of bytes — and can unpack bytes back into Python values.
Think of the format string as the packing checklist your airline gives you. Follow it exactly, and your stuff arrives intact on the other end.
When would you use this?
- Reading image files (like BMP headers)
- Talking to hardware sensors
- Sending data to programs written in C
- Working with network protocols
One thing to remember
struct is the translator between Python’s comfortable world of named variables and the computer’s real world of raw bytes — a strict packing checklist that both sides agree on.
See Also
- Python Atexit How Python's atexit module lets your program clean up after itself right before it shuts down.
- Python Bisect Sorted Lists How Python's bisect module finds things in sorted lists the way you'd find a word in a dictionary — by jumping to the middle.
- Python Contextlib How Python's contextlib module makes the 'with' statement work for anything, not just files.
- Python Copy Module Why copying data in Python isn't as simple as it sounds, and how the copy module prevents sneaky bugs.
- Python Dataclass Field Metadata How Python dataclass fields can carry hidden notes — like sticky notes on a filing cabinet that tools read automatically.