Skip to content

non-string fieldnames for csv.DictReader and csv.DictWriter - #5366

Merged
srittau merged 4 commits into
python:masterfrom
Akuli:csv
May 10, 2021
Merged

srittau merged 4 commits into
python:masterfrom
Akuli:csv

Conversation

@Akuli

@Akuli Akuli commented May 7, 2021 •

Copy link
Copy Markdown
Collaborator

Fixes #4800

To check that this works:

import csv
import enum
from typing import TYPE_CHECKING

class Foo(enum.Enum):
    X = 1
    Y = 2

def main() -> None:
    with open('foo.csv', 'w') as file:
        writer = csv.DictWriter(file, list(Foo))
        writer.writeheader()
        writer.writerow({Foo.X: "lol", Foo.Y: "wat"})

    with open('foo.csv', 'r') as file:
        foo_reader = csv.DictReader(file, list(Foo))
        print(list(foo_reader))
        if TYPE_CHECKING:
            reveal_type(next(foo_reader))

    with open('foo.csv', 'r') as file:
        string_reader = csv.DictReader(file)
        print(list(string_reader))
        if TYPE_CHECKING:
            reveal_type(next(string_reader))

main()

Output:

[{Foo.X: 'X', Foo.Y: 'Y'}, {Foo.X: 'lol', Foo.Y: 'wat'}]
[{'X': 'lol', 'Y': 'wat'}]

mypy on master:

foo.py:13: error: Dict entry 0 has incompatible type "Foo": "str"; expected "str": "Any"
foo.py:13: error: Dict entry 1 has incompatible type "Foo": "str"; expected "str": "Any"
foo.py:19: note: Revealed type is "builtins.dict*[builtins.str, builtins.str]"
foo.py:25: note: Revealed type is "builtins.dict*[builtins.str, builtins.str]"
Found 2 errors in 1 file (checked 1 source file)

mypy after this PR:

foo.py:19: note: Revealed type is "builtins.dict*[foo.Foo*, builtins.str]"
foo.py:25: note: Revealed type is "builtins.dict*[builtins.str*, builtins.str]"

@github-actions

github-actions Bot commented May 7, 2021

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

1 similar comment
@github-actions

github-actions Bot commented May 7, 2021

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

Comment thread stdlib/csv.pyi Outdated
@github-actions

github-actions Bot commented May 7, 2021

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wrong types for csv.DictWriter

2 participants