Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Optionals (or Haskell's Maybe) in Python?

In Swift I can do var?.prop. This results in nil if var is nil, else it results in the value of the prop property of var.

Equivalently, I can do var >>= prop in Haskell, which gives me None is var is None, else it gives me the value of applying prop to the value inside var (wrapped in Just).

Is there an equivalent in Python?

like image 480
Ana Avatar asked Dec 30 '15 23:12

Ana


1 Answers

The other answers are on the right track in suggesting a conditional expression, but wrong about how to do it. You can do it this way:

None if var is None else var.prop

or, equivalently

var.prop if var is not None else None

There is a draft PEP about adding such a feature to Python, and ther has been discussion of it on the Python-ideas mailing list. It doesn't look like it will be added in the near future (if ever), but reading the PEP will give you an idea of some existing and proposed ways of handling this.

like image 187
BrenBarn Avatar answered Sep 19 '22 11:09

BrenBarn