FixedPoint

Steve Holden sholden at holdenweb.com
Thu Feb 7 16:44:48 CET 2002


"Mark McEahern" <mark at mceahern.com> wrote ...
> In the FixedPoint module found here:
>
>
>
ftp://ftp.python.org/pub/python/contrib-09-Dec-1999/DataStructures/FixedPoin
> t.py.Z
>
> there seems to be a bug comparing to None like this:
>
>   if f == None:
>
> Demo:
>
>     $ python
>     Python 2.2 (#1, Dec 31 2001, 15:21:18)
>     [GCC 2.95.3-5 (cygwin special)] on cygwin
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> import FixedPoint
>     >>> f = FixedPoint.FixedPoint(1.0)
>     >>> if f == None:
>     ...     print "that's not true!"
>     ...
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>       File "FixedPoint.py", line 272, in __cmp__
>         xn, yn, p = _norm(self, other)
>       File "FixedPoint.py", line 415, in _norm
>         y = FixedPoint(y, x.p)
>       File "FixedPoint.py", line 216, in __init__
>         raise TypeError("can't convert to FixedPoint: " + `value`)
>     TypeError: can't convert to FixedPoint: None
>
> This doesn't happen if you use either of the following:
>
> if f is None:
> ...
>
> if not f:
> ...
>
> I ran into this because PyPgSql (v2.0) uses the first method:
>
>     File "/usr/lib/python2.2/site-packages/pyPgSQL/PgSQL.py", line 1434,
in
>   _quote
>
>       if value == None:
>
> I'm not sure what the best fix is here but one that works is to modify the
> __cmp__ method for FixedPoint to anticipate comparison to None.  Here's
the
> current __cmp__:
>
>     def __cmp__(self, other):
>         xn, yn, p = _norm(self, other)
>         return cmp(xn, yn)
>
> The fix would look like this:
>
>     def __cmp__(self, other):
>         ## To avoid crashing on if x == None and the like:
>         if other is None:
>             return 1
>         xn, yn, p = _norm(self, other)
>         return cmp(xn, yn)
>
> Or perhaps it'd be better to muck with __eq__ and __ne__?  Well, anyway,
> that mod to __cmp__ works.
>
> Cheers,
>
Mark:

Since the *intent* for None is that there should only ever be one object of
type None, the better test would be

    if something is None

which can easily be used without requiring any changes to FixedPoint.

Good general rule: if Tim made it that way, it's supposed to be that way :-)

regards
 Steve
--
Consulting, training, speaking: http://www.holdenweb.com/
Author, Python Web Programming: http://pydish.holdenweb.com/pwp/

"This is Python.  We don't care much about theory, except where it
intersects with useful practice."  Aahz Maruch on c.l.py







More information about the Python-list mailing list