There is some code:

import copy a = 'spamlkfna;inoianoiho' b = copy.copy(a) if a is b: print("yes") 

In the book that I am reading, I found out that 2 variables are being created here that will refer to different objects, but the string if a is b returns True. I can not understand why this happens if is returns true only if the 2 links are equal, that is, they refer to the same object. Is it all optimization tricks? Or in the version after python 3.0 this moment looks different? My version on which I work 3.7.1

  • 2
    Yes, optimization. If the object is immutable, then in fact there is no point in making a real copy - andreymal
  • one
    Actually, the _copy_dispatch dictionary is filled in here in copy.py , where for all immutable objects embedded a copy function is written , which stupidly returns the same object and everything - Andreymal
  • b = a [::] using the same record, the result does not change at all - Sergey Patilevy
  • one
    I don’t know how to check this anymore, but it’s probably also an optimization - it’s obvious that no changes are made - andreymal
  • one
    b = a[:] is a short and beautiful analogue of copy.copy(a) , based on the fact that the slice returns a shallow copy of the data. For a string, it also returns a reference to the interned instance, but for a list of characters it will work. - Sergey Gornostaev

1 answer 1

CPython is interning strings , so you can't make a copy of it. But it should be borne in mind that this is an internal implementation feature and sometime this behavior may change.