by BiteCode_dev · 6y ago · 0 comments
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.
That complexifies the GC (already a complex beast) as it requires strong type-specific specialisation, more bookkeeping, and adds self-inflicted edge cases. Even the JVM folks didn't bother (though mayhaps they did not because they have more than one garbage collector).
For those situations, bytes() + memoryview() or bytearray() can be used, but then you are on your own.
And honestly, I would be rich if I got a dollar every time a student does this:
msg.upper()
Instead of: msg = msg.upper()
And then call me to say it doesn't work. >>> 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. >>> x = 257
>>> y = 257
>>> x is y
False
>>> def f():
... x = 257
... y = 257
... return x is y
...
>>> f()
True
The lesson being that `is` is essentially meaningless for immutable objects, and to always use `==`.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