by OJFord · 6y ago · 0 comments
> > I think name choice is easier if you write the documentation first:
> > cutprefix - Removes the specified prefix.
> > trimprefix - Removes the specified prefix.
> > stripprefix - Removes the specified prefix.
> > removeprefix - Removes the specified prefix. Duh. :)
I actually don't agree that it's so obvious, since it returns the prefix-removed string rather than modifying in-place. I think Fahlgren's argument would work better for `withoutprefix`.
So there is no possible confusion.
Yes. And doing otherwise is pretty risky as the Java folks discovered, ultimately deciding to revert the optimisation of substring sharing storage rather than copying its data.
The issue is that while data-sharing substringing is essentially free, it also keeps the original string alive, so if you slurp in megabytes, slice out a few bytes you keep around and "throw away" the original string, that one is still kept alive by the substringing you perform, and you basically have a hard to diagnose memory leak due to completely implicit behaviour.
Languages which perform this sharing explicitly — and especially statically (e.g. Rust) — don't have this issue, but it's a risky move when you only have one string type.
Incidentally, Python provides for opting into that behaviour for bytes using memory views.
You can get around that with a smarter garbage collector, though. On every mark-sweep pass (which you need for cycle detection even if you use refcounts for primary cleanup), add up the number of bytes of distinct string objects using the buffer. If it's less than the size of the buffer, you can save memory by transparently mutating each substring to use it's own buffer. If it's not, then you actually are saving memory by sharing storage, so you should probably keep doing that.
For those situations, bytes() + memoryview() or bytearray() can be used, but then you are on your own.
>>> a = [254, 255, 256, 257, 258]
>>> b = [254, 255, 256, 257, 258]
>>> for i in range(5): print(a[i] is b[i])
...
True
True
True
False
False
In Python, integers in the range [-5, 256] are statically constructed in the interpreter and refer to fixed instances of objects. All other integers are created dynamically and refer to a new object each time they are created.It always creates a new object but it doesn't necessarily copy the contents (even shallowly).
For instance slicing a `memoryview` creates a subview which shares storage with its parent.
Since you said "always", I'll be "that guy"...
For the builtin types, yeah. But not in general; user code can do whatever it wants:
class MyType:
def __getitem__(self, *args):
return self
my_obj = MyType()
my_other_obj = my_obj[3:7]
assert my_other_obj is my_obj