A `Result` type with a pseudo-operator `~` that expands to `return Err(err)`

Hi

Context

There have been people, mesmerized by the beautiful monads (and Rust), writing sheds that mimic these monadic behaviours in other (possibly, functional) languages.

Question

I wonder if, without changing the grammar of Python, one can use either the descriptor protocol or one of the operator methods (e.g. ~) to mimic the ? operator in Rust, where it automatically expands into something like: if result is Err, return result.

Of course this has to be done at the C-API level.

I have seen how PyGenObject works at interrogating the PyInterpreterState and just wondering if it is even possible for a type to also interrogate the interpreter thread state and the current frame to return the Err variant of Result back to the function (with return value of type Resuly caller.

1 Like

Some people have done similar things by re-writing the bytecode of a function with a decorator. See for example the (in)famous goto statement:

1 Like

See related:

2 Likes

I meant it to be kind of done without a function decorator.

Moved to general discussion (aka Python help), as this proposal is premature. An idea generally needs to make a single, concrete proposal, as well as compare what is possible now with what would be enabled by the change.

1 Like