Unpack .args
for Structural Pattern Matching against Exceptions
#105393
Labels
type-feature
A feature request or enhancement
Feature or enhancement
match_class
inceval.c
should default to match the positional arguments in the.args
attribute for ExceptionsPitch
By default, the BaseException object in Python defines an args attribute which is assigned the tuple of the arguments given to Exception objects at instantiation.
Matching this object in structural pattern matching (SPM) requires knowledge of this implementation detail and results in the match statement being overly verbose for developers who prefer
return
-ing errors instead ofraise
-ing them.the
match_class
function inceval.c
allows for passing positional arguments to the match for classes. The function uses a__match_args__
class attribute to compare positional values against attributes of the instance. These attributes are packed into aPyList
object, and the values are then compared against for SPM.The proposal here is to, for Exception objects, unpack the
.args
attribute by default into the list of values used for SPM. The result would be a cleaner syntax more aligned with how exception objects are constructed.A proof-of-concept implementation can be found here:
https://github.com/1mikegrn/cpython
Previous discussion
https://discuss.python.org/t/add-structural-pattern-matching-to-exception-objects/27389/22
https://www.reddit.com/r/Python/comments/13zq790/add_match_args_to_baseexception/
Originally this idea was framed as adding a
__match_args__ = ("args", )
class attribute to the BaseException class. The downside there is that you are then required to pass a tuple of args to thecase
. After further investigation and discussion, changingmatch_class
to unpack theargs
attribute for Exception objects seems the better approach.The purpose of this change is to better support the notion of errors as values in Python. Keeping errors out of the global error state and in the local stack provides for more granular control flow and explicitness in error handling. Static type checkers like mypy can validate type safety more effectively for errors that are returned instead of raised. It's an approach that has been seen in multiple other languages as a first-class citizen, and major projects in languages with
try/catch
functionality have been known to emulate the approach so as to derive its benefits.The text was updated successfully, but these errors were encountered: