PEP 285: Adding a bool type
Martin v. Loewis
martin at v.loewis.de
Sun Mar 31 05:25:13 EST 2002
philh at comuno.freeserve.co.uk (phil hunt) writes:
> On Sat, 30 Mar 2002 08:38:00 -0500, Guido van Rossum <guido at python.org> wrote:
> >Tim must be missing something. The obvious way to turn a bool b into
> >an int is int(b).
>
> Will this work on old versions of python? I've just checked that it
> works on 2.0, but what about 1.5.1 or 1.6?
>
> I'd guess (b*1) would work on everything, however.
The way Guido meant this is really "turn a *bool* into an int". There
are no bools in 2.0, so I wonder what you've checked. If you want to
change an arbitrary object into 0/1, int() certainly won't work:
>>> int([])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object can't be converted to int
To turn an arbitrary object into a bool, you could have used
operator.truth so far, since Python 1.4. To turn that into 0/1 pair,
you could write int(operator.truth(obj)). This will also work back to
Python 1.4, since truth already returns 0/1; passing that to int() was
always allowed.
Regards,
Martin
More information about the Python-list
mailing list