jdunck/python-unicodecsv — pull request #33 by jdotjdot (2014-09-29 04:00:05+00:00)
Title: Returning values from .writerow()

In my Django project, I ran into the (admittedly niche) use case of needing to stream a large CSV file. Django offers [a tutorial](https://docs.djangoproject.com/en/dev/howto/outputting-csv/#streaming-large-csv-files) about how to do this, and it involves creating a fake buffer of sorts to return values from the `csv` writer rather than write to the actual buffer:

```python
class Echo(object):
"""An object that implements just the write method of the file-like
interface.
"""
def write(self, value):
"""Write the value by returning it, instead of storing in a buffer."""
return value

def some_streaming_csv_view(request):
"""A view that streams a large CSV file."""
# Generate a sequence of rows. The range is based on the maximum number of
# rows that can be handled by a single sheet in most spreadsheet
# applications.
rows = (["Row {0}".format(idx), str(idx)] for idx in range(65536))
pseudo_buffer = Echo()
writer = csv.writer(pseudo_buffer)
response = StreamingHttpResponse((writer.writerow(row) for row in rows),
content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
return response
```

I have non-ASCII characters in my data and needed to use the `unicodecsv` module and noticed that `unicodecsv`'s `writerow()` method did not `return` anything. Adding a `return` statement fixed my problem. Even if only to better match the native Python `csv` module, I think this should be added.

Note that `writerows()` still doesn't properly return anything, but it also does not in the native Python `csv` module, and so I've left it for consistency's sake.