Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.9 — Writing Modern Python: An Idiom Upgrade
Python · Example 1 of 3 Python 3.11+

Modern idioms in one program

Several upgrades in one run: f-string =, dict |, removeprefix, walrus, zip(strict=True), StrEnum, tomllib, pathlib, slots dataclass, except*. It writes a small folder to the run's scratch directory.

Python has changed a lot since the code in old tutorials was written. This topic puts the old way and the modern way side by side, so you can read old code, write current code, and know what each recent version added.

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 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite "Total: %d items" % count with an f-string, for count = 7, and print it.

02

Merge {"a": 1} and {"a": 2, "b": 3} with the dictionary union operator and print the result. Which value of a wins?

03

Use zip(strict=True) on [1, 2] and ["a"] inside a try and print the error message.

04

Rewrite from typing import Optional, List hints Optional[List[str]] in the modern style and print it with typing.get_type_hints for a function using it.

Explain it without notes

01

Give five modern replacements for old Python idioms.

02

What does zip(a, b, strict=True) protect you from?

03

How would you modernise a large codebase safely?

04

What are template strings and what problem do they address?

05

Is a | b for dicts a deep merge? How does it differ from a |= b and {**a, **b}?

Modern idioms in one program Python 3.11+
Sign in to run this example in your browser.

Expected output

hectal v3 | hectal v3 | hectal v3 | version=3
merged: {'theme': 'dark', 'size': 14}
trimmed: 1.2.3 file
walrus: long list of 3
zip strict: zip() argument 2 is shorter than argument 1
StrEnum: red True blue
toml: {'server': {'port': 8080, 'hosts': ['a', 'b']}}
pathlib: ['a.txt'] hello
User(name='Asha', age=0)
except*: (ValueError('bad value'),)
except* key: (KeyError('k'),)