是否存在像Ruby和?的Python库(或模式)?

And*_*rio 6 ruby python null andand

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

do_stuff_with(float(x) if x else None)
Run Code Online (Sandbox Code Playgroud)

除了不需要输入x两次外,就像Ruby的andand库一样:

require 'andand'
do_stuff_with(x.andand.to_f)
Run Code Online (Sandbox Code Playgroud)

Ray*_*ger 9

我们没有其中一个但是你自己也不难:

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
Run Code Online (Sandbox Code Playgroud)

  • 模仿Ruby的andand:return(func(x)if(x不是None)否则为None).并且可能发送可选的额外args:def andand(x,func,*args,**kwargs) (3认同)