Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm - Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead

Tags:

python

After updating PyCharm to 2017.1, a new inspection warning started to pop up in a place where everything's seemingly simple and correct. It looks as following:

Screenshot

It looks like open() doesn't return the expected type for file parameter, but the code is pretty straightforward and, most importantly, does work as expected (using Python 3.5.2).

Python docs mention a way using StringIO and it removes the warning indeed, but is it the correct pythonic way to specify output stream for print? If so, why? Is this warning important to follow?

like image 670
Roman Kotenko Avatar asked Apr 07 '17 17:04

Roman Kotenko


1 Answers

The only solution I found is to type hint PyCharm correctly:

from typing import IO

with open('output_filename', 'w') as f:  # type: IO[str]
    print('some text to go to the file...', file=f)

This keeps PyCharm happy and does not in any way impede the correct running of your code.

like image 124
Mark Veltzer Avatar answered Oct 17 '22 04:10

Mark Veltzer