3 ms·
In [7]: a = "foo" In [8]: b = "foo" In [9]: a is b Out[9]: True In [10]: b = "foobaljlajdfsklfjds l;kjsl;dfj ls;dfj l;skdj flsdjluejsklnm "
by jedberg 9y ago
In [7]: a = "foo"
In [8]: b = "foo"
In [9]: a is b
Out[9]: True
In [10]: b = "foobaljlajdfsklfjds l;kjsl;dfj ls;dfj l;skdj flsdjluejsklnm "
In [11]: a = "foobaljlajdfsklfjds l;kjsl;dfj ls;dfj l;skdj flsdjluejsklnm "
In [12]: a is b
Out[12]: False
Seems to work with small and big strings too.
- nneonneo 9y agoThis would be due to string interning, which automatically caches small strings, which are very common because attribute names are just strings.
- Dylan16807 9y agoTo be clear the question of which strings to intern is up to an implementation of string interning. Only small strings, all strings, or even only large strings are all options that are good for different reasons.
- winstonewert 9y agoRelevant code here: https://hg.python.org/cpython/file/f254ceec0d45/Objects/codeobject.c#l72 https://hg.python.org/cpython/file/f254ceec0d45/Objects/code... Its not actually length, its whether the string looks like it could be a python name, and it only happens for string literals.
- cpsempek 9y agoThis comment is great, points out why the article is bad. Python integers are not weird simply because a well-defined operator gives a result which goes against an intuition based on the semantics of English.