Skip to content

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

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

Merged
merged 4 commits into from
May 10, 2021

Conversation

Akuli
Copy link
Collaborator

@Akuli Akuli commented May 7, 2021

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
Copy link
Contributor

github-actions bot commented May 7, 2021

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

1 similar comment
@github-actions
Copy link
Contributor

github-actions bot commented May 7, 2021

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

@github-actions
Copy link
Contributor

github-actions bot commented May 7, 2021

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