bool() or similar

Steve Holden sholden at holdenweb.com
Tue Nov 13 15:24:01 EST 2001


"Andrew Dalke" <dalke at dalkescientific.com> wrote ...
>
> Oliver Fromme:
> >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-
> >wise.
>
> >>> for x in (0, 1, 2, (), (1,), ((),), [], ["Q"], "hello", ""):
> ...     print repr(x), operator.truth(x)
> ...
> 0 0
> 1 1
> 2 1
> () 0
> (1,) 1
> ((),) 1
> [] 0
> ['Q'] 1
> 'hello' 1
> '' 0
> >>>

Oliver:

AS a beginner you *might* not spot the need to import the "operator" module
to use this code. But I think "not not x" is a very commendable attempt,
guaranteed to return the same as operator.truth().

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list