Skip to content

csv.DictWriter.writeheader loses field-name representations for equal keys #158776

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: Python csv documentation, DictWriter.writeheader(): “Write a row with the field names (as specified in the constructor) to the writer’s file object, formatted according to the current dialect.”

Expected: '1,True\r\n'

Actual: 'True,True\r\n'

import csv
import io

fields = [1, True]
formatting = {}
case = {"fieldnames": fields, "formatting": formatting}
try:
    for field in fields:
        hash(field)  # Valid dictionary keys; fieldnames is a finite sequence.
    actual, expected = io.StringIO(), io.StringIO()
    csv.DictWriter(actual, fieldnames=fields, **formatting).writeheader()
    csv.writer(expected, **formatting).writerow(fields)
    actual, expected = actual.getvalue(), expected.getvalue()
    if actual != expected:
        print("REFUTATION CONFIRMED:", case, "actual:", repr(actual),
              "expected:", repr(expected))
    else:
        print("REFUTATION REJECTED: actual matches documented expectation")
except Exception as exc:
    print("REFUTATION REJECTED:", type(exc).__name__, str(exc))

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library csv:

REFUTATION CONFIRMED: {'fieldnames': [1, True], 'formatting': {}} actual: 'True,True\r\n' expected: '1,True\r\n'

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/csv-20261003-022404-c1

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions