santinic / pampy

Pampy: The Pattern Matching for Python you always dreamed of.
MIT License
3.51k stars 125 forks source link

Add support for Python 3.7 dataclasses #13

Closed stevenheidel closed 5 years ago

stevenheidel commented 5 years ago

I added support for Python 3.7 dataclasses. We're prolific users of dataclasses where I work, and this would greatly help with simplifying the code base. Plus since dataclasses are straightforward in most cases (basically named dictionaries) then it's only an effectively 2 line change given the utilities Pampy already provides.

Before/after example with Pampy for implementing a simple AST transform:

# Without pampy, recursively simplifying a + 0 = 0 + a = a
def simplify(expr):
    if isinstance(expr, BinaryExpression) and expr.operator = '+':
        if expr.a == 0:
            return simplify(expr.b)
        elif expr.b == 0:
            return simplify(expr.a)
    return expr
# With pampy, recursively simplifying a + 0 = 0 + a = a
def simplify(expr):
    return match(expr,
        BinaryExpression('+', 0, _), simplify,
        BinaryExpression('+', _, 0), simplify,
        _,                           expr)
santinic commented 5 years ago

This is such a nice thing, thank you @stevenheidel . Feel free to keep suggesting improvements like this :)