by aapycgarb · 11y ago · 0 comments
I've definitely been bitten by this before, accidentally passing in a book parameter instead of an int, and having some math work initially and then blow up months later.
Knuth argues against this kind of implicit bool to integer conversion in Concrete Mathematics.
There's a lot of history of languages without a real boolean type using integer 0 and 1 as the sentinel values indicating false-ness and true-ness.
And Python, in a nod to that, implements bool as a subclass of int, of which only two instances can ever exist (with False having a value of 0 and True having a value of 1).
So this isn't weak typing -- isinstance(True, int) is True in Python, and operations like the ones you're mentioning work because of that, for the same reason any other subclass of int would work.
>>> isinstance(type, object)
true
>>> T = type('T', (), {})
>>> isinstance(T, type)
True
>>> isinstance(T, object)
True
>>> isinstance(T(), object)
True
>>> isinstance(int, object)
True
>>> issubclass(int, object)
True
>>> isinstance(1, object)
TrueFirst off, see my other comment about Python's boolean type and the fact that it is an integral type:
https://news.ycombinator.com/item?id=9595988
Second, boolean evaluation of arbitrary types in Python is not "weak" -- it's well-defined through a standard language-level protocol, and it's always very clear what can and can't be evaluated as a boolean and what boolean values will result from doing so.