On 3/21/2020 2:09 PM, 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
I've never seen anyone relying on this behaviour, and I don't expect
these new methods will change that. Thinking that `is` is another way of
writing `==`, yes, I see that frequently. But relying on object identity
to see whether a new string was created by a method, no.
Agreed. I think the PEP should just write the Python pseudo-code without
copying, and it should mention that whether or not the original string
is returned is an implementation detail. Then I think the actual
documentation should just omit any discussion of it, like the existing
docs for lstrip().
If you want to know whether a prefix/suffix was removed, there's a more
reliable way than identity and a cheaper way than O(N) equality. Just
compare the length of the string before and after. If the lengths are
the same, nothing was removed.
That's a good point. This should probably go in the PEP, and maybe the
documentation.
Eric
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/python-dev@python.org/message/SOLOVVZXIGEAFZKX223YEAWLP6G5TSB7/
Code of Conduct: http://python.org/psf/codeofconduct/