Steven D'Aprano wrote:
> Having confirmed that prefix is a tuple, you call tuple() to 
> make a copy of it in order to iterate over it. Why?
> 
> Having confirmed that option is a string, you call str() on
> it to (potentially) make a copy. Why?

This was an attempt to ensure no one can do funny business with tuple or str 
subclassing. I was trying to emulate the ``PyTuple_Check`` followed by 
``PyTuple_GET_SIZE`` and ``PyTuple_GET_ITEM`` that are done by the C 
implementation of ``str.startswith()`` to ensure that only the tuple/str 
methods are used, not arbitrary user subclass code. It seems that that's what 
most of the ``str`` methods force.

I was mistaken in how to do this with pure Python. I believe I actually wanted 
something like:

    def cutprefix(self, prefix, /):
        if not isinstance(self, str):
            raise TypeError()

        if isinstance(prefix, tuple):
            for option in tuple.__iter__(prefix):
                if not isinstance(option, str):
                    raise TypeError()

                if str.startswith(self, option):
                    return str.__getitem__(
                        self, slice(str.__len__(option), None))

            return str.__getitem__(self, slice(None, None))

        if not isinstance(prefix, str):
            raise TypeError()

        if str.startswith(self, prefix):
            return str.__getitem__(self, slice(str.__len__(prefix), None))
        else:
            return str.__getitem__(self, slice(None, None))

... which looks even uglier.

> We ought to get some real-life exposure to the simple case first, before 
> adding support for multiple prefixes/suffixes.

I could be (and have been) convinced either way about whether or not to 
generalize to tuples of strings. I thought Victor made a good point about 
compatibility with ``startswith()``
_______________________________________________
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/CQVVWGPC454LWATA2Y7BZ5OEAGVSTHEZ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to