例如,我有一个对象x
,它可能是None
或浮点数的字符串表示形式。我要做到以下几点:是否有像Ruby和andand这样的Python库(或模式)?
do_stuff_with(float(x) if x else None)
除了不必键入x
两次,与Ruby的andand库:
require 'andand'
do_stuff_with(x.andand.to_f)
例如,我有一个对象x
,它可能是None
或浮点数的字符串表示形式。我要做到以下几点:是否有像Ruby和andand这样的Python库(或模式)?
do_stuff_with(float(x) if x else None)
除了不必键入x
两次,与Ruby的andand库:
require 'andand'
do_stuff_with(x.andand.to_f)
我们没有这些之一,但它并不难自己推出:
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为你写'em'时自己写'他们?
def makeandand(func):
return lambda x: func(x) if x else None
andandfloat = makeandand(float)
andandfloat('10.25')
>>> 10.25
andandfloat('')
>>> None
andand
不完全是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
在您的使用情况下,我认为这种做法是双赢的:它与任何可以转换为float
透明的交易,并执行的”正确的事情“,如果一个虚假但可转换的 - float
值(如0)被传入。
这个解决方案很有创意,在某些用例中绝对有用。但我不想为每一种我使用的方法创建包装,特别是如果我只使用一次或两次。 –
@Andres:你可以立即调用它来处理那些一次性用例:'maketrap(float)(“2.5”)'等等 – kindall
模仿Ruby的andand:return(func(x)if(x不是None)else None)。也许可以发送可选的额外参数:def andand(x,func,* args,** kwargs) – tokland
我喜欢它,托克兰的建议,它简洁而强大。 –