[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

how to let argument be optional falling back to certain integer

David Raymond <David.Raymond at> writes:

>> This is true.  I have written 0 as false in C so many times.  But
>> clearly for me times have changed...  I now look at numbers as a thing
>> in their own special class not to be confused as truth-values.  (So much
>> so that I fell for this.)  But I confess I still think of numbers as all
>> TRUE.  (Even zero!)
> Also remember that in Python bool is a subclass of int:
>>>> isinstance(False, int)
> True
>>>> 0 == False
> True
>>>> 1 == True
> True
>>>> ["A", "B"][False]
> 'A'
>>>> ["A", "B"][True]
> 'B'
> So if you're trying to do something slightly different based on the
> type of the input you might fall into this trap
> if isinstance(foo, float):
>     do float stuff
> elif isinstance(foo, int):
>     do int stuff
> elif isinstance(foo, bool):
>     this line will never run because it would have triggered the int line

In my case I was only interested in ints, so I actually did try
isinstance(k, int) and it seemed to work because I didn't try 

  k = False 

I settled for the explicit check done by Chris Angelico.