I’m a functional programmer at heart, so I’m quite happy thinking in terms of things like functors and monads.
I use F# a lot which has computation expressions which is nice syntax for using monads without having to write bind continuations everywhere.
final in the above code will either be Error if some_function_that_returns_result returned an error, or it will be Ok with the value of y.
Today I was pointed at generator.send in Python. Which you can abuse use to get a pretty similar flow.
If you execute the above python you’ll get the following output:
Run passing example
Do something, got value 1
Do something and maybe fail, got value 5
Don't fail
Do something else, got value 5
Final result = Ok(10)
Run failing example
Do something, got value 10
Do something and maybe fail, got value 14
Do fail
Final result = Error(Some bad error)
Isn’t that fun! It’s monadic bind in python and it doesn’t even look that bad.