Skip to content

Instantly share code, notes, and snippets.

@fredrikaverpil
Created November 4, 2022 18:13
Show Gist options
  • Save fredrikaverpil/f225cdd92c9c253c8851316e4ef99a9a to your computer and use it in GitHub Desktop.
Save fredrikaverpil/f225cdd92c9c253c8851316e4ef99a9a to your computer and use it in GitHub Desktop.
Pattern matching gotchas
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Caught [{'foo': 'bar'}, {'bar': 'baz'}]\n",
"Did not catch [{'bar': 'baz'}, {'foo': 'bar'}]\n"
]
}
],
"source": [
"x = [\n",
" {\"foo\": \"bar\"},\n",
" {\"bar\": \"baz\"},\n",
"]\n",
"y = [\n",
" {\"bar\": \"baz\"},\n",
" {\"foo\": \"bar\"},\n",
"]\n",
"\n",
"for item in (x, y):\n",
" match item:\n",
" case [{\"foo\": \"bar\"}, *other_items]:\n",
" print(f\"Caught {item}\")\n",
" case _:\n",
" print(f\"Did not catch {item}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Caught {'foo': 'bar', 'bar': 'baz'}\n",
"Caught {'bar': 'baz', 'foo': 'bar'}\n"
]
}
],
"source": [
"x = {\"foo\": \"bar\", \"bar\": \"baz\"}\n",
"y = {\"bar\": \"baz\", \"foo\": \"bar\"}\n",
"\n",
"for item in (x, y):\n",
" match item:\n",
" case {\"foo\": \"bar\", **kwargs}:\n",
" print(f\"Caught {item}\")\n",
" case _:\n",
" print(f\"Did not catch {item}\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.10.8 ('.venv': poetry)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "cd44e36c613be01649759f409b60d8bc3a6d73161928441df7ba39adc0804353"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment