3 ms·
Some of these quirks are explained incorrectly. I find the real explanations interesting, so please allow me to provide them. > 999+1 is not 1000 The examples
by kgm 13y ago
Some of these quirks are explained incorrectly. I find the real explanations interesting, so please allow me to provide them.
> 999+1 is not 1000
The examples given in this section do not actually show what the poster thinks! Python's interning of small integers is not relevant. It only applies to integers in the range -5 through 256.
The real explanation for why "1000 is 1000" evaluates to True has to do with the Python compiler. By evaluating this expression as a single statement in the interactive interpreter, the compiler notices that the constant value 1000 is repeated more than once. Therefore, it is able to re-use the same object.
But if you provide the value in more than one statement, the compiler is unable to do this:
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
Note that this behavior exists because each statement in the interactive interpreter is compiled separately. If you place the code within a function instead, the entire function is compiled at once, and the object is reused once more:
>>> def f():
... a = 257
... b = 257
... return a is b
...
>>> f()
True
> Ellipsis?
Apparently Ellipsis is always “bigger” than anything, as opposite to None, which is always “smaller” than anything.
Not so. Ellipsis follows Python 2's default rules for the comparison of unrelated types.
>>> Ellipsis < ()
True
The default is documented as comparing objects "consistently but arbitrarily"[1]. The actual rules are:
1) None is the smallest object.
2) Followed by numbers.
3) Followed by all other objects. Objects of distinct types are compared by the lexical ordering of their type names.
This can easily lead to senseless orderings, when two types define an ordered relationship between themselves, but another type happens to have a name that is lexically between them, as with str, tuple, and unicode:
>>> "def" < (1,)
True
>>> (1,) < u"abc"
True
>>> u"abc" < "def"
True
The Ellipsis constant is an instance of a type named "ellipsis", and so it is smaller than instances of most of the other non-numeric builtin types, except for dict.
The actual use of Ellipsis has nothing to do with recursive containers printing an ellipsis in their repr. It's part of a wacky special syntax that exists for NumPy's benefit:
>>> d = {}
>>> d[...] = None
>>> d
{Ellipsis: None}
[1] http://docs.python.org/2/reference/expressions.html#not-in http://docs.python.org/2/reference/expressions.html#not-in
- agf 13y agohttp://stackoverflow.com/questions/7969552/why-does-4-3-return-true-in-python-2 http://stackoverflow.com/questions/7969552/why-does-4-3-retu...