Equivalent code to the bool() built-in function

Chris Rebert clp2 at rebertia.com
Sat Apr 16 16:58:37 EDT 2011


On Sat, Apr 16, 2011 at 1:24 PM, candide <candide at free.invalid> wrote:
> Consider the following code :
>
> # --------------------------------------
> def bool_equivalent(x):
>    return True if x else False
>
>
> # testing ...
>
> def foo(x):
>    return 10*x
>
> class C:
>    pass
>
> for x in [42, ("my","baby"), "baobab", max, foo, C] + [None, 0, "", [],
> {},()]:
>    print bool(x)==bool_equivalent(x)
> # --------------------------------------
>
>
> Is the bool_equivalent() function really equivalent to the bool() built-in
> function ?

The ternary operator, if-statement, and `while` all do the equivalent
of an implicit bool() on their condition, so bool_equivalent() will
always give the same result as bool() because it's indeed using the
moral equivalent of bool() behind the scenes.
That is, `True if x else False` conceptually gets compiled down to
`True if bool(x) == 1 else False` (but without doing a run-time lookup
of "bool").

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list