
On Thu, Sep 02, 2021 at 04:54:45PM +0900, Stephen J. Turnbull wrote:
Steven D'Aprano writes:
On Thu, Sep 02, 2021 at 04:04:40PM +0900, Stephen J. Turnbull wrote:
You may not need to teach them about singletons, though.
It's hard to teach why `is` works with None,
For definitions of "works" that comes down to "agrees with Nick that 'is' is just a weird way to spell '==' most of the time". But that's not how I think of 'is'.
Ah, but that's because you're a Python programmer who has been seeped in the language for many, many years :-) To most people, "is" and "equals" are synonyms, as in: * one and one is two; * two times four is eight; * the discriminant of a general quadratic a x^2 + bx + c is b^2-4ac etc. And there are programming languages where `is` *is* an equality test, e.g. Hypertalk lets you say things like: if x + 1 is 2 then ... if the first word of the last line of text is "Goodbye" then ... So for somebody who is expecting "is" to be a synonym for `==`, how do you explain what it actually is? You need to talk about the Python execution model, how all values are objects, and that the reason that `x is None` always does the right thing but `x is []` doesn't is that None is a singleton, so that there is only one object that is None, but the empty list is not, there are many, many distinct empty lists. You might be able to avoid using the word "singleton", but it would be difficult, and even more difficult would be to avoid using the *concept* of a singleton. Otherwise, you leave open the possibility that there could be *two* None objects, and that there might be some unusual circumstances where the identity comparison will return False: Q: Will `None is None` always return true? A: Yes, None is identical to None. Q: How about `eval('None') is None`? A: Yes, `eval('None')` is None too. Q: What about `type(None)() is None`? A: Yes, that's also None. Q: How about `builtins.__dict__['None'] is None`? A: Yes, that is also None. Q: If I have ctypes return None, is that also identical to None? A: Yes it is. Q: What if I pickle None from one version of Python into another? A: Yes, that is still identical to None. Q: Suppose I use marshal instead of pickle? A: Yes, that is still identical to None. Q: But suppose I ... A: Look, there's only ever one None object, no matter where it comes from! Q: Oh, its a singleton, why didn't you say so? *wink* -- Steve