Python Forum

Full Version: maybe, maybe not
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
ha ha, i just ran across a case where i wanted to code a bool value of Maybe. maybe i should rethink this script. i already use None so it will have to be something else. i'm thinking ...
You have a function like this:

from random import choice


def broken_function():
    return choice((1, "1", 1.1, None, ...))
A function which handles the None:

def maybe(obj):
    return obj is not None
And then the combination of broken_function and maybe:
result = broken_function()
if maybe(result):
    print("Got the result:", result)
If your function return results or different states, you can create sentinel objects for this task.

RESULT_NO_OK = object()
RESULT_INF = object()
There is also a new PEP about sentinels: https://www.python.org/dev/peps/pep-0661/

Another way to have this control flow is the use of exceptions. Raise your custom exceptions and the caller has to catch them.
With Python 3.11 the try-block without an occurring exception will cost nearly zero overhead: https://docs.python.org/3.11/whatsnew/3....imizations