Equivalent code to the bool() built-in function
Daniel Kluev
dan.kluev at gmail.com
Sun Apr 17 19:45:16 EDT 2011
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.
>>> import dis
>>> def bool2(x):
... return True if x else False
...
>>> dis.dis(bool2)
2 0 LOAD_FAST 0 (x)
3 POP_JUMP_IF_FALSE 10
6 LOAD_GLOBAL 0 (True)
9 RETURN_VALUE
>> 10 LOAD_GLOBAL 1 (False)
13 RETURN_VALUE
case POP_JUMP_IF_FALSE:
w = POP();
if (w == Py_True) {
Py_DECREF(w);
goto fast_next_opcode;
}
if (w == Py_False) {
Py_DECREF(w);
JUMPTO(oparg);
goto fast_next_opcode;
}
err = PyObject_IsTrue(w);
Py_DECREF(w);
if (err > 0)
err = 0;
else if (err == 0)
JUMPTO(oparg);
else
break;
continue;
So technically these implementations are equivalent besides the fact
that bool() is type rather than function.
--
With best regards,
Daniel Kluev
More information about the Python-list
mailing list