I'm not asking about the difference between == and is operators! I am asking about interning or something..!
In Python 3.9.1,
>>> str(1) is '1'
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> '1' is '1'
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True
I found out that characters which match [a-zA-Z0-9_] are interned in Python. I understand why '1' is '1'. Python stores a character '1' somewhere in the memory internally and refers to it whenever '1' is called. And str(1) returns '1', and I think, it should refers to the same address as other literal '1's. Shouldn't str(1) is '1' also be True?
ischecks for references, not content. Also,str(1)is not a literal therefore it is not interned.But
'1'is interned because it's directly a string. Whereasstr(1)goes through a process to become a string. As you can see:So the way to make them both interned is with
sys.intern:As mentioned in the docs:
Note that in Python 2
intern()was a built-in keyword, but now in python 3 it was merged into thesysmodule to becomesys.intern