模式匹配是Python 3.10的新特性,EuroPython请来了这个功能的贡献者之一,Daniel Moisset,为我们介绍模式匹配。
简介
When Python 3.10 comes out in October 2021, it will include a new feature called “Structural Pattern Matching”. Structural Pattern Matching has been a staple of functional programming languages, but it has recently appeared or been proposed as future additions to imperative and OOP programming languages (like JavaScript, C++, and Rust). It provides an elegant way of processing and deconstructing heterogeneous data structures, and it enables an alternative paradigm to method dispatch.
As one of this feature’s contributors, my goals in this presentation are to describe the motivation for this new functionality, present some of the problems that its use will effectively solve, and give a brief introduction of how to use it.
This talk is aimed at intermediate Python developers (although a beginner will be able to understand it). After attending you should be able to understand not just how to use pattern matching, but also when it’s a good idea to use it and what are the possible pitfalls to avoid.
There will be a Q&A session which could be a good chance to discuss your questions about why certain design decisions were made when introducing pattern matching into Python
Type: Talk (30 mins);
Python level: Intermediate;
Domain level: Beginner
翻译
当Python 3.10发布的时候(实际上,2021年10月4日已经发布了),它将会包含一个新的特性,叫Structural Pattern Matching(结构模式匹配)。Structural Pattern Matching 是函数编程语言的主要部分,但是最近它出现在了Javascript, C++, Rust等命令式或面向对象的语言中。它提供了一种优美地处理和解构各种各样地数据结构地方法。也为我们解决问题提供了另一种思路。
作为这个特性地贡献者,我这次演讲的目标是介绍开发这个新特性的动机,呈现一些这个新功能可以高效解决的问题,并简短介绍如何使用。
这次的介绍目标听众是中级Python程序员,初级程序员也应该能听懂。听完讲座以后,你应该能懂得如何使用模式匹配,已经什么时候应该使用它,并避免一些可能的陷阱。
之后会有提问环节,我们可以讨论如果用模式匹配设计Python代码。
类型:演讲(30分钟)
Python 水平:中级
领域水平:初级
作者简介
I’m a Latin American expat in London. After 20ys of background as an entrepreneur, software engineer and project leader, I’m currently training engineers. Most of my professional career has been marked by a love for Python and good engineering. I’m deeply interested in compiler and language design, and places were CS theory and engineering practice touch each other closely.
Non professionally, I’m a bad piano player, a husband a Dungeon Master, and a cat herder.
Preferred pronouns are he/him.
翻译
我是在伦敦的拉丁美洲人。有20年的从业经验,办过企业,写过代码,带领过团队。我现在培训工程师。我的职业生涯的主要部分都伴随着我对Python的热爱。我深深的热爱编译器,语言设计,计算机理论与工程实践的结合。
业余爱好有弹钢琴,玩龙与地下城,撸猫。
请称呼我he/him。
动机
(Daniel说了十分钟的动机,我总结如下。)
各种各样的数据结构,就像是一个有各种各样的小物件迷宫。他们可以是方形的,圆形的,十字形的,甜甜圈形的。他们可是白的,黑的,红的,蓝的。他们可以在迷宫的东边,西边,南边,北边。他们或大如泰山,或小如芝麻。我们要找出我们想要的形状,就要用模式匹配。
而我们做模式匹配的时候,往往在匹配的同时,也要提取出各种信息。比如,我们要提取长方形的长和宽,我们要提取原型的半径,我们要提取甜甜圈的内半径和外半径等。我们需要把这些信息,提取到新的变量中。
这样,我们就有了模式匹配。
语法
模式匹配,Python里面用match/case语句实现。其语法如下:
match <subject>:
case <pattern 1>:
<code block 1>
case <pattern 2> if <guard>:
<code block