On Tue, Mar 31, 2020 at 4:20 AM Joao S. O. Bueno <[email protected]> wrote:
>
> Hi Andrew -
>
> I made my previous post before reading your first answer.
>
> So, anyway, what we have is that for a "mutable string like object" one
> is free to build his wrapper - StringIO based or not - put it on pypi, and
> remember
> calling `str()` on it before having it leave your code.
>
> Thank you for the lengthy reply anyway.
>
> That said, anyone could tell about small, efficient,
> well maintained "mutable string" classes on Pypi?
>
There's a vast difference between "mutable string" and "string
builder". The OP was talking about this kind of thing:
buf = ""
for i in range(50000):
buf += "foo"
print(buf)
And then suggested using a StringIO for that purpose. But if you're
going to change your API, just use a list:
buf = []
for i in range(50000):
buf.append("foo")
buf = "".join(buf)
print(buf)
So if you really want a drop-in replacement, don't build it around
StringIO, build it around list.
class StringBuilder:
def __init__(self): self.data = []
def __iadd__(self, s): self.data.append(s)
def __str__(self): return "".join(self.data)
This is going to outperform anything based on StringIO fairly easily,
plus it's way WAY simpler.
But this is *not* a mutable string. It's a string builder. If you want
a mutable string, first figure out exactly what mutations you need,
and what performance you are willing to accept.
ChrisA
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/X5OQOV3FKEXVVXRHHWTMNQY5OLYSOFKA/
Code of Conduct: http://python.org/psf/codeofconduct/