Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
maybe, maybe not
#2
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
maybe, maybe not - by Skaperen - Jul-22-2021, 12:03 AM
RE: maybe, maybe not - by DeaD_EyE - Jul-22-2021, 07:30 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020