4 ms·
So why is this happening? The blog post also shows it, but doesn't explain why (first example)
by audiometry 9y ago
So why is this happening? The blog post also shows it, but doesn't explain why (first example)
- squeaky-clean 9y agostd_throwaway got the reasoning right in higher comment. You're actually doing a comparison if the object references are identical, not if the values are identical. The tricky bit is that everything is an object in Python, even "primitives" like integers, which can be surprising coming from some other languages. Then the trickier bit is that CPython (the most popular and standard implementation) on startup creates an object for every int from -5 to 256 and will re-use those instead of creating a new PyLongObject. This means that `256 is 256` works, because under the hood, it's short-circuting it to the same object. But `257 is 257` creates 2 different PyLongObjects, which have the same value, 257, but aren't technically the same object. And in my above example, the reason `x = 257; x is 257` is True when on the same line, but False when on separate lines (in the REPL) is because of the reasons kmill says, the constants pool that the interpreter creates. If they're interpreted together, it will create and use the same constant. Here is my entry on my company's blog about this. I won't guarantee you it's well written, but it does show bytecode and has links to the relevant C source lines at the very end. https://www.everymundo.com/literals-other-number-oddities-python/ https://www.everymundo.com/literals-other-number-oddities-py...
- audiometry 9y agothanks. that makes good sense.