Skip to main content

Positional sub-pattern matching for custom classes.

Project description

release pypi

posmatch

Positional sub-pattern matching for custom classes.

Requirements

Python 3.9 or higher.

Note: Although this package can be installed and used in Python 3.9+, its usage only makes sense with the pattern matching feature introduced in Python 3.10. All code snippets below require Python 3.10+.

Installation

pip install posmatch

Usage

The pos_match decorator

from posmatch import pos_match

@pos_match
class Color:

    def __init__(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

color = Color(64, 64, 64)

match color:
    case Color(0, 0, _):
        print('Shade of blue')
    case Color(red, green, blue) if red == green == blue:
        print('Shade of grey')

Output:

Shade of grey

The PosMatchMeta metaclass

from posmatch import PosMatchMeta

class Date(metaclass=PosMatchMeta):

    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

date = Date(2121, 1, 1)

match date:
    case Date(_, m, d) if m == 5 and d == 1:
        print('May Day')
    case Date(y) if y > 2100:
        print('Distant future')

Output:

Distant future

The PosMatchMixin mix-in class

from posmatch import PosMatchMixin

class Rectangle(PosMatchMixin):

    def __init__(self, width, height):
        self.width = width
        self.height = height

shape = Rectangle(16, 16)

match shape:
    case Rectangle(w, h) if w == h:
        print('Square')
    case Rectangle(x, y) if x > y:
        print('Landscape')

Output:

Square

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

posmatch-0.5.0-py3-none-any.whl (4.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page