pythoncsvtype-hinting

How to type-annotate object returned by csv.writer?


I want to apply type annotation to the returned object of csv.writer in order to comply with a larger codebase. Unfortunately I can not figure out the fitting return type.

>>> import csv
>>> writer = csv.writer(open('outfile.csv', 'w'))
>>> type(writer)
<class '_csv.writer'>

If I try to use this classname:

>>> import _csv
>>> writer: _csv.writer = csv.writer(open('outfile.csv', 'w'))

I get the following mypy error:

Invalid type "_csv.writer"

Does someone know which type to use in this case. Of course I could use typing.Any but this nullify the sense of a type annotation.


Solution

  • Often when things are acting weird it's a sign typeshed doesn't exactly map to runtime. If you look at _csv in typeshed you will see the type is named _writer. So you should can the annotation to _csv._writer.