Skip to content

Positional sub-pattern matching for custom classes.

License

Notifications You must be signed in to change notification settings

mportesdev/posmatch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

release pypi

posmatch

Positional sub-pattern matching for custom classes.

Requirements

Python 3.10 or higher.

Installation

pip install posmatch

Usage

The pos_match decorator

from posmatch import pos_match


@pos_match
class Color:
    def __init__(self, red, green, blue):
        self.red = red
        self.green = green
        self.blue = blue


color = Color(0, 0, 128)

match color:
    case Color(r, g, b) if r == g == b:
        print('Shade of grey')
    case Color(0, 0):
        print('Shade of blue')

Output:

Shade of blue

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

About

Positional sub-pattern matching for custom classes.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages