[Python-Dev] Re: PEP 616 -- String methods to remove prefixes and suffixes

2020年3月21日 11:12:08 -0700

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.
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.
-- 
Steven
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/ATVEUSROY3BSUK5BDPPS5A75TRCRR4TD/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to