[Python-ideas] Maybe/Option builtin

Alex Hammel ahammel87 at gmail.com
Wed May 21 17:38:16 CEST 2014


What's a specific use case? Usually a Maybe is used to model a chain of
computations which might fail. You can use exceptions for that in Python:

try:
    foo1 = bar()
    foo2 = baz(foo1)
    foo3 = quux(foo2)
except FooException:
    # recover


On occasion I've wanted to do the opposite: call a number of functions and
keep the value of the first one that doesn't throw an exception. I
implemented it like this<https://gist.github.com/ahammel/ef978511dad42479fd31>.


That certainly doesn't need to be a built-in, though, and I'm not convinced
it belongs in that standard library. It's a relatively rare use-case, and
it's easy to roll-your-own if you need it.


On Wed, May 21, 2014 at 7:49 AM, mulhern <mulhern at gmail.com> wrote:

> I feel that a Maybe/Option type, analogous to the types found in Haskell
> or OCaml would actually be useful in Python. The value analogous to the
> None constructor should be Python's None.
>
> Obviously, it wouldn't give the type-checking benefits that it gives in
> statically checked languages, but every use of a Maybe object as if it were
> the contained object would give an error, alerting the user to the fact
> that None is a possibility and allowing them to address the problem sooner
> rather than later.
>
> I feel that it would be kind of tricky to implement it as a class.
> Something like:
>
> class Maybe(object):
>
>     def __init__(self, value=None):
>         self.value = value
>
>     def value(self):
>         return self.value
>
> is a start but I'm not able to see how to make
>
> if Maybe():
>     print("nothing") # never prints
>
> but
>
> if Maybe({}):
>     print("yes a value") #always prints
>
> which is definitely the desired behaviour.
>
> I also think that it would be the first Python type introduced solely
> because of its typey properties, not because it provided any actual
> functionality, which might be considered unpythonic.
>
> Any comments?
>
> Thanks!
>
> - mulhern
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140521/b8a042ca/attachment-0001.html>


More information about the Python-ideas mailing list