For a full explanation consider the following example:
>>> import dis
>>> def is_truthy(x):
>>> return "Those sweed words!" if x else "All lies!"
>>> is_truthy(None)
'All lies!'
>>> is_truthy(1)
'Those sweed words!'
>>> is_truthy([])
'All lies!'
>>> is_truthy(object())
'Those sweed words!'
What's happening in is_truthy() ? Let's find out. Running dis.dis(is_truthy) gives you:
2 0 LOAD_FAST 0 (x)
3 POP_JUMP_IF_FALSE 10
6 LOAD_CONST 1 ('The pure word')
9 RETURN_VALUE
>> 10 LOAD_CONST 2 ('All lies!')
13 RETURN_VALUE
As you can see x is pushed onto the stack, then POP_JUMP_IF_FALSE is executed. This will take the jump to first push and then return the right answer.
POP_JUMP_IF_FALSE is defined in ceval.c:
TARGET(POP_JUMP_IF_FALSE) {
PyObject *cond = POP();
int err;
if (cond == Py_True) {
Py_DECREF(cond);
FAST_DISPATCH();
}
if (cond == Py_False) {
Py_DECREF(cond);
JUMPTO(oparg);
FAST_DISPATCH();
}
err = PyObject_IsTrue(cond);
Py_DECREF(cond);
if (err > 0)
err = 0;
else if (err == 0)
JUMPTO(oparg);
else
goto error;
DISPATCH();
As you can see, if the object consumed by POP_JUMP_IF_FALSE is already either True or False, the answer is simple. Otherwise the interpreter tries to find out if the object is truthy by calling PyObject_IsTrue() which is defined in the object protocol. The code in object.c shows you exactly how it works:
PyObject_IsTrue(PyObject *v)
{
Py_ssize_t res;
if (v == Py_True)
return 1;
if (v == Py_False)
return 0;
if (v == Py_None)
return 0;
else if (v->ob_type->tp_as_number != NULL &&
v->ob_type->tp_as_number->nb_bool != NULL)
res = (*v->ob_type->tp_as_number->nb_bool)(v);
else if (v->ob_type->tp_as_mapping != NULL &&
v->ob_type->tp_as_mapping->mp_length != NULL)
res = (*v->ob_type->tp_as_mapping->mp_length)(v);
else if (v->ob_type->tp_as_sequence != NULL &&
v->ob_type->tp_as_sequence->sq_length != NULL)
res = (*v->ob_type->tp_as_sequence->sq_length)(v);
else
return 1;
/* if it is negative, it should be either -1 or -2 */
return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
}
Again, if the object is just True or False themselves, the answer is simple. None is also considered false. Then various protocols like the number protocol, the mapping protocol and the sequence protocol are checked. Otherwise the object is considered true.
To wrap it up: x is considered true if it is True, true according to the number, mapping or sequence protocol or some other kind of object. If you want your object to evaluate to false, you can do so by implementing any of said protocols, see the provided links.
Comparing to None like in if x is None is an explicit comparison. The logic above does not apply.
if <elem>:is equivalent toif <elem>.has_children():that is quite different fromif <elem> is not None:. - jfs