New GitHub issue #107721 from yanivakivas:<br>
<hr>
<pre>
## Feature or enhancement
**Assign match-case result to a variable**
## Pitch
Currently, in Python 3.10+, match-case statements allow us to perform pattern matching and execute code blocks based on patterns. However, the result of the match-case statement cannot be directly assigned to a variable. My suggestion is to introduce the ability to assign the match-case result to a variable, making the syntax more concise and flexible.
**Current approach:**
```python
def is_adult(age):
match age:
case x if x > 21:
return True
case _:
return False
```
**Suggested approach:**
```python
def is_adult(age):
can_drink = match age:
case x if x > 21:
True
case _:
False
```
By introducing this enhancement, developers can assign the match-case result to a variable (can_drink in the example) and use it as desired. This will lead to more readable and expressive code, especially when multiple conditions are involved.
## Limitations
**Single Assignment Limitation:** Assigning the match-case result to a variable should only be allowed if the variable is assigned within each case block. Allowing multiple assignments to the same variable from different case blocks might lead to confusion and unexpected behavior.
**Scope and Lifetime:** The scope and lifetime of the variable assigned within a match-case statement need to be well-defined to avoid potential issues with variable visibility and memory management.
**Returning from Match-case Block:** If the match-case statement is used inside a function, returning from within a case block might not behave as expected. The return might only exit the current case block, not the entire function, leading to subtle bugs.
**Non-trivial Expressions:** When the match-case result is assigned to a variable, complex expressions within a case block might lead to less readable code, reducing the clarity of the intent.
**Consistency with Existing Syntax:** Care should be taken to ensure that the proposed syntax for assigning the match-case result to a variable aligns well with existing Python conventions and is intuitive for developers.
**Performance Considerations:** If the match-case statement is used in performance-critical sections of code, the introduction of variable assignments might impact performance. Proper benchmarks should be conducted to assess any potential overhead.
By addressing these limitations and considerations, the proposed enhancement can provide a valuable addition to Python's match-case feature, allowing developers to write more elegant and maintainable code.
</pre>
<hr>
<a href="https://github.com/python/cpython/issues/107721">View on GitHub</a>
<p>Labels: type-feature</p>
<p>Assignee: </p>