-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Interned/cached integer in a function #258
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Thanks @frenzymadness Both the examples you shared (this one and #257) are very interesting. I'll add them in the next revision (unless someone else wants to raise a PR :) |
You can do it more easily:
The key point here is to take a large enough number that it won't be cached by Python.
|
@david-shiko I'm not sure I understand your point. What you described is already here and the interned numbers are from -5 to 256 for CPython. My example here is about the default value for kw argument. It shows that even a number much higher than 256 mentioned above can be cached in some cases. |
It seems that the Python interpreter uses cached numeric literals on a per-compile basis. >>> def a(b=3000):
... c = 3000
... print(id(b), id(c), b is c)
...
>>> a()
140032012726032 140032012726032 True
>>> a(3000)
140032012726192 140032012726032 False
>>> b = 3000
>>> c = 3000
>>> print(id(b), id(c), b is c)
140032012726192 140032012726160 False If you make it into a script file and run it, the whole thing will compile and everything will be True. def a(b=3000):
c = 3000
print(id(b), id(c), b is c)
a()
a(3000)
b = 3000
c = 3000
print(id(b), id(c), b is c)
|
Code example:
From this article: https://utcc.utoronto.ca/~cks/space/blog/python/PythonIsWithLiteral
The text was updated successfully, but these errors were encountered: