Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
maybe, maybe not
#1
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 ...
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#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
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

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