Hacker News new | past | comments | ask | show | jobs | submit login

> Interestingly, Python does the same thing as JS in this case, even though it is typically quite strongly typed. [...] > Python outputs 0, it doesn't complain like the other two.

yep, this is one of those Python weird bits. in Python, booleans are ints, True is 1 and 0 is False. and i don't mean it in a JS-ish way like "they can be converted to...". no, True is the integer value 1. in fact, the type bool is a subtype of int. if you think of types as sets of values, and subtypes as subsets of their parent set, that `book < int` relation suddenly makes a lot of sense ;)

  >>> +(not not [])
  0
  >>> (not not [])
  False
  >>> 0 == False
  True
  >>> 1 == True
  True
  >>> True + True
  2
  >>> True - False + True * 0.5
  1.5
  >>> isinstance(False, bool)
  True
  >>> isinstance(False, int)
  True
  >>> bool < int
  True
so, if you accept that the operation `not []` makes sense to be defined as True (because `bool([])` is False), and that it makes sense for False to be the integer 0, then `+(not not [])` being 0 is just a logical consequence of that :)

for the record, i do think it's weird for Python to define bools as ints, and to make all values define a boolean semantics via __bool__().




Python was created February 1991, but it didn't have a boolean type until 2002 per PEP 285 <https://www.python.org/dev/peps/pep-0285/>

The rationale for making bool a subset of integers is for ease of implementation and substitutability (which aids backwards compatibility)47, as explained here:

> In an ideal world, bool might be better implemented as a separate integer type that knows how to perform mixed-mode arithmetic. However, inheriting bool from int eases the implementation enormously (in part since all C code that calls PyInt_Check() will continue to work -- this returns true for subclasses of int). Also, I believe this is right in terms of substitutability: code that requires an int can be fed a bool and it will behave the same as 0 or 1.

I have some Python code where there are still a number of uses of 0 and 1 for false and true, because it was written before Python added a boolean type.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: