{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `match` 语句\n",
    "\n",
    "```{hint}\n",
    "Python 3.10 及其以上版本的特性。\n",
    "```\n",
    "\n",
    "`match` 语句接受一个表达式并将它的值与以一个或多个 `case` 语句块形式给出的一系列模式进行比较。这在表面上很类似 C, Java 或 JavaScript（以及许多其他语言）中的 `switch` 语句，但它还能够从值中提取子部分（序列元素或对象属性）并赋值给变量。\n",
    "\n",
    "最简单的形式是将一个目标值与一个或多个字面值进行比较："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def http_error(status):\n",
    "    match status:\n",
    "        case 400:\n",
    "            return \"Bad request\"\n",
    "        case 404:\n",
    "            return \"Not found\"\n",
    "        case 418:\n",
    "            return \"I'm a teapot\"\n",
    "        case _:\n",
    "            return \"Something's wrong with the internet\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{hint}\n",
    "最后一个代码块中的变量名 `_` 被作为 **通配符** 并必定会匹配成功。如果没有任何 `case` 语句匹配成功，则任何分支都不会被执行。\n",
    "```\n",
    "\n",
    "你可以使用 ``|`` （“或”）在一个模式中组合几个字面值：\n",
    "\n",
    "```python\n",
    "case 401 | 403 | 404:\n",
    "    return \"Not allowed\"\n",
    "```\n",
    "\n",
    "模式的形式可以类似于解包赋值，并可被用于绑定变量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test_point(point):\n",
    "    match point:\n",
    "        case (0, 0):\n",
    "            print(\"原点\")\n",
    "        case (0, y):\n",
    "            print(f\"Y={y}\")\n",
    "        case (x, 0):\n",
    "            print(f\"X={x}\")\n",
    "        case (x, y):\n",
    "            print(f\"X={x}, Y={y}\")\n",
    "        case _:\n",
    "            raise ValueError(\"不是一个点\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X=2, Y=3\n",
      "原点\n",
      "Y=5\n",
      "X=7\n"
     ]
    }
   ],
   "source": [
    "test_point((2, 3)), test_point((0, 0)), test_point((0, 5)), test_point((7, 0));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "不是一个点",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_3716/1044635205.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mtest_point\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_3716/853505448.py\u001b[0m in \u001b[0;36mtest_point\u001b[1;34m(point)\u001b[0m\n\u001b[0;32m     10\u001b[0m             \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"X={x}, Y={y}\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     11\u001b[0m         \u001b[0mcase\u001b[0m \u001b[0m_\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 12\u001b[1;33m             \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"不是一个点\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: 不是一个点"
     ]
    }
   ],
   "source": [
    "test_point(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{important}\n",
    "- 第一个模式有两个字面值，可以看作是上面所示字面值模式的扩展。\n",
    "- 但接下来的两个模式结合了一个字面值和一个变量，而变量 **绑定** 了一个来自目标的值（`point`）。\n",
    "- 第四个模式捕获了两个值，这使得它在概念上类似于解包赋值 `(x, y) = point`。\n",
    "```\n",
    "\n",
    "如果你使用类来结构化你的数据，你可以使用类名之后跟一个类似于构造器的参数列表，这样能够捕获属性放入到变量中："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Point:\n",
    "    x: int\n",
    "    y: int\n",
    "\n",
    "def where_is(point):\n",
    "    match point:\n",
    "        case Point(x=0, y=0):\n",
    "            print(\"原点\")\n",
    "        case Point(x=0, y=y):\n",
    "            print(f\"Y={y}\")\n",
    "        case Point(x=x, y=0):\n",
    "            print(f\"X={x}\")\n",
    "        case Point():\n",
    "            print(\"在其他地方\")\n",
    "        case _:\n",
    "            print(\"不是一个点\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以在某些为其属性提供了排序的内置类（例如 `dataclass`）中使用位置参数。你也可以通过在你的类中设置 `__match_args__` 特殊属性来为模式中的属性定义一个专门的位置。如果它被设为 `(\"x\", \"y\")`，则以下模式均为等价的（并且都是将 `y` 属性绑定到 `var` 变量）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Point(x=1, y=7)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Point:\n",
    "    x: int\n",
    "    y: int\n",
    "\n",
    "var = 7\n",
    "Point(1, var)\n",
    "Point(1, y=var)\n",
    "Point(x=1, y=var)\n",
    "Point(y=var, x=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取模式的推荐方式是将它们看做是你会在赋值操作左侧放置的内容的扩展形式，以便理解各个变量将会被设置的值。只有单独的名称（例如上面的 `var`）会被 `match` 语句所赋值。带点号的名称（例如 `foo.bar`）、属性名称（例如上面的 `x=` 和 `y=`） 或类名称（通过其后的 \"`(...)`\" 来识别，例如上面的 `Point`）都绝不会被赋值。\n",
    "\n",
    "模式可以任意地嵌套。例如，如果我们有一个由点组成的短列表，则可以这样匹配它："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def where_is(points):\n",
    "    match points:\n",
    "        case []:\n",
    "            print(\"没有点\")\n",
    "        case [Point(0, 0)]:\n",
    "            print(\"原点\")\n",
    "        case [Point(x, y)]:\n",
    "            print(f\"单点 {x}, {y}\")\n",
    "        case [Point(0, y1), Point(0, y2)]:\n",
    "            print(f\"在 Y 轴上的两个点 {y1}, {y2}\")\n",
    "        case _:\n",
    "            print(\"其他点\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以向一个模式添加 `if` 子句，称为“守护项”。 如果守护项为假值，则 `match` 将继续尝试下一个 `case` 语句块。请注意值的捕获发生在守护项被求值之前：\n",
    "\n",
    "我们可以向一个模式添加 ``if`` 子句，称为“守护项”（guard）。如果守护项为假值，则 ``match`` 将继续尝试下一个 `case` 语句块。 请注意值的捕获发生在守护项被求值之前：\n",
    "\n",
    "```python\n",
    "match point:\n",
    "    case Point(x, y) if x == y:\n",
    "        print(f\"Y=X at {x}\")\n",
    "    case Point(x, y):\n",
    "        print(f\"Not on the diagonal\")\n",
    "```\n",
    "\n",
    "此语句的一些其他关键特性：\n",
    "\n",
    "- 类似于解包赋值，元组和列表模式具有完全相同的含义并且实际上能匹配任意序列。一个重要的例外是它们不能匹配迭代器或字符串。\n",
    "- 序列模式支持扩展解包操作: `[x, y, *rest]` 和 `(x, y, *rest)` 的作用类似于解包赋值。在 `*` 之后的名称也可以为 `_`，因此 `(x, y, *_)` 可以匹配包含至少两个条目的序列而不必绑定其余的条目。\n",
    "- 映射模式：`{\"bandwidth\": b, \"latency\": l}` 从字典中获取 `\"bandwidth\"` and `\"latency\"` 的值。与序列模式不同，额外的键会被忽略。也支持像 `**rest` 这样的解包方式。（但是 `**_` 是多余的，所以不允许。）\n",
    "- 子模式可使用 `as` 关键字来捕获：\n",
    "\n",
    "    ```python\n",
    "    case (Point(x1, y1), Point(x2, y2) as p2): ...\n",
    "    ```\n",
    "\n",
    "    将把输入的第二个元素捕获为 `p2` （只要输入是包含两个点的序列）\n",
    "\n",
    "- 大多数字面值是按相等性比较的，但是单例对象 `True`, `False` 和 `None` 则是按标识号比较的。\n",
    "- 模式可以使用命名常量。这些命名常量必须为带点号的名称以防止它们被解读为捕获变量：\n",
    "\n",
    "    ```python\n",
    "    from enum import Enum\n",
    "    class Color(Enum):\n",
    "        RED = 'red'\n",
    "        GREEN = 'green'\n",
    "        BLUE = 'blue'\n",
    "\n",
    "    color = Color(input(\"Enter your choice of 'red', 'blue' or 'green': \"))\n",
    "\n",
    "    match color:\n",
    "        case Color.RED:\n",
    "            print(\"I see red!\")\n",
    "        case Color.GREEN:\n",
    "            print(\"Grass is green\")\n",
    "        case Color.BLUE:\n",
    "            print(\"I'm feeling the blues :(\")\n",
    "    ```\n",
    "\n",
    "要获取更详细的说明和额外的示例，你可以参阅以教程格式撰写的 {pep}`636`。\n",
    "\n",
    "循环 `else` 子句提供了常见的编写代码的明确语法：这是编写代码的结构，让你捕捉循环的“另一条”出路，而不通过设定和检查标志位或条件。\n",
    "\n",
    "例如，假设你要写一个循环搜索列表的值，而且需要知道在离开循环后该值是否已经找到，可能会用下面的方式编写该任务：\n",
    "\n",
    "```python\n",
    "found = False\n",
    "while x and not found:\n",
    "    if match(x[0]):\n",
    "        print('Ni')\n",
    "        found = True\n",
    "    else:\n",
    "        x = x[1:]\n",
    "if not found:\n",
    "    print('not found')\n",
    "```\n",
    "\n",
    "我们亦可使用循环 `else` 分句来简化上述代码：\n",
    "\n",
    "```python\n",
    "while x:\n",
    "    if match(x[0]):\n",
    "        print('Ni')\n",
    "        break\n",
    "    x = x[1:]\n",
    "else:\n",
    "    print('not found')\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "8231c362f1335a08c500d79bd4002cbcf7e316a37464a7a395ec9af0792b6831"
  },
  "kernelspec": {
   "display_name": "Python 3.9.7 64-bit (conda)",
   "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.0"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
