[Python-ideas] str.startswith taking any iterator instead of just tuple

James Powell james at dontusethiscode.com
Fri Jan 3 00:37:56 CET 2014


On 01/02/2014 06:24 PM, Guido van Rossum wrote:
> The current behavior is intentional, and the ambiguity of strings
> themselves being iterables is the main reason. Since startswith() is
> almost always called with a literal or tuple of literals anyway, I see
> little need to extend the semantics. (I notice that you don't actually
> give any examples where the iterator would be useful -- have you
> encountered any, or are you just arguing for consistency's sake?)

This is driven by a real-world example wherein a large number of
prefixes stored in a set, necessitating:

    any('spam'.startswith(c) for c in prefixes)
    # or
    'spam'.startswith(tuple(prefixes))

However, .startswith doesn't seem to be the only example of this, and
the other examples are free of the string/iterable ambiguity:

    isinstance(x, {int, float})

I do agree that it's definitely important to retain the behaviour of:

    'spam'.startswith('sz')

At same time, I think the non-string iterable problem is already fairly
well-known and not a source of great confusion. How often has one typed:

   isinstance(x, Iterable) and not isinstance(x, str)

Cheers,
James Powell

follow: @dontusethiscode + @nycpython
attend: nycpython.org + flask-nyc.org
read: seriously.dontusethiscode.com



More information about the Python-ideas mailing list