Giter Club home page Giter Club logo

python-pattern-matching's Introduction

Python Pattern Matching

Python, I love you. But I'd like you to change. It's not you, it's me. Really. See, you don't have pattern matching. But, that's not the root of it. Macros are the root of it. You don't have macros but that's OK. Right now, I want pattern matching. I know you offer me if/elif/else statements but I need more. I'm going to abuse your functions. Guido, et al, I hope you can forgive me. This will only hurt a little.

Python Pattern Matching is an Apache2 licensed Python module for pattern matching like that found in functional programming languages. Most projects that address Python pattern matching focus on syntax and simple cases. Operator overloading is often used to change the semantics of operators to support pattern matching. In other cases, function decorators are used to implement multiple dispatch, sometimes known as function overloading. Each of these syntaxes, operators, and decorators, is really more of a detail in the application of pattern matching.

A lot of people have tried to make this work before. Somehow it didn't take. I should probably call this yet-another-python-pattern-matching-module but "yappmm" doesn't roll off the tongue. Other people have tried overloading operators and changing codecs. This module started as a codec hack but those are hard because they need an ecosystem of emacs-modes, vim-modes and the like to really be convenient.

Python Pattern Matching focuses instead on the semantics of pattern matching in Python. The dynamic duck-typing behavior in Python is distinct from the tagged unions found in functional programming languages. Rather than trying to emulate the behavior of functional pattern matching, this project attempts to implement pattern matching that looks and feels native to Python. In doing so the traditional function call is used as syntax. There are no import hooks, no codecs, no AST transforms.

Python match function example.

Finally, pythonic pattern matching! If you've experienced the feature before in "functional" languages like Erlang, Haskell, Clojure, F#, OCaml, etc. then you can guess at the semantics.

Show the same code without patternmatching.

Features

  • Pure-Python
  • Developed on Python 3.9
  • Tested on CPython 3.6, 3.7, 3.8, and 3.9
  • Fully Documented
  • 100% test coverage
  • Hours of stress testing

Quickstart

Installing Python Pattern Matching is simple with pip:

$ pip install patternmatching

You can access documentation in the interpreter with Python's built-in help function. The help works on modules, classes, and functions in pattern matching.

>>> from patternmatching import match, bind, bound, like
>>> help(match)                     # doctest: +SKIP

Alternative Packages

Other Languages

Developer Guide

Python Pattern Matching License

Copyright 2015-2021, Grant Jenks

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

python-pattern-matching's People

Contributors

grantjenks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-pattern-matching's Issues

Add Case Study: Satisfiability

"""Satisfiability and Propositional Logic

Consider the following constraints:

– Alice can only meet either on Monday, Wednesday or Thursday
– Bob cannot meet on Wednesday
– Carol cannot meet on Friday
– Dave cannot meet neither on Tuesday nor on Thursday
– Question: When can the meeting take place?

- Encode then into the following Boolean formula:

    (Mon ∨ Wed ∨ Thu) ∧ (¬Wed) ∧ (¬Fri) ∧ (¬Tue ∧ ¬Thu)

The meeting must take place on Monday

"""

import logging
from patternmatching import *

logging.basicConfig(format='%(message)s', level=logging.DEBUG)

options = [
    'monday', 'wednesday', 'thursday', 'X',
    'monday', 'tuesday', 'thursday', 'friday', 'X',
    'monday', 'tuesday', 'wednesday', 'thursday', 'X',
    'monday', 'wednesday', 'friday', 'X',
    True,
]

constraints = (
    padding + anyone * group('alice') + padding + 'X'
    + padding + anyone * group('bob') + padding + 'X'
    + padding + anyone * group('carol') + padding + 'X'
    + padding + anyone * group('dave') + padding + 'X'
    + like(lambda _: bound.alice == bound.bob == bound.carol == bound.dave)
)

assert match(options, constraints)  # <-- FAILS! and I don't know why :(

Add Case Study: Symbolic Expression Optimization

Create Symbol Expressions using namedtuples and write optimizer rules using patternmatching.

Might be a good demo for the landing page -- I recall lots of complex clauses with patternmatching.

Add z3 integration

An integration with Z3 seems possible and useful. Z3 knows nothing about Python so I think the trick is to encode Python’s object model in Z3 code.

For example, when matching sequences, Z3 would be told that each matching element must be equal. This might also apply to NamedTuples and data classes pretty easily.

The general class of equality would be difficult to capture without translating Python byte code to Z3 statements but the common cases of built-in types (ints, strs, lists, etc) and class factories (data class, named tuple, etc) may be possible.

I know z3 supports integers but does it also handle strings and floats? Hi

Failed when using with _:

Hello, I am not sure if this project is still actively maintained. If so, I would really appreciate if someone can help me on the following issue.

I got an error for the following sample code:

import pypatt

@pypatt.transform
def factorial(num):
    with match(num):
        with 1:
            return 1
        with _:
            return num * factorial(num - 1)

print factorial(3)

Error:

Traceback (most recent call last):
  File "tt.py", line 29, in <module>
    print factorial(3)
  File "tt.py", line 769, in factorial

  File "/usr/lib/python2.7/site-packages/pypatt/macro.py", line 174, in trybind
    result = visitor(expr, value)
  File "/usr/lib/python2.7/site-packages/pypatt/macro.py", line 158, in visitor
    raise RuntimeError('unknown ast.Name')
RuntimeError: unknown ast.Name

Can anyone help me on this? Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.