views:

178

answers:

2

I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc. I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject_RichCompare() with True as the second value, but that returns False for "1" == True for example. Is there a convenient function to do this, or do I have to test against a sequence of types and do special-case tests for each possible type? What does the internal implementation of if() do?

+5  A: 

Isn't this it, in object.h:

PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);

?

RichieHindle
Yes it is. Thanks for the answer! (I was grepping the headers for "bool" and "Bool" and "Compare" and "Test" and found nothing)I actually just found it too, by getting the source, grepping through the parser until I got JUMP_IF_TRUE, then looking through ceval.c until I got to JUMP_IF_TRUE and saw that it used PyObject_IsTrue. Maybe I'll just use the source code, rather than the documentation from here on out :-)
The source code is the definitive answer to most questions. 8-) And the Python source code is very easy to understand - it's surprisingly self-consistent and predictable for a codebase with many authors. When I read your question I thought "I bet the function's called IsTrue", and sure enough it was.
RichieHindle
+1  A: 

Use

int PyObject_IsTrue(PyObject *o)
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.

(from Python/C API Reference Manual)

rincewind