bool() or similar

Oliver Fromme olli at
Tue Nov 13 17:58:06 CET 2001


I'm still in the process of learning, but I think I have a
reasonable overview over the language, built-in functions
and libraries.

However, I wonder if there is a good way to convert some-
thing to a boolean value (0 or 1), given any type of object?
Such as a bool() function, which works in the same way as
int() or str().  I.e. it would return 0 when given either
0, "", an empty sequence or an empty mapping, and 1 other-

The closest thing I could come up with with was:

>>> def bool(x): return not not x
>>> def bool(x): return x and 1 or 0

But both of them don't seem to be particularly elegant or
clean.  Is there something I'm missing?

   Oliver Fromme

Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 München
Any opinions expressed in this message may be personal to the author
and may not necessarily reflect the opinions of secnetix in any way.

"All that we see or seem is just a dream within a dream" (E. A. Poe)

More information about the Python-list mailing list