[Python-Dev] Slice as a copy... by design? (original) (raw)

Christian Heimes lists at cheimes.de
Thu May 22 19:16:14 CEST 2008


Facundo Batista schrieb:

Hi!

A thread in PyAr raised the question that, considering that strings are immutable, why a slice of a string is a copy and not a reference to a part of that string.

Because the reference approach is more complicated, harder to implement and may lead to unexpected behavior.

For example:

a = "a long string with 500,000 chars ..." b = a[0] del a

With the slice-as-copy design the string 'a' is immediately freed. The slice-as-reference design would keep the 500kB string in memory although you are only interested in the first character.

The buffer interface was designed for the slice-as-copy use case:

a = "abcdefg" b = buffer(a, 2, 3) b <read-only buffer for 0x839c2e0, size 3, offset 2 at 0x8391c40> str(b) 'cde' sys.getrefcount(a) 3 del b sys.getrefcount(a) 2

Christian



More information about the Python-Dev mailing list