Token is inconsistent in py3.10 pattern matching
See original GitHub issueDescribe the bug
Token
is not working correctly with structural pattern matching.
While you can create tokens as:
t = Token(type_="TEST", value="test")
you have to pattern match on:
match t:
case Token(type="TEST"):
pass
As pattern matching tries to access the attributes by names provided to the pattern.
I find this solution fairly confusing and ugly, as well as hard to work with type checkers and triggers a nasty bug in pylance (https://github.com/microsoft/pylance-release/issues/3197).
To Reproduce
t = Token(type_="TEST", value="test")
match t:
case Token(type_="TEST"):
print("with underscore") # expected match
case Token(type="TEST"):
print("without underscore") # actual match
Potential solutions
The simplest solution would be to rename type
/type_
to be consistent between the __init__
argument and the attribute, but this might be a fairly big change to the API. There might be a possibility to add custom pattern matching logic so that matching works on Token(type_=...)
, but I’m not very familiar with the pattern matching API yet.
Issue Analytics
- State:
- Created a year ago
- Comments:12 (12 by maintainers)
Top GitHub Comments
I would say that both should be done.
No, IMO the behavior that is achived with
type, value
is good: You can ignore the type if you are matching asstr
, which is the expected behavior. I feared that casea
would not behave correctly, but if it does I think we should keep it with that.