鉴于下面的例子,哪个更pythonic?使用函数组合,lambdas或(现在用于)完全不同的东西?我不得不说lambdas似乎更具可读性,但Guido本人似乎想完全删除lambdas - http://www.artima.com/weblogs/viewpost.jsp?thread=98196
from functools import partial
from operator import not_, ge
def get_sql_data_type_from_string(s):
s = str(s)
# compose(*fs) -> returns composition of functions fs
# iserror(f, x) -> returns True if Exception thrown from f(x), False otherwise
# Using function composition
predicates = (
('int', compose(not_, partial(iserror, int))),
('float', compose(not_, partial(iserror, float))),
('char', compose(partial(ge, 1), len)))
# Using lambdas
predicates = (
('int', lambda x: not iserror(int, x)),
('float', lambda x: not iserror(float, x)),
('char', lambda x: len(x) <= 1))
# Test each predicate
for i, (t, p) in enumerate(predicates):
if p(s):
return i, t
# If all predicates fail
return (i + 1), 'varchar'
答案 0 :(得分:8)
从未见过Python的程序员将能够一目了然地找出lambda。我已经使用Python超过十年了,我正在摸索着弄清楚组合形式,即使用lambda版本进行比较。
去寻找一个不吸吮的人。另外,鉴于lambda切入3.0,我怀疑它会被删除。
答案 1 :(得分:2)
这是一种属于“不同”类别的方法:
def get_sql_data_type_from_string(s):
s = str(s)
def char(x):
if len(x)<=1:
return x
raise RuntimeError('Not a char')
predicates = (
('int', int),
('float', float),
('char', char)
)
# Test each predicate
for i, (t, p) in enumerate(predicates):
try:
p(s)
return i,t
except:
pass
# If all predicates fail
return (i + 1), 'varchar'