maybe, maybe not - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Forum & Off Topic (https://python-forum.io/forum-23.html) +--- Forum: Bar (https://python-forum.io/forum-27.html) +--- Thread: maybe, maybe not (/thread-34341.html) |
maybe, maybe not - Skaperen - Jul-22-2021 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 ...
RE: maybe, maybe not - DeaD_EyE - Jul-22-2021 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 NoneAnd 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.11.html#optimizations |