Parse a binary file header with struct
Real binary formats (images, audio, network packets) start with a fixed header: a magic number that says what the file is, a version, then sizes. Struct describes the layout once, unpack_from reads at an offset, and the checks reject files that are too short or of the wrong kind. Money is stored in paise as whole numbers, never as floats.
TOML and YAML are friendly formats for configuration files, pickle saves Python objects but must never be opened from an untrusted source, and struct and bytes let you read and write raw binary data.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 7 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Parse the TOML text [app]\nname = "demo"\nretries = 3 with tomllib.loads. Print the value of retries plus 1 (it should print 4). Hint: the value sits inside the app table.
Use yaml.safe_load on a YAML list of three numbers written one per line, each starting with - (for example - 10). Print their sum. Hint: the result is a normal Python list.
Pack the numbers 1, 2, 3 as three little-endian 2-byte unsigned integers with struct.pack("<HHH", ...). Print the .hex() of the result, then unpack it back and print the tuple.
Explain it without notes
Why is it dangerous to unpickle data from an untrusted source? What should you use instead?
What is the difference between yaml.load and yaml.safe_load, and what typing surprises can YAML give?
When would you choose TOML over YAML or JSON for configuration?
What is endianness, and where does it matter?
Expected output
header size: 12
30 4843544c0101000300000012
(1, 1, [(1, 2000), (2, 3500), (3, 1250)])
rejected: file too short for a header
rejected: not a Hectal file: b'XXXX'
struct.error: unpack requires a buffer of 6 bytes
8 5