[Python-ideas] Pattern matching
Szymon Pyżalski
szymon at pythonista.net
Tue Apr 7 21:25:21 CEST 2015
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 07.04.2015 17:52, Guido van Rossum wrote:
>
> On Apr 7, 2015 8:46 AM, "Paul Moore" <p.f.moore at gmail.com
> <mailto:p.f.moore at gmail.com>> wrote:
>
> On 7 April 2015 at 15:54, Szymon Pyżalski <szymon at pythonista.net
> <mailto:szymon at pythonista.net>> wrote:
>> I was trying to google if there were some attempts to add
>> pattern matching feature (as seen in e.g. haskell) to Python. I
>> couldn't
> however
>> find anything. Were there any proposals for a feature like this?
>
> From a quick look:
>
> https://pypi.python.org/pypi/patterns
> https://pypi.python.org/pypi/py-pattern-matching
>
Thanks these are nice but I think they try to mimic languages based on
algebraic data types too much. I was thinking about something like this:
Magic method for patterns
- -----------------------------
Any object can be a pattern. If an object has a special method (called
``__pattern__`` or ``__match__``) defined then this method will govern
how this object behaves as pattern. If not - pattern matching works
the same as ``__eq__``
The ``__pattern__`` method can return ``False`` for no match. For a
match it can return ``True`` (simplest patterns) a sequence or a mapping
.
Syntax for pattern matching
- -------------------------------
The syntax could look something like this::
for object:
pattern1: statement1
pattern2:
statement2
statement3
pattern3 as var1, var2:
statement4
statement5
For the simplest cases this works simply by calling appropriate
statement block. If the ``__pattern__`` method returns a mapping, then
the values from it will be merged into the local namespace. If it
returns a sequence and there is the ``as`` clause, the values will be
assigned to variables specified.
> Quick idea: this might integrate well with PEP 484, or with the
> (still speculative) multiple dispatch that Lukas Lang wants to
> write.
Function dispatch
- -----------------------[
Besides the above syntax the patterns could be also used to register
functions for dispatching. I dont' know how precisely it would
integrate with PEP 484, but I agree that any valid type hint should
also be a valid pattern.
Existing objects as patterns
- ----------------------------------
* Types should match their instances
* Tuples should match sequences that have the same length and whose
elements match against the elements of a tuple (subpatterns)
* Dictionaries should match mappings that contain all the keys in the
pattern and the values match the subpatterns under these keys
* Regular expressions should match strings. For named groups they
should populate the local namespace.
* The ``Ellipsis`` object can be used as a match-all pattern.
Example
- -----------
The code below would work if the ``point`` variable is specified as:
* a tuple (x, y)
* a mapping {'x': x, 'y': y}
* a string "{x}-{y}".format(x, y)
::
def print_point(x, y):
print('x = {}'.format(x))
print('y = {}'.format(y))
for point:
(Number, Number) as x, y:
print_point(x, y)
{'x': Number, 'y': Number}:
print_point(x, y)
re.compile('(?P<x>[0-9]+)-(?P<y>[0-9])+'):
# Or re.compile('([0-9]+)-([0-9])+') as x, y:
print_point(int(x), int(y))
...:
raise TypeError('Expected something else')
Greetings
zefciu
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1
iQEcBAEBAgAGBQJVJC8YAAoJEBoIz6vZoBBhm04H/i5dJAMTloRxqSXXyY7QU8kx
0gBPjCoCsw6XZSu1nlKP0/yY+tO5uXjQEK5s1vid8gjuEBnrZCtwjfCYiiqSs96P
7iT9kSnyx/0jr5FvAC1ZItb3KN7G+MBxMfCHENM8yMz7Yxdw2F5ziT7zFE5aOELW
y3Mz37+GytmMUT/DXA4wIHBFJgALspWgoU2P/ilzg4oCtbQREmX5pcMnFIsMavPI
oIu7KJ0ZW2hJ4K2a0h8HWCpZ9aYwcCTF51HMkTAXo6leLSm3XG36jKiCEFJiZpxe
sLH8e/2rF93tBUVunJfyEQG/bOnlkoTX2rONavDZCqSqt8t3ehT170TtHJL10Os=
=iO75
-----END PGP SIGNATURE-----
More information about the Python-ideas
mailing list