4 ms·
Nitpick: this isn't an implicit conversion. There's a lot of history of languages without a real boolean type using integer 0 and 1 as the sentinel values indi
by ubernostrum 11y ago
Nitpick: this isn't an implicit conversion.
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.
- cma 11y agoInteresting, so technically isn't weak typing, but in practice to me it is a distinction without a difference. You could make int a subtype of string, and allow things like "1" + 1 == "11" and end up with many of the same problems of weakly typed languages.
- ubernostrum 11y agoWell, there's also ancient-history stuff going on here in that Python originally didn't have a boolean type, which mean using integer 0 and 1 was the standard practice. "True" and "False" as aliases for integer 1 and 0 were added in 2002, and the actual boolean type -- implemented as a subclass of int since that got automatic compatibility with existing code using integer values -- was added in 2003.
- Veedrac 11y agoWell, that would violate the Liskov Substitution Principle. But I think there's a fundamental divide about what weak typing actually is. For example, it's entirely possible in Rust to have implemented Add for i32 and String. Even this isn't weak typing in its traditional form. AFAIK, in this sense weak typing refers to whenever the compiler will implicitly cast one type to another in order to satisfy a type constraint. C's number types do this. PHP does this on everything. Javascript has, eg., [] + [] == "". Python does not do this - all type casts are explicit in the implementation of the operator or function (which is implemented on the type, not globally). It's reasonable to argue that the use of the phrase "weak typing" to mean "things I don't like about a type-system" is not only well established but maybe even more useful. It does, however, irritate Python programmers who don't want their language lumped in with PHP.