Lisp mentality vs. Python mentality

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Apr 26 00:54:49 EDT 2009


On Sat, 25 Apr 2009 10:50:50 +0300, Ciprian Dorin, Craciun wrote:

> On Sat, Apr 25, 2009 at 10:43 AM,  <bearophileHUGS at lycos.com> wrote:
>> Ciprian Dorin, Craciun:
>>> Python way:
>>> ---------
>>> def eq (a, b) :
>>>     return a == b
>>>
>>> def compare (a, b, comp = eq) :
>>>     if len (a) != len (b) :
>>>         return False
>>>     for i in xrange (len (a)) :
>>>         if not comp (a[i], b[i]) :
>>>             return False
>>>     return True
>>
>> That's not "pythonic".
>>
>> Bye,
>> bearophile
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
>     Ok... Then what's pythonic? Please give a pythonic implementation...

Don't re-invent the wheel. Instead of creating your own functions, use 
existing tools to your advantage.

import operator

def compare(a, b, comp=operator.eq):
    if len(a) != len(b):
        return False
    for a, b in zip(a, b):
        if not comp(a[i], b[i]):
            return False
    return True


But we can re-write that to be even more pythonic, by using the built-in 
all():

def compare(a, b, comp=operator.eq):
    if len(a) != len(b):
        return False
    return all(comp(x, y) for (x, y) in zip(a, b))

or even:

def compare(a, b, comp=operator.eq):
    return (len(a) == len(b)) and all(comp(*t) for t in zip(a, b))


(All the above are untested, so please excuse any errors.)


>     Ciprian Craciun.
> 
>     P.S.: Also, I'm tired of hearing about the pythonic way... Where
> do I find a definitive description about the pythonic way? 

There is no such thing as a definitive description of pythonic -- it is 
like art, and pornography: you can recognise it when you see it (except 
when you can't).

However, you can get close by doing:

import this

in the Python interactive interpreter. Or from a shell prompt:

python -m this


> I think that
> this word is used only when someone sees something that he doesn't like,
> he doesn't know what he doesn't like at it, and just goes to say its
> un-pythonic, without saying what would be... Wouldn't be just easier to
> say "I don't know" or "I doesn't feel right to me"?

I think that there's a risk that people over-use unpythonic when they 
mean "I don't like it", but that doesn't mean that pythonic isn't a 
meaningful concept. However, it is a matter of degree, not kind: like 
mole-hills and mountains, unpythonic and pythonic are very different 
things, but there's no precise dividing line between them.


-- 
Steven



More information about the Python-list mailing list