[New-bugs-announce] [issue32547] csv.DictWriter emits strange errors if fieldnames is an iterator

Ben Cummings report at bugs.python.org
Sat Jan 13 19:41:44 EST 2018


New submission from Ben Cummings <ben at benandconner.com>:

If I pass an iterator to csv.DictWriter as the fieldname field, then DictWriter consumes that iterator pretty quickly, emitting strange errors such as the following when trying to write the headers.

>>> import csv
>>> fields = iter(["a", "b", "c", "d"])
>>> f = open('test.csv', 'w')
>>> writer = csv.DictWriter(f, fieldnames=fields)
>>> writer.writeheader()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/csv.py", line 142, in writeheader
    self.writerow(header)
  File "/usr/lib/python3.4/csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/usr/lib/python3.4/csv.py", line 149, in _dict_to_list
    + ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: 'c', 'a'

This is because writeheader and _dict_to_list repeatedly iterate over self.fieldnames. It seems like this could be solved by making a list of fieldnames in the constructor.

----------
components: Library (Lib)
messages: 309904
nosy: bendotc
priority: normal
severity: normal
status: open
title: csv.DictWriter emits strange errors if fieldnames is an iterator
versions: Python 3.4, Python 3.5, Python 3.6, Python 3.7, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32547>
_______________________________________


More information about the New-bugs-announce mailing list