-
-
Notifications
You must be signed in to change notification settings - Fork 30.3k
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.DictWriter emits strange errors if fieldnames is an iterator #76728
Comments
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. |
This isn't a bug. The docs specify that *fieldnames* is a sequence, "The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the csvfile." We could make this a feature request. but as far as I can tell there isn't a real use case, nor has one ever arisen in the decade long history of the module. Adding the list(fieldnames) behavior could be done without a backwards compatibility issue, but it does incur an overhead that would be paid by all existing working code. |
Perhaps we could raise an exception with a clearer error message when fieldnames not a sequence? |
I've submitted a patch that introduces code that raises TypeError at construction if |
@iritkatriel The issue seems to have been resolved. Can we close the issue? |
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: