On Mon, Jan 03, 2022 at 11:31:30PM -0500, elvis kahoro wrote:

> I was hoping there could be some syntax to extend pattern matching to
> handle exceptions such that we could handle patterns with multiple types of
> exceptions like so:
> 
> match *this_raises_an_exception*, *this_raises_another_exception*:
>         case *AttributeError*, *TypeError*:
>             print("catches attribute and type errors")
>         case *AttributeError*, *AttributeError*:
>             print("catches attribute and attribute")

Can you explain why you want to do that?

Right now, to do something like that you would need something like this:

    err1 = err2 = None
    try:
        x = this_raises_an_exception
    except AttributeError as e:
        err1 = e
    try:
        y = this_raises_another_exception
    except (AttributeError, TypeError) as e:
        err2 = e

    if err1 is err2 is None:
        # handle the case where neither expression raised
        print(x, y)

    elif err1 is None or err2 is None:
        # only one expression raised
        print("everything else")

    elif isinstance(err1, AttributeError):
        if isinstance(err2, AttributeError):
            print("two Attribute Errors")

        elif isinstance(err2, TypeError):
            print("Attribute Error and Type Error")

        else:
            print("everything else")

    else:
        print("everything else")


or something equally convoluted. I agree that if you are currently 
writing code this horrible, the idea of using a match statement would 
seem attractive.

But... are you actually writing this sort of horrible, convoluted, 
complex, complicated mess of code? Why??? Please explain your actual 
concrete use-case for this. Otherwise it looks to me like an 
over-generalisation.

I think I would need to see a sketch of *real* code to understand why 
you want this.

As I see it, there are three realistic use-cases, all which can be 
handled with existing syntax:

* protect the match expression in a try...except:

    try: x = expression
    except SomeError: ...
    match x: ...

* protect a case block in a try...except:

    match expression:
        case something:
            try:
                block
            except SomeError: ...


* protect the whole construct in a try...except:

    try:
        match expression:
            case something:
                block
    except:
        log(something)
        raise


Anything else seems to me to be YAGNI; too complex and complicated to 
care about.

Convince me that I'm wrong.



-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/RNMCIYU6ZGEWQWGAQ4B3QRN225O3MS6W/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to