diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4f367f5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,18 @@ +Copyright © 2017 Erez Shinan + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..7809d89 --- /dev/null +++ b/README.md @@ -0,0 +1,151 @@ +# Pattern matching PEP 634 + +This is a python package implementing pattern-matching similar to what [PEP-634](https://www.python.org/dev/peps/pep-0634/) proposes. + +## Installation + +Use the package manager [pip](https://pip.pypa.io/en/stable/) to install pattern-matching-pep634. + +```bash +pip install pattern-matching-pep634 +``` + +## Usage + +There are 4 different implementations of pattern matching in here. + +The safest one is this: +```python +from pattern_matching import Matcher + +match = Matcher(Click, KeyPress, Quit) + +with match(event.get()) as m: + if m.case('Click(position=(x, y))'): + handle_click_at(m.x, m.y) + elif m.case('KeyPress(key_name="Q") | Quit()'): + m.game.quit() + elif m.case('KeyPress(key_name="up arrow")'): + m.game.go_north() + elif m.case('KeyPress()'): + pass # Ignore other keystrokes + elif m.case('other_event'): + raise ValueError(f"Unrecognized event: {m.other_event}") +``` + +(This is based on an example in [PEP-636](https://www.python.org/dev/peps/pep-0636/)) + +Note how you have to specify which names you will be using, and how you always have to use `m.` to access the capture values. +This is the so called `no_magic` implementation. This implementation will work even in Python3.7 and other implementations than CPython that support the same features as 3.7 + +### auto_lookup + +If you don't want to specify which classes you will be using, but don't want to have the pattern matching messing with the locals, you can use `auto_lookup` + +```python +from pattern_matching.auto_lookup import match + + +with match(event.get()) as m: + if m.case('Click(position=(x, y))'): + handle_click_at(m.x, m.y) + elif m.case('KeyPress(key_name="Q") | Quit()'): + m.game.quit() + elif m.case('KeyPress(key_name="up arrow")'): + m.game.go_north() + elif m.case('KeyPress()'): + pass # Ignore other keystrokes + elif m.case('other_event'): + raise ValueError(f"Unrecognized event: {m.other_event}") +``` + +You still have to use `m.`, but at least you don't have to duplicate the class names and carry around a `Matcher` instance. + +Note that this might have weird edge cases and fail for some reason sometimes. (Most notably conflict between what you think is visible in a function vs. what really is) + +### injecting + +This is for those who don't want to type `m.` everywhere. +```python +from pattern_matching.injecting import match + + +with match(event.get()): + if case('Click(position=(x, y))'): + handle_click_at(x, y) + elif case('KeyPress(key_name="Q") | Quit()'): + game.quit() + elif case('KeyPress(key_name="up arrow")'): + game.go_north() + elif case('KeyPress()'): + pass # Ignore other keystrokes + elif case('other_event'): + raise ValueError(f"Unrecognized event: {other_event}") +``` + +This will 'infect' the name space and put the captured names into it. It also does `auto_lookup`. + +This is will only work on Python3.9. It might also randomly break with debuggers/coverage/tracing tools. + +Note that this heavily suffers from the problem of what locals are defined and what aren't, e.g. the problem of where names are looked up. + + +### full_magic + +This is the one that is as close as possible to the syntax proposed in PEP-634 + +```python +from pattern_matching.full_magic import match + + +with match(event.get()): + if Click(position=(x, y)): + handle_click_at(x, y) + elif KeyPress(key_name="Q") | Quit(): + game.quit() + elif KeyPress(key_name="up arrow"): + game.go_north() + elif KeyPress(): + pass # Ignore other keystrokes + elif other_event: + raise ValueError(f"Unrecognized event: {other_event}") +``` + +(only differences to PEP-634 is `with match` instead of match, `if`/`elif` instead of `case` and `:=` instead of `as`) + +This does source-code analysis to figure out what cases to take and which names do bind. This is also Python3.9 only, and might break with any minor release of python. But that is unlikely. + +Note: Sometimes, the small amount of optimization that python does can still break this: + +```python +from pattern_matching.full_magic import match + + +with match(n): + if 1 | 2: + print("Smaller than three") + elif 3: + print("Equal to three") + elif _: + print("Bigger than three") +``` + +Python's peephole optimizer will (normally) correctly figure out that only the first branch can be taken and throw away the rest of the code. +This means that `match` can not correctly jump to the other lines. To circumvent the optimizer, `c@` ('case') can be added to prevent the optimization + +```python +from pattern_matching.full_magic import match + + +with match(n): + if c@ 1 | 2: + print("Smaller than three") + elif c@ 3: + print("Equal to three") + elif c@ _: + print("Bigger than three") +``` + This doesn't have to be done always, but it is a good first attempt if you get weird error messages. + +## License +[MIT](https://choosealicense.com/licenses/mit/) \ No newline at end of file diff --git a/pattern_matching/__init__.py b/pattern_matching/__init__.py index acbfb8d..80fa1db 100644 --- a/pattern_matching/__init__.py +++ b/pattern_matching/__init__.py @@ -1,61 +1,6 @@ from __future__ import annotations -from typing import Any +from .no_magic import Matcher -from pattern_matching.pattern_engine import str2pattern - -class _Match: - def __init__(self, matcher: Matcher, value: Any): - self.__matcher__ = matcher - self.__value__ = value - self.__vars__ = None - - def __getattr__(self, item): - return self.__vars__[item] - - def __matmul__(self, other: str): - return self.case(other) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - return False - - def case(self, pattern: str): - assert isinstance(pattern, str) - pt = str2pattern(pattern) - var = pt.match(self.__value__, self.__matcher__._get) - if var is not None: - self.__vars__ = var - return True - else: - return False - - def __call__(self, pattern: str): - return self.case(pattern) - - -class Matcher: - """ - A portable match statement. - - This is what should always be used. It forces you to clearly define all accessible names, including constants. - """ - def __init__(self, *args, **kwargs): - self.__names__ = kwargs - for a in args: - try: - self.__names__[a.__name__] = a - except AttributeError: - raise ValueError("Can not use values that don't have a `__name__` attribute (functions, classes) without specifying a name") - - def _get(self, name: str): - try: - return self.__names__[name] - except KeyError: - raise NameError - - def __call__(self, value: Any): - return _Match(self, value) \ No newline at end of file +__version__ = "0.1.0" \ No newline at end of file diff --git a/pattern_matching/no_magic.py b/pattern_matching/no_magic.py new file mode 100644 index 0000000..a282b49 --- /dev/null +++ b/pattern_matching/no_magic.py @@ -0,0 +1,61 @@ +from __future__ import annotations +from typing import Any + +from pattern_matching.pattern_engine import str2pattern + + +class _Match: + def __init__(self, matcher: Matcher, value: Any): + self.__matcher__ = matcher + self.__value__ = value + self.__vars__ = None + + def __getattr__(self, item): + return self.__vars__[item] + + def __matmul__(self, other: str): + return self.case(other) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + return False + + def case(self, pattern: str): + assert isinstance(pattern, str) + pt = str2pattern(pattern) + var = pt.match(self.__value__, self.__matcher__._get) + if var is not None: + self.__vars__ = var + return True + else: + return False + + def __call__(self, pattern: str): + return self.case(pattern) + + +class Matcher: + """ + A portable match statement. + + This is what should always be used. It forces you to clearly define all accessible names, including constants. + """ + + def __init__(self, *args, **kwargs): + self.__names__ = kwargs + for a in args: + try: + self.__names__[a.__name__] = a + except AttributeError: + raise ValueError("Can not use values that don't have a `__name__` attribute (functions, classes) without specifying a name") + + def _get(self, name: str): + try: + return self.__names__[name] + except KeyError: + raise NameError + + def __call__(self, value: Any): + return _Match(self, value) \ No newline at end of file diff --git a/pattern_matching/pattern_engine.py b/pattern_matching/pattern_engine.py index 19c2e04..d9ae7db 100644 --- a/pattern_matching/pattern_engine.py +++ b/pattern_matching/pattern_engine.py @@ -99,7 +99,7 @@ def match(self, value: Any, get: Callable[[str], Any]) -> Optional[dict[str, Any res = pat.match(val, get) if res is None: return None - out |= res + out.update(res) return out @@ -110,7 +110,7 @@ def _match_all(pts: tuple[Pattern, ...], value: Any, get) -> Optional[dict[str, if cvar is None: return None else: - out |= cvar + out.update(cvar) return out @@ -147,7 +147,7 @@ def match(self, value: Any, get: Callable[[str], Any]) -> Optional[dict[str, Any cvar = vp.match(val, get) if cvar is None: return None - out |= cvar + out.update(cvar) used.add(kp) if self.star is not None: out[self.star] = {k: v for k, v in value.items() if k not in used} @@ -175,7 +175,7 @@ def match(self, value: Any, get: Callable[[str], Any]) -> Optional[dict[str, Any if post_out is None: return None - return pre_out | {self.star: star_val} | post_out + return {**pre_out,self.star: star_val, **post_out} pattern_lark_parser = Lark(""" @@ -224,7 +224,7 @@ def match(self, value: Any, get: Callable[[str], Any]) -> Optional[dict[str, Any @v_args(inline=True) -class Lark2Pattern(Transformer[Pattern]): +class Lark2Pattern(Transformer): def __default__(self, data, children, meta): raise NotImplementedError((data, children, meta)) diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..10c38f3 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +version = attr: pattern_matching.__version__ \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..a23f08f --- /dev/null +++ b/setup.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from setuptools import setup, find_packages +import pathlib + +here = pathlib.Path(__file__).parent.resolve() + +# Get the long description from the README file +long_description = (here / 'README.md').read_text(encoding='utf-8') + + +setup( + name='pattern-matching-pep634', + + # version= # Handled in setup.cfg + + description='Pattern matching, backport of PEP-634', + + long_description=long_description, + + long_description_content_type='text/markdown', + + url='https://github.com/MegaIng/pattern-matching', + + author='MegaIng', + author_email='trampchamp@hotmail.de', + + # Classifiers help users find your project by categorizing it. + # + # For a list of valid classifiers, see https://pypi.org/classifiers/ + classifiers=[ + 'Development Status :: 3 - Alpha', + + 'Intended Audience :: Developers', + 'Topic :: Software Development', + + 'License :: OSI Approved :: MIT License', + + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3 :: Only', + 'Programming Language :: Python :: Implementation :: CPython', + ], + + keywords='pattern-matching, PEP-634, backport', + + packages=['pattern_matching'], + + python_requires='>=3.7', + install_requires=['lark'], + project_urls={ # Optional + 'Bug Reports': 'https://github.com/MegaIng/pattern-matching/issues', + 'Source': 'https://github.com/MegaIng/pattern-matching/', + }, +) diff --git a/tests/examples.py b/tests/examples.py index 14cf671..6495045 100644 --- a/tests/examples.py +++ b/tests/examples.py @@ -247,6 +247,7 @@ def do(command): >4 >4 """) + TEST_FALLTHROUGH_2 = Example('TEST_FALLTHROUGH_2', """ def classify(i): match i: diff --git a/tests/test_full_magic.py b/tests/test_full_magic.py index 700ec97..52a965e 100644 --- a/tests/test_full_magic.py +++ b/tests/test_full_magic.py @@ -108,8 +108,11 @@ def {n.lower()}(self):\n {indent(full_magic.translate(e), ' ' * 12)} ''') -_generate_tests() -TestFullMagicGenerated = __import__(GENERATED_MODULE_NAME).TestFullMagicGenerated +try: + _generate_tests() + TestFullMagicGenerated = getattr(__import__('tests.' + GENERATED_MODULE_NAME), GENERATED_MODULE_NAME).TestFullMagicGenerated +except SyntaxError: + TestFullMagicGenerated = None if __name__ == '__main__': unittest.main() \ No newline at end of file