gh-106246: Allow the use of unions as match patterns - #118525
Conversation
| w = 0 | ||
| self.assertIsNone(w) | ||
|
|
||
| def test_union_type_postional_subpattern(self): |
There was a problem hiding this comment.
english is not my mother tongue, but postional must not to be replaced by positional?
| import dataclasses | ||
| import enum | ||
| import inspect | ||
| from re import I |
| x = 0 | ||
| match x: | ||
| case IntOrStr(): | ||
| x = 1 |
There was a problem hiding this comment.
Add a test that involves a union that does not match.
|
Please rename the title to use gh-106246. |
| return NULL; | ||
| } | ||
| // Subpatterns are not supported for union types: | ||
| if (_PyUnion_Check(type)) { |
There was a problem hiding this comment.
I don't like the fact that we call _PyUnion_Check(type) twice for no real reason.
There was a problem hiding this comment.
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.