Equivalent code to the bool() built-in function

Dave Angel davea at ieee.org
Sun Apr 17 21:46:37 EDT 2011


On 01/-10/-28163 02:59 PM, Daniel Kluev wrote:
> On Sun, Apr 17, 2011 at 8:38 AM, Ben Finney<ben+python at benfinney.id.au>  wrote:
>> It won't look up the *name* ‘bool’, but it will use that object. Any
>> boolean expression is going to be calling the built-in ‘bool’ type
>> constructor.
>>
>> So the answer to the OP's question is no: the function isn't equivalent
>> to the type, because the OP's ‘bool_equivalent’ function necessarily
>> uses the built-in ‘bool’ type, while the reverse is not true.
>
> Actually, as I was curious myself, I've checked sources and found that
> `True if x else False` will _not_ call bool(), it calls
> PyObject_IsTrue() pretty much directly.

You miss Ben's point, and got it backwards.

He didn't say that the function will call the bool() type (constructor), 
but that it will use the bool type;  in other words, it will return True 
or False.  The one that may not is the function bool().

 >>> print bool("143")
True
 >>> bool = int
 >>> print bool("143")
143

Once bool has been reassigned, calling it may not return True or False 
any more.

DaveA




More information about the Python-list mailing list