Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more pythonic - function composition, lambdas, or something else? [closed]

Given the example below, which is more pythonic? Using function composition, lambdas, or (now for) something completely different? I have to say that the lambdas seem to be more readable, but Guido himself seems to want to remove lambdas altogether - 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'
like image 982
pyrospade Avatar asked Sep 02 '12 05:09

pyrospade


1 Answers

A programmer who has never seen Python will be able to figure out the lambda at a glance. I've been using Python for over ten years, and I was scratching my head to figure out the composition form, even with the lambda version to compare against.

Go for the one that doesn't suck. Also, given that lambda made the 3.0 cut, I doubt it will ever be removed.

like image 141
Marcelo Cantos Avatar answered Oct 28 '22 23:10

Marcelo Cantos