tMC
tMC

Reputation: 19335

Python string FIFO

Does Python have any data types for FIFO buffering of strings? I created something (below) but suspect I'm reinventing the wheel.

class Buffer(list):
    def __init__(self):
        super(Buffer, self).__init__()

    def put(self, nlmsg):
        for c in nlmsg: self.append(c)

    def peek(self, number):
        return "".join( [self[i] for i in range(number)] )

    def get(self, number):
        return "".join( [self.pop(0) for i in range(number)] )

Usage example:

>>> buf = Buffer()
>>> buf.put('abcdefg')
>>> buf
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> buf.peek(4)
'abcd'
>>> buf
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> buf.get(5)
'abcde'
>>> buf
['f', 'g']

I looked at Queue but when adding a str I would have to split each byte manually, else the entire str would become an item in the queue. Is there anything like this already out there?

Upvotes: 6

Views: 4698

Answers (3)

bilaljo
bilaljo

Reputation: 391

I know the post is old, but the deque object supports already "string-buffering" if you are using joining:

>>> from collections import deque
>>> string_buffer = dequeue()
>>> string_buffer.append("a")
>>> string_buffer.append("b")
>>> "".join(string_buffer)
ab

No need to write a new class.

Upvotes: 1

jcollado
jcollado

Reputation: 40394

Using collections.deque it would be implemented as follows:

from collections import deque

class Buffer(deque):
    def put(self, iterable):
        for i in iterable:
            self.append(i)

    def peek(self, how_many):
        return ''.join([self[i] for i in xrange(how_many)])

    def get(self, how_many):
        return ''.join([self.popleft() for _ in xrange(how_many)])



buf = Buffer()
buf.put('abcdefg')
print buf
print buf.peek(4)
print buf
print buf.get(5)
print buf

Example output:

deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
abcd
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
abcde
deque(['f', 'g'])

Upvotes: 3

Russell Borogove
Russell Borogove

Reputation: 19037

How about the string type itself?

>>> buf = ""
>>> buf += "abcdefg"
>>> buf
'abcdefg'
>>> list(buf)
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> buf[:4] # instead of peek
'abcd'
>>> got,buf = buf[:5],buf[5:] # instead of get
>>> got
'abcde'
>>> buf
'fg'

The idiom for get() is the only thing that's noticeably ugly here.

Upvotes: 0

Related Questions