PEP 308: A PEP Writer's Experience - PRO

Samuele Pedroni pedronis at bluewin.ch
Sat Feb 8 17:40:25 EST 2003


"Fredrik Lundh" <fredrik at pythonware.com> ha scritto nel messaggio
news:mailman.1044741027.23208.python-list at python.org...
> Paul Rubin wrote:
>
> > I think Andrew Koenig pointed out a third argument which many of us
> > had perhaps underestimated: it can prevent bugs.  A lot of the
> > workarounds attempted for its absence are flat out wrong.  He gives an
> > example showing finding the maximum of x and y with
> >
> >    x > y and x or y
> >
> > which looks reasonable and might even pass the initial unit tests of a
> > real program, but gives the wrong answer (zero) if x is 0 and y is
> > negative.  A conditional expression like
> >
> >    x if (x > y) else y
> >
> > is much harder to get wrong.
>
> in Python, that's spelled:
>
>     max(x, y)
>

I thought the same, but it is false:

>>> class C:
...  def __init__(self,id,v):
...   self.id = id
...   self.v = v
...  def __cmp__(self,o):
...    return cmp(self.v,o.v)
...
>>> c1=C(1,'a')
>>> c2=C(2,'a')
>>> c1 == c2
1
>>> max(c1,c2).id
1
>>> (c1 > c2 and c1 or c2).id
2

<.5 wink>








More information about the Python-list mailing list