Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is_dataclass check in transform() should only match instances not types #2

Closed
RedBeard0531 opened this issue Apr 23, 2021 · 1 comment
Assignees
Labels
bug Something isn't working confirmed fixed
Milestone

Comments

@RedBeard0531
Copy link

def transform(pattern, f):
def rf(p):
return transform(p, f)
if is_dataclass(pattern):
pattern = Dataclass(type(pattern), pattern.__dict__)

Normally you can just pass a type to a terse match, but currently it doesn't work if the type is a dataclass because it tries to match against the type as if it were an instance of the dataclass. https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass recommends using is_dataclass(obj) and not isinstance(obj, type) to only match instances.

Example showing the bug:

In [1]: from dataclasses import dataclass

In [2]: @dataclass
   ...: class Foo:
   ...:     x: int
   ...:

In [3]: from apm import *

In [4]: match(Foo(1), Foo, 1) # <--- should work but doesn't
---------------------------------------------------------------------------
MatchError                                Traceback (most recent call last)
<ipython-input-4-58e7e898a729> in <module>
----> 1 match(Foo(1), Foo, 1)

~/.local/lib/python3.9/site-packages/apm/match.py in match(value, pattern, multimatch, strict, captureall, *extra)
     83                 return invoke(acc[0], [])
     84             return acc[0]
---> 85         raise MatchError(value)
     86
     87     if isinstance(captureall, dict):

MatchError: Foo(x=1)

In [5]: match(Foo(1), InstanceOf(Foo), 1) # <--- workaround
Out[5]: 1
@scravy scravy closed this as completed in e920779 Apr 24, 2021
@scravy scravy self-assigned this Apr 24, 2021
@scravy
Copy link
Owner

scravy commented Apr 24, 2021

Thanks for the report and tracking it down so neatly. Fixed in e920779 and released as https://github.com/scravy/awesome-pattern-matching/releases/tag/0.21.2

@scravy scravy added bug Something isn't working confirmed fixed labels Apr 24, 2021
@scravy scravy added this to the 1.0.0 milestone Apr 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working confirmed fixed
Projects
None yet
Development

No branches or pull requests

2 participants