I stayed up past my bedtime recently and made a script and later a web app to convert a dataclass to a non-dataclass. The web app is powered by a WebA

Appreciating Python's match-case by parsing Python code

submited by
Style Pass
2022-06-23 23:00:06

I stayed up past my bedtime recently and made a script and later a web app to convert a dataclass to a non-dataclass. The web app is powered by a WebAssembly build of Python (which also powers my Python pastebin tool).

While making this script I found excuses to use odd Python features, the most interesting being Python's match-case statement.

Python 3.10 added a match-case block that folks often assume to be equivalent to the switch-case blocks from other programming languages. While you can use match-case like switch-case, you usually wouldn't: match-case is both more powerful and more complex than switch-case. Python's match-case blocks are for structural pattern matching -- that phrase sounds complex because it is!

I'll write a follow-up post soon on how this script works at a high level, but right now I'd like to talk about my adventures using structural pattern matching to writing this code.

There are trade offs with using dataclasses: performance concerns (which don't usually matter) and edge cases where things get weird (__slots__ and slots=True are both finicky). But my reason for creating this dataclass to regular class converter was to help me better teach dataclasses. Seeing the equivalent code for a dataclass helps us appreciate what dataclasses do for us.

Leave a Comment