Skip to content
This repository has been archived by the owner on Dec 29, 2022. It is now read-only.

Strings are iterable, but not Iterable? #44

Closed
imjasonh opened this issue Nov 16, 2017 · 3 comments
Closed

Strings are iterable, but not Iterable? #44

imjasonh opened this issue Nov 16, 2017 · 3 comments

Comments

@imjasonh
Copy link

Docs for String says:

A String is an immutable sequence of bytes. Strings are iterable; iteration over a string yields each of its 1-byte substrings in order.

But String doesn't implement Iterable's Iterate method.

Is this intentional?

String could implement Iterable, in theory, by returning an iterator which passes each one-byte substring into Next.

@alandonovan
Copy link
Contributor

alandonovan commented Nov 16, 2017

The doc comment is out of date. The spec was changed relatively recently to makes strings not-iterable, because more often than not, iterating over a string is a mistake. (The usual symptom is that one means to iterate over the list ["foo"] but instead iterates over "foo", yielding the values "f", "o", "o". Because the elements of the iteration have the same type as the sequence as a whole, often the mistake goes unnoticed. The two staff at Google with single-letter userids receive a lot of unintended e-mail sent by errant Python programs.)

Instead of string being iterable, four methods were added to string that return iterable values. This approach also makes the intention more obvious as to whether you're iterating over string elements (bytes) or Unicode code points, and whether numeric values or substrings are desired.

@imjasonh
Copy link
Author

Great, I was hoping this wouldn't go down the path Python chose, and was nervous when I read the doc string. :)

@alandonovan
Copy link
Contributor

Re-opening as a documentation issue.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants