4 ms·
the python documentation [1] says the following: > The current implementation keeps an array of integer objects for all integers between -5 and 256, when you c
by woodrowbarlow 9y ago
the python documentation [1] says the following:
> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
does anyone have any idea how they chose that range? it's a 262-wide block starting at -5, which seems incredibly arbitrary.
[1] https://docs.python.org/2/c-api/int.html https://docs.python.org/2/c-api/int.html
- masklinn 9y agoYou could probably find out from the code's log. I'd guess the small positive integers are common due to e.g. iteration or len() of small collections and the like, and the very small negatives are due to things like error values.
- llccbb 9y agoThe small negatives might also be for indexing from the end of lists. `my_list[-1]` is super common.
- masklinn 9y agoGood point.
- jwilk 9y agoI did some git archaeology. Here are relevant commits and bug reports: * Initial commit with -1...99 cached: https://github.com/python/cpython/commit/842d2ccdcd540399501a918b9724d2eaf5599f39 https://github.com/python/cpython/commit/842d2ccdcd540399501... * Cache more negative numbers, -5...99: https://github.com/python/cpython/commit/c91ed400e053dc9f11dd30c84e2bb611999dce50 https://github.com/python/cpython/commit/c91ed400e053dc9f11d... https://bugs.python.org/issue561244 https://bugs.python.org/issue561244 * Cache more positive numbers, -5...256: https://github.com/python/cpython/commit/418a1ef0895e826c65d4113be5d86891c199e15d https://github.com/python/cpython/commit/418a1ef0895e826c65d... https://bugs.python.org/issue1436243 https://bugs.python.org/issue1436243
- woodrowbarlow 9y agogood find! here's a summary: it looks like they searched the standard library for negative integer literals and that's how they settled on -5 for the low end. the high end came after introducing the `bytes` object. it went up to 256 instead of just 255 for size/len checks.