Comparing variable types

David Eppstein eppstein at ics.uci.edu
Sun Oct 26 01:24:10 EST 2003


In article <mailman.102.1067136355.702.python-list at python.org>,
 Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote:

> On Sat, Oct 25, 2003 at 10:36:03PM -0400, Kill Bill wrote:
> > type(i) == "<type 'float'>"
> > this always returns false.  How come?
> > type(i)returns <type 'float'> if i is a float so why isn't == working?
> 
> Because "<type 'float'>" is a string :)
> 
> You want
>     import types
>     type(i) == types.FloatType
> 
> or
>     type(i) == type(1.0)
> 
> or in 2.2 and later you can simply do
>     type(i) == float

But it's almost always preferable to do
    isinstance(i,float)
because that allows subclasses of float to be used.  If you really have 
to test whether i is an unsubclassed float,
    type(i) is float
would be a better choice than
    type(i)==float
as it more accurately expresses the intent that only the precise float 
type will be allowed.

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list