Python结构模式匹配

我无法运行此代码:

match shape:
    case Point(x, y):
        ...
    case Rectangle(x, y, _, _):
        ...
print(x, y)

match在python中找不到关键字,

我在这里找到它:https : //www.python.org/dev/peps/pep-0622/#the-match-statement

...任何的想法??

更新:刚刚看到你的答案,像我这样的新 python 开发人员可能会犯同样的错误,所以我会把这个问题留给可能需要的每个人......谢谢你们,我真的很感谢你们的努力!

回答

2021 年 4 月 19 日更新:Python 3.10 将引入结构模式匹配。有关更多详细信息,请参阅其他优秀答案。

您所指的来源是 PEP(Python 增强提案),它尚未在稳定版本中实现。此外,PEP 已被PEP634取代。

截至 2021 年初,已match发布的 Python 版本 <= 3.9 中不存在该关键字。

由于 Python 没有任何类似于其他语言中的 switch/case 的功能,因此您通常会使用嵌套if/elif/else语句或字典。

这是一个基于您的问题的示例,尽管我并不能立即清楚您要实现的目标。


class Point:
   def __init__(self, x, y):
       pass

class Rectangle:
   def __init__(self, x1, y1, x2=0, y2=0):
       pass

shapes = dict(
    point=Point,
    rectangle=Rectangle,
)

my_obj = shapes['point'](x, y)

  • I lost 20 minutes searching python.org site this famous match-case, [announced as implemented](https://www.infoworld.com/article/3609208/how-to-use-structural-pattern-matching-in-python.html), and got [a lot of long philosophical views](https://www.python.org/search/?q=match+case&submit=) and [even tutorials](https://www.python.org/dev/peps/pep-0636/) on it, until I finally reached your answer and discovered it was never implemented. Thanks a lot.

回答

截至 2021 年 3 月,结构模式匹配不仅被正式接受,而且在 Python 3.10 的最新 alpha 和开发版本中可用。我写了一篇文章“从今天开始使用 Python 中的模式匹配!” 上周详细介绍了如何实现这一点,但我会在这里做一个简短的回顾。

通过 pyenv 安装 3.10-dev/a6

首先确保你已经安装并设置了pyenv。在这一点上简单地做

pyenv install 3.10-dev

您现在可以在本地激活测试版并运行解释器。

pyenv local 3.10-dev
python
Python 3.10.0a6+ (heads/master:87f649a409, Mar 11 2021, 16:29:20) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

通过 docker 容器运行

如果您不关心在本地系统中直接运行 3.10,您也可以使用 docker。新的 alpha 6 已经启动,3.10.0a6 解释器可以很容易地在这样的容器中启动。

docker run -it python:3.10.0a6-buster

你有它,两种不同的方法来使用/测试 python 中的新结构模式匹配。

注意:这仍然是一个早期版本,完整的版本将在 10 月推出,所以暂时不要在此功能上构建您的生产堆栈。但是,如果您想尝试未来的概念,现在就可以这样做。


以上是Python结构模式匹配的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>