-
-
Notifications
You must be signed in to change notification settings - Fork 29.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
csv.writer.writerow() does not accept generator (must be coerced to list) #67360
Comments
The csv.writer.writerow() does not accept a generator as input. I find this counter-intuitive and against the spirit of similar APIs. If the generator is coerced to a list, everything works as expected. See the following test script which fails on the line "w.writerow(g)". In my opinion, this line should work identically to the line "w.writerow(list(g))". --- import csv
f = open('foo.csv', 'w')
w = csv.writer(f)
g = (i for i in ['a', 'b', 'c'])
w.writerow(list(g))
g = (i for i in ['a', 'b', 'c'])
w.writerow(g) |
This seems like a sensible enhancement request to me. It is possible it could even be considered a bug, the docs aren't exactly clear on what 'row' is expected to be. |
I have created an initial patch such that writerow() now allows generators. I have also added a unit test to demonstrate the fix. The code now coerces iterators (and generators) to a list, then operates on the result. I would have preferred to simply iterate over the argument, however, there is a special case where the length of the argument is exactly 1. So coercing to a list makes checking the length simpler. All feedback welcome. |
Hmm. That could be an issue. If someone passes a generator they will generally expect it to be consumed as a generator, not turned into a list implicitly. So it may be better to turn this into a doc bug and require the explicit "list" call :(. |
The docs mention that "row" should be a sequence, so there is no a bug. Here is a patch which makes writerow() accept an iterable without converting it to a list. It also adds tests for few corner cases and fixes the docs. |
Left a question about handling of the unquoted empty field exception on Rietveld. |
New changeset cf5b62036445 by Serhiy Storchaka in branch 'default': |
Looks like Serhiy forgot to close this, so closing it. |
No, I just had a stale tab :( :( |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: