[Python-ideas] Pattern Matching Syntax
steven at rigetti.com
steven at rigetti.com
Fri May 11 12:36:31 EDT 2018
Hi everyone, I’m also a first time poster to python-ideas so I apologize if
reviving a week old thread is bad form. I emailed Guido out of the blue to
share some thoughts on the JavaScript pattern matching proposal’s
applicability to Python and he encouraged me to post those thoughts here.
The best argument for pattern matching is to support what Daniel F Mossat
above calls “structural patterns”. These go beyond simple value matching or
boolean conditions that are better served with other constructs like if
statements. Structural pattern matching allows for reasoning about the
shape of data.
As a practical example, in my day job I work as a software engineer at a
startup that builds quantum computers. Python has been a great language for
writing physics experiments and doing numerical simulations. However, our
codebase contains a lot of `isinstance` calls due to the need to write
converters from the physics experiment definition language to quantum
assembly instructions. There’s some examples in our open source code as
well, for instance here:
https://github.com/rigetticomputing/pyquil/blob/master/pyquil/quil.py#L641
. This could be written more succinctly as:
match instr:
case Gate(name, params, qubits): result.append(Gate(name, params, [
qubit_mapping[q] for q in qubits])
case Measurement(qubit, classical_reg): result.append(Measurement(
qubit_mapping[qubit], classical_reg)
else: result.append(instr)
Something that I also haven’t seen discussed yet is how well this would
work with the new Python 3.7 dataclasses. Dataclasses allow us to create
more structured data than using dicts alone. For instance, each instruction
in our internal assembly language has its own dataclass. Pattern matching
would make it easy to create readable code which loops over a list of these
instructions and performs some sort of optimizations/transformations.
Finally I want to talk about matching on the structure of built-in data
structures like lists and dicts. The javascript proposal does a great job
of supporting these data types and I think this would also be natural for
Python which also has some destructuring bind support for these types on
assignment.
Consider the example of accessing nested dictionaries. This comes up a lot
when working with JSON. If you had a dictionary like this:
target = {'galaxy': {'system': {'planet': 'jupiter'}}}
Then trying to access the value ‘jupiter’ would mean one of these
alternatives:
# Risks getting a ValueError
my_planet = target[‘galaxy’][‘system’][‘planet’]
print(my_planet)
# Awkward to read
my_planet = target.get(‘galaxy’, {}).get(‘system’, {}).get(‘planet’)
if my_planet:
print(my_planet)
With pattern matching this could become more simply:
match target:
case {‘galaxy’: {‘system’: {‘planet’: my_planet}}}: print(my_planet)
This example was stolen from the tutorial for the glom library
https://sedimental.org/glom_restructured_data.html which works on nested
data. Structural pattern matching is a more universal concept and could
eliminate the need for these kinds of helper functions.
>From reading through this thread (as well as other background reading like
https://groups.google.com/forum/#!msg/python-ideas/aninkpPpEAw/wCQ1IH5mAQAJ
and the Javascript proposal) a couple things seem clear to me for pattern
matching in the case of Python:
- it should be statement based
- it should have great support for built-in data types like lists, dicts,
namedtuples, and dataclasses
- it should form a coherent story with other similar Python concepts like
unpacking on assignment
There are a ton of details to be worked out obviously and we should go slow
as Guido suggested. However, I believe that it would be worth doing the
work. To that end: if there’s anyone else who’d like to collaborate and
come up with a first draft of a more well-defined proposal I would love to
commit my time to this, my email is below.
Also, I sent this email from PyCon in Cleveland if anyone would like to
brainstorm in person :).
Steven Heidel
Rigetti Quantum Computing
steven at rigetti.com
On Friday, May 4, 2018 at 4:37:43 PM UTC, Guido van Rossum wrote:
>
> Can I recommend going slow here? This is a very interesting topic where
> many languages have gone before. I liked Daniel F Moisset's analysis about
> the choices of a language designer and his conclusion that match should be
> a statement.
>
> I just noticed the very similar proposal for JavaScript linked to by the
> OP: https://github.com/tc39/proposal-pattern-matching -- this is more
> relevant than what's done in e.g. F# or Swift because Python and JS are
> much closer. (Possibly Elixir is also relevant, it seems the JS proposal
> borrows from that.)
>
> A larger topic may be how to reach decisions. If I've learned one thing
> from PEP 572 it's that we need to adjust how we discuss and evaluate
> proposals. I'll think about this and start a discussion at the Language
> Summit about this.
>
> --
> --Guido van Rossum (python.org/~guido)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180511/a8b6f3a9/attachment.html>
More information about the Python-ideas
mailing list