Will
Will

Reputation: 75673

slices to immutable strings by reference and not copy

If you use string.split() on a Python string, it returns a list of strings. These substrings that have been split-out are copies of their part of the parent string.

Is it possible to instead get some cheaper slice object that holds only a reference, offset and length to the bits split out?

And is it possible to have some 'string view' to extract and treat these sub-strings as if they are strings yet without making a copy of their bytes?

(I ask as I have very large strings I want to slice and am running out of memory occasionally; removing the copies would be a cheap profile-guided win.)

Upvotes: 22

Views: 5802

Answers (3)

Sven Marnach
Sven Marnach

Reputation: 602355

String objects always point to a NUL-terminated buffer in Python, so substrings must be copied. As Ignacio pointed out, you can use buffer() to get a read-only view on the string memory. The buffer() built-in function has been superseded by the more versatile memoryview objects, though, which are available in Python 2.7 and 3.x (buffer() is gone in Python 3.x).

s = "abcd" * 50
view = memoryview(s)
subview = view[10:20]
print subview.tobytes()

This code prints

cdabcdabcd

As soon as you call tobytes(), a copy of the string will be created, but the same happens when slicing the old buffer objects as in Ignacio's answer.

Upvotes: 9

Will
Will

Reputation: 75673

Here's the quick string-like buffer wrapper I came up with; I was able to use this in place of classic strings without changing the code that expected to consume strings.

class StringView:
    def __init__(self,s,start=0,size=sys.maxint):
        self.s, self.start, self.stop = s, start, min(start+size,len(s))
        self.size = self.stop - self.start
        self._buf = buffer(s,start,self.size)
    def find(self,sub,start=0,stop=None):
        assert start >= 0, start
        assert (stop is None) or (stop <= self.size), stop
        ofs = self.s.find(sub,self.start+start,self.stop if (stop is None) else (self.start+stop))
        if ofs != -1: ofs -= self.start
        return ofs
    def split(self,sep=None,maxsplit=sys.maxint):
        assert maxsplit > 0, maxsplit
        ret = []
        if sep is None: #whitespace logic
            pos = [self.start,self.start] # start and stop
            def eat(whitespace=False):
                while (pos[1] < self.stop) and (whitespace == (ord(self.s[pos[1]])<=32)):
                    pos[1] += 1
            def eat_whitespace():
                eat(True)
                pos[0] = pos[1]
            eat_whitespace()
            while pos[1] < self.stop:
                eat()
                ret.append(self.__class__(self.s,pos[0],pos[1]-pos[0]))
                eat_whitespace()
                if len(ret) == maxsplit:
                    ret.append(self.__class__(self.s,pos[1]))
                    break
        else:
            start = stop = 0
            while len(ret) < maxsplit:
                stop = self.find(sep,start)
                if -1 == stop:
                    break
                ret.append(self.__class__(self.s,self.start+start,stop-start))
                start = stop + len(sep)
            ret.append(self.__class__(self.s,self.start+start,self.size-start))
        return ret
    def split_str(self,sep=None,maxsplit=sys.maxint):
        "if you really want strings and not views"
        return [str(sub) for sub in self.split(sep,maxsplit)]
    def __cmp__(self,s):
        if isinstance(s,self.__class__):
            return cmp(self._buf,s._buf)
        assert isinstance(s,str), type(s)
        return cmp(self._buf,s)
    def __len__(self):
        return self.size
    def __str__(self):
        return str(self._buf)
    def __repr__(self):
        return "'%s'"%self._buf

if __name__=="__main__":
    test_str = " this: is: a: te:st str:ing :"
    test = Envelope.StringView(test_str)
    print "find('is')"
    print "\t",test_str.find("is")
    print "\t",test.find("is")
    print "find('is',4):"
    print "\t",test_str.find("is",4)
    print "\t",test.find("is",4)
    print "find('is',4,7):"
    print "\t",test_str.find("is",4,7)
    print "\t",test.find("is",4,7)
    print "split():"
    print "\t",test_str.split()
    print "\t",test.split()
    print "split(None,2):"
    print "\t",test_str.split(None,2)
    print "\t",test.split(None,2)
    print "split(':'):"
    print "\t",test_str.split(":")
    print "\t",test.split(":")
    print "split('x'):"
    print "\t",test_str.split("x")
    print "\t",test.split("x")
    print "''.split('x'):"
    print "\t","".split("x")
    print "\t",Envelope.StringView("").split("x")

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799200

buffer will give you a read-only view on a string.

>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> b = buffer(s, 2, 10)
>>> b
<read-only buffer for 0x7f935ee75d70, size 10, offset 2 at 0x7f935ee5a8f0>
>>> b[:]
'cdefghijkl'

Upvotes: 24

Related Questions