-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
gh-106246: Allow the use of unions as match patterns #118525
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
Conversation
@@ -3361,6 +3370,31 @@ class A: | |||
w = 0 | |||
self.assertIsNone(w) | |||
|
|||
def test_union_type_postional_subpattern(self): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
english is not my mother tongue, but postional
must not to be replaced by positional
?
@@ -3,6 +3,7 @@ | |||
import dataclasses | |||
import enum | |||
import inspect | |||
from re import I |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
accidental?
x = 0 | ||
match x: | ||
case IntOrStr(): | ||
x = 1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add a test that involves a union that does not match.
Please rename the title to use gh-106246. |
@@ -470,6 +471,16 @@ _PyEval_MatchClass(PyThreadState *tstate, PyObject *subject, PyObject *type, | |||
if (PyObject_IsInstance(subject, type) <= 0) { | |||
return NULL; | |||
} | |||
// Subpatterns are not supported for union types: | |||
if (_PyUnion_Check(type)) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't like the fact that we call _PyUnion_Check(type)
twice for no real reason.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we save the result in a variable? Or would it cleaner to handle unions first?
Is there any particular reason for disallowing subpatterns? The case for matching a union in the first place is typically because they share some relevant interface or attribute. For example: FuncDef = ast.FunctionDef | ast.AsyncFunctionDef
match node:
case FuncDef(name=name, body=body):
... instead of match node:
case ast.FunctionDef(name=name, body=body) | ast.AsyncFunctionDef(name=name, body=body):
... |
@sobolevn @JelleZijlstra @sylvainmouquet @tmke8 I pushed a variant of this pull request that addresses the raised issues and also support subpatterns #118644. |
This didn't require many code changes. Though I'm not entirely sure about code style and whether I added enough tests.