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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With