Skip to content

"csv.writer.write" does not work for objects expecting something other than "str" in their "write" method #3997

Description

@deveshks

This was originally found when upgrading pip to mypy 0.770 in pypa/pip#8235

There was a change made to _csv.pyi in #3581 which hardcodes the input type of _Writer.write to str

class _Writer(Protocol):
def write(self, s: str) -> Any: ...

If I understand correctly, as per the csv.writer docs , csvfile can be any object with a write() method, which means that things like io.BytesIO whose write accepts bytes-like object will fail typechecking

A minimal reproducer for this is as follows, and the type checking was done against mypy 0.770
and python 3.8.2

import csv
import io

buffer = io.BytesIO()
wrt = csv.writer(buffer)

And the output is

$ mypy --version
mypy 0.770

$ python --version
Python 3.8.2

$ mypy scratch.py 
scratch.py:5: error: Argument 1 to "writer" has incompatible type "BytesIO"; expected "_Writer"
scratch.py:5: note: Following member(s) of "BytesIO" have conflicts:
scratch.py:5: note:     Expected:
scratch.py:5: note:         def write(self, s: str) -> Any
scratch.py:5: note:     Got:
scratch.py:5: note:         def write(self, Union[bytes, bytearray]) -> int
Found 1 error in 1 file (checked 1 source file)

Also note that this worked in mypy 0.760

$ mypy --version
mypy 0.760

$ mypy scratch.py 
Success: no issues found in 1 source file

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