I'd like to be able to deconstruct `complex` objects into their real and imaginary components using a `match` statement, like:

    match 1-4j:
        case complex(a, b):
            print(f"{a=} {b=}")

This would just require setting

    complex.__match_args__ = ("real", "imag")

The other builtin type I think should be able to do this is `slice`:

    match slice(1, -1, None):
        case slice(start, stop, step):
            print(f"{start=} {stop=} {step=}")

which would require

    slice.__match_args__ = ("start", "stop", "step")

This would be useful, for example, in custom __getattr__ methods which need to handle slices.

    def __getattr__(self, arg):
        match arg:
            case slice(start, stop, end):
                ...  # handle slice
            case n if isinstance(n, int):
                ...  # handle single index
            case _:
                raise TypeError

There are various other builtin types which could conceivably have __match_args__ defined, but with varying degrees of usefulness:

range, property, staticmethod, classmethod, memoryview, types.GenericAlias, types.UnionType, types.CodeType, types.FunctionType,  types.MethodType, types.ModuleType, types.GenericAlias, types.FrameType, types.TracebackType, types.CellType

But none of these are really that important, I think.

What do you think?

Patrick

_______________________________________________
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/OMXUKLBFROW72TUBO6QDH5FOZ4MHDYOC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to