Commentary published in an article: https://dev.to/taikedz/rusts-option-type-in-python-547p
Using this type allows the developer to express nullness and force the recipient of the Option to code for it. The Option does not stand in for the value, the value must be unpacked from it.
def some_func() -> Option:
some_value = None
# ... implementation ...
if valid:
return Option("some value")
elif not_valid:
# Explicit null-return
return Null
# or even
return Option(some_value) # will behave like Null if some_value is still None
res = some_func()
if res.is_null():
... # handle it
value = res.unwrap()
it can be ignored, or a default result can be used instead:
# Without a check, this may "panic" (borrowing from rust's terminology)
# the program exits systematically with an error message
value = some_func().unwrap("failed to get data from some_func")
# On occurrence of nullity, a default value is substituted instead.
value = some_func().or_default("default data")
on nullity, you may want to use an exception:
value = some_func().or_raise(ValueError, "could not get value")
This makes more sense if you need to force consumers of the code to think about nullity.
In that sense, making use of this mechanism is opinionated.
The likelihood of other python programmers enjoying this is fairly low, even as a semantically succinct technique for way-marking nullity and making ensuring results are checked properly.
Thus, you might want to use it
- as a teaching example to build in good habits
- as your own way of making yourself more conscientious of nullity
- preventing yourself from writing un-checked code later on when you consume your own work ...