[Python-ideas] Maybe/Option builtin

Steven D'Aprano steve at pearwood.info
Thu May 22 01:50:31 CEST 2014


On Wed, May 21, 2014 at 10:49:36AM -0400, mulhern 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.

Since this is a Python list, you shouldn't take it for granted that we 
will be familiar with Haskell or Ocaml, nor expect us to go off and 
study those languages well enough to understand what a Maybe object is 
used for or how it will fit into Python's execution model.

I'm no expect on either of those two languages, but it seems to me that 
that the only point of Maybe is to allow the static type checker to 
distinguish between (for example) "this function returns a string" and 
"this function returns either a string or None". Since Python doesn't do 
static, compile-time type checks, I'm having difficulty in seeing what 
would be the point of Maybe in Python.

As I said, I'm not an expert in Haskell, but I don't think this proposal 
is helpful, and certainly not helpful enough to make it a built-in or 
standard part of the language. If I have missed some benefit of Maybe, 
please explain how it would apply in Python terms.



> 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

In Python 2, define __nonzero__. In Python 3, define __bool__.

https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
https://docs.python.org/3/reference/datamodel.html#object.__bool__

 
> but
> 
> if Maybe({}):
>     print("yes a value") #always prints
> 
> which is definitely the desired behaviour.

Not to me it isn't. This goes against the standard Python convention 
that empty containers are falsey. Since Maybe({}) wraps an empty dict, 
it should be considered a false value.




-- 
Steven


More information about the Python-ideas mailing list