Search code examples
pythoncopy-on-write

Does Python use copy-on-write for copies of lists?


Suppose I copy an existing list:

existing_list = [ 1, 2, 3 ];
copied_list = existing_list[:]

...

copied_list[2] = 'a' // COW happens here

[Some edits]

I heard that Python uses copy-on-write when either copied_list or existing_list is mutated. Is this true?

Seems to me like an over-complication that requires locking all over the place (think multi-threading).

For clarity: I am not looking for a COW impl. I'm just trying to understand what's Python standard behavior.


Solution

  • There is no copy-on-write. When you run copied_list = existing_list[:], a new list is built and populated immediately. Here is the source: http://hg.python.org/cpython/file/2.7/Objects/listobject.c#l467