是否有像 Ruby 的 andand 这样的 Python 库(或模式)?

问题描述:

例如,我有一个对象 x,它可能是 None 或浮点数的字符串表示.我想做以下事情:

For example, I have an object x that might be None or a string representation of a float. I want to do the following:

do_stuff_with(float(x) if x else None)

除了不必键入 x 两次,就像 Ruby 的 and 库一样:

Except without having to type x twice, as with Ruby's andand library:

require 'andand'
do_stuff_with(x.andand.to_f)

我们没有其中之一,但不难推出您自己的方案:

We don't have one of those but it isn't hard to roll your own:

def andand(x, func):
    return func(x) if x else None

>>> x = '10.25'
>>> andand(x, float)
10.25
>>> x = None
>>> andand(x, float) is None
True