Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有像Ruby';什么是andand?_Python_Ruby_Null_Andand - Fatal编程技术网

Python 有没有像Ruby';什么是andand?

Python 有没有像Ruby';什么是andand?,python,ruby,null,andand,Python,Ruby,Null,Andand,例如,我有一个对象x,它可能是None或浮点数的字符串表示形式。我想做以下工作: do_stuff_with(float(x) if x else None) 除了不必键入两次x,就像Ruby的库一样: 我们没有这样的产品,但要推出自己的产品并不难: def andand(x, func): return func(x) if x else None >>> x = '10.25' >>> andand(x, float) 10.25 >&g

例如,我有一个对象
x
,它可能是
None
或浮点数的字符串表示形式。我想做以下工作:

do_stuff_with(float(x) if x else None)
除了不必键入两次
x
,就像Ruby的库一样:


我们没有这样的产品,但要推出自己的产品并不难:

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

根据雷蒙德的想法,这里有一家制造这种有条件包装的工厂。既然你可以让Python为你写,为什么还要自己写呢

def makeandand(func):
    return lambda x: func(x) if x else None

andandfloat = makeandand(float)

andandfloat('10.25')
>>> 10.25

andandfloat('')
>>> None
并不完全是python,但我不知道该用什么更好的名字。可能是
trap
,因为您正在捕获无效值

值得注意的是,一个常见的Python习惯用法是继续并尝试做您需要做的事情,并在异常出现时处理它们。这被称为EAFP,出自格言“请求原谅比获得允许更容易”。因此,也许有一种更具python风格的写作方式:

def maketrap(func, *exceptions):
    def trap(x):
        try:
            return func(x)
        except exceptions or (Exception,):
            return None
    return andand

trapfloat = maketrap(float)

# optionally specify the exceptions to convert to a None return
# (default is to catch anything but you may want to allow some through)
trapfloat = maketrap(float, ValueError)
trapfloat = maketrap(float, ValueError, TypeError)

# if you don't want to store it (i.e. you only need it once or twice)...
maketrap(float)(x)    # ... just call it immediately

在您的用例中,我认为这种方法是一种胜利:它透明地处理任何可以转换为
浮点值的事情,并且如果传入一个错误的但可以转换为-
浮点值的值(例如0),它会做“正确的事”。

模仿Ruby的and:return(func(x)if(x不是None)else None)。并且可能发送可选的额外参数:def和(x,func,*args,**kwargs)我喜欢它,根据tokland的建议,它简洁而强大。这个解决方案很有创意,在某些用例中肯定很有用。但我不想为我使用的每一种方法创建包装,特别是如果我只使用一次或两次的话。@Andres:对于那些一次性用例,你可以立即调用它:
maketrap(float)(“2.5”)
等等。
def maketrap(func, *exceptions):
    def trap(x):
        try:
            return func(x)
        except exceptions or (Exception,):
            return None
    return andand

trapfloat = maketrap(float)

# optionally specify the exceptions to convert to a None return
# (default is to catch anything but you may want to allow some through)
trapfloat = maketrap(float, ValueError)
trapfloat = maketrap(float, ValueError, TypeError)

# if you don't want to store it (i.e. you only need it once or twice)...
maketrap(float)(x)    # ... just call it immediately