In dem folgenden Beispiel, das mehr Python ist? Mit Funktionszusammensetzung, Lambdas oder (jetzt für) etwas ganz anderes? Ich muss sagen, dass die Lambda-Ausdrücke scheinen besser lesbar zu sein, aber Guido scheint sich zu wollen lambdas ganz entfernen - http://www.artima.com/weblogs/viewpost.jsp?thread=98196Was ist mehr Python - Funktion Zusammensetzung, Lambdas oder etwas anderes?
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'
ich denke, die Lambda-Version der direkteste und klar ist, was ich denke, macht es auch die meisten „pythonic“. –
Nitpick - entsprechend Ihrer Definition von iserror sollten Sie etwas wie 'iserror (int, x)' im Gegensatz zu 'iserror (int (x))' haben. –
Lambdas sind nett – pyCthon