Re: PgBoolean

Gerhard Häring <[email protected]>
Newsgroups gmane.comp.python.db.pypgsql.user
Organization OPUS GmbH
Message-ID <[email protected]>
You wrote:
> Can anyone tell me how to programatically check the value of a PgBoolean
> object? I am doing the following:
> 
> #####
> from pyPgSQL import PgSQL
> from pyPgSQL import libpq
> 
> db = PgSQL.connect("localhost::testdb")
> cursor = db.cursor()
> cursor.callproc("sp_TestBoolean", 1, 1)
> retval = cursor.fetchone()
> #####
> 
> When I print the value of retval, I get this:
> [<PgBoolean instance at 0x401c8900: Value: False>]
> 
> I would like to be able to do something like this:
> 
> if retval == true:
>    # do something
> else:
>    # do something else

It's not wise to test for truth values using == true. In Python, you test
wether something is nonzero, or zero.

These are examples of objects that are nonzero:

1, 2, 3, 4, 5, "foobar", [3,4,5], (3,4)

You can see this when you use them in an if-statement:

    >>> if "foobar": print "true"
    ...
    true

These are examples of objects whose truth value is "false":

0, 0.0, "", [], ()

Proof:

    >>> if not 0.0: print "false"
    ...
    false


Now, back to pyPgSQL :-) You simply test for the truth value of PgBooleans
using the if-statement:

    if retval:
       # do something
    else:
       # do something else


As far as "== true" is concerned, this does not exist in Python. *But*
there is are "True" and "False" constants in Python 2.2.2 (these are really
ints in 2.2.2). In Python 2.3 (still in development), we have a real
boolean type.

But please don't do things like:

    if foo == True:
        # ... 

just because that's possible with 2.2.2 and later. Such code hurts my eyes
;-) It's also more verbose than it needs to be. And error-prone, because it
requires that the class or type of foo support comparison to "True".
Checking for the nonzero-ness is much more rubost, and works with all
objects, as you've seen above (ints, longs, floats, strings, lists, etc.).

HTH,
-- 
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/




-------------------------------------------------------
This sf.net email is sponsored by: 
Battle your brains against the best in the Thawte Crypto 
Challenge. Be the first to crack the code - register now: 
http://www.gothawte.com/rd521.html
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.