
On 21 Mar 2020, at 19:09, Steven D'Aprano wrote:
On Sat, Mar 21, 2020 at 12:15:21PM -0400, Eric V. Smith wrote:
On 3/21/2020 11:20 AM, Ned Batchelder wrote:
Why be so prescriptive? The semantics of these functions should be about what the resulting string contains. Leave it to implementors to decide when it is OK to return self or not.
I agree with Ned -- whether the string object is returned unchanged or a copy is an implementation decision, not a language decision.
[Eric]
The only reason I can think of is to enable the test above: did a suffix/prefix removal take place? That seems like a useful thing.
We don't make this guarantee about string identity for any other string method, and CPython's behaviour varies from method to method:
py> s = 'a b c' py> s is s.strip() True py> s is s.lower() False
and version to version:
py> s is s.replace('a', 'a') # 2.7 False py> s is s.replace('a', 'a') # 3.5 True
And it is different for string subclasses, because the method always returns an instance of the baseclass:
class str2(str): ... pass ... isinstance(str2('a b c').strip(), str2) False isinstance(str2('a b c').strip(), str2) False
Servus, Walter