Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the [:] included in `.removeprefix()` definition?

In PEP-616, the specification for removeprefix() includes this code block:

def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

Why does the last line say return self[:], instead of just return self?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[:] is an old idiom for copying sequences. Nowadays, we use the idiomatic .copy for lists; there isn’t normally a good reason to copy strings, since they are supposed to be immutable, so the str class doesn’t provide such a method. Furthermore, due to string interning, [:] may well return the same instance anyway.

So, why include it in code like this?

Because str can be subclassed. The clue is in the subsequent text:

When the arguments are instances of str subclasses, the methods should behave as though those arguments were first coerced to base str objects, and the return value should always be a base str.

Suppose we had a user-defined subclass:

class MyString(str):
    ...

Notice what happens when we slice an instance to copy it:

>>> type(MyString('xyz')[:])
<class 'str'>

In the example implementation, therefore, the [:] ensures that an instance of the base str type will be returned, conforming to the text specification.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading