Positional subpattern matching for custom classes.
Project description
Positional subpattern matching for custom classes.
Note: This is mostly a toy project. Using it will save you one line of boiler-plate code at the cost of an additional decorator or argument. In many cases, the same effect can be easily achieved by using a dataclass.
Requirements
Python 3.8 or higher.
Note: Although this package itself does not require Python 3.10, its usage only makes sense with the new pattern matching feature introduced in 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, b):
print('shade of blue')
case Color(r, g, b) if r == g == b:
print('shade of grey')
case _:
print('other color')
Output:
shade of grey
The PosMatchMeta metaclass
from posmatch import PosMatchMeta
class Color(metaclass=PosMatchMeta):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
color = Color(0, 0, 64)
match color:
case Color(0, 0, b):
print('shade of blue')
case Color(r, g, b) if r == g == b:
print('shade of grey')
case _:
print('other color')
Output:
shade of blue
Project details
Release history Release notifications | RSS feed
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.