How to determine the bool between the strings and ints?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 8 13:23:09 EDT 2007


On Sat, 08 Sep 2007 12:08:16 -0300, Ricardo Aráoz wrote:


>>  if type(x) == type(True):
>> ...    print "bool"
>> ...
>> bool
>> 
>> 
> Or just :
> 
>>>> a = True
>>>> type(a) == int
> False

[snip]

You know, one or two examples was probably plenty. The other six or seven 
didn't add anything to your post except length.

Also, type testing by equality is generally not a good idea. For example:

class HexInt(int):
    """Like built-in ints, but print in hex by default."""
    def __str__(self):
        return hex(self)
    __repr__ = __str__

You should be able to use a HexInt anywhere you can use an int. But not 
if your code includes something like this:

if type(value) == int:
    do_something()
else:
    print "Not an int!"

(What do you mean my HexInt is not an int? Of course it is.)

Better is to use isinstance(value, int). Better still is to do duck-
typing, and avoid type() and isinstance() as much as possible.



-- 
Steven.



More information about the Python-list mailing list