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

James Powell james at dontusethiscode.com
Fri Jan 3 01:39:07 CET 2014


On 01/02/2014 06:59 PM, Guido van Rossum wrote:
>> 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))
> Neither of these strikes me as bad. Also, depending on whether the set
> of prefixes itself changes dynamically, it may be best to lift the
> tuple() call out of the startswith() call.

I agree. The any() formulation proves good enough in practice.

Creating a tuple can be a bit tricky, since the list of prefixes could
be large and could change.

>> 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})
> And there could still be another ambiguity here: a metaclass could
> conceivably make its instances (i.e. classes) iterable.

It's an interesting point that there's fundamental ambiguity between
providing an iterable of arguments or providing a single argument that
is itself an iterable (e.g., in the case of a type that is itself
iterable, like Enum)

In fact, I've actually warmed up to the any() formulation, because it
makes explicit which behaviour you want.

>> I do agree that it's definitely important to retain the behaviour of:
>>     'spam'.startswith('sz')
> Duh. :-)

You never know...

> All in all I hope you will give up your push for this feature. It just
> doesn't seem all that important, and you really just move the
> inconsistency to a different place (special-casing strings instead of
> tuples).

For these functions and methods, being able to provide a tuple of
arguments instead of a single argument seems mostly a convenience. It
allows the most common case of wanting to internalise the iteration with
a minimum of ambiguity. The any() or tuple() formulation are available
where needed.

In the end, I'm happy to drop the push for this feature.

(In general, I agree that there isn't a need to stamp out all
inconsistencies or to belabour the use of abstract types.)

Cheers,
James Powell

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



More information about the Python-ideas mailing list