Pycharm 2017.1 Python open() and print() shows Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]'

Answered

I just upgraded to pycharm 2017.1 and it show false warning within with statement in following code:

def wf(outfile):
with open(outfile, 'w') as outf:
print("write", file=outf)

# same goes with
output_file = open(outfile, 'r')
print("whatever", output_file)

Screen shot:

file=outf is highlighted and shows:

Expected type 'Optional[IO[str]]', got 'TextIOWrapper[str]' instead less... (Ctrl+F1)
This inspection detects type errors in function call expressions.
Due to dynamic dispatch and duck typing,
this is possible in a limited but useful number of cases.
Types of function parameters can be specified in docstrings or in Python 3 function annotations

I think this is more bug then intended behaviour.

Can anyone point out the possible fix? 
Without ignoring the check for every print() usage?

 

PyCharm 2017.1
Build #PY-171.3780.115, built on March 24, 2017
JRE: 1.8.0_112-release-736-b13 x86
JVM: OpenJDK Server VM by JetBrains s.r.o
Windows 10 10.0

2 comments

I'm also receiving the same warning and am interested to see the response to this. For now, I have annotated my code by saying that this is a possible bug with the PyCharm IDE.

0

Please sign in to leave a comment.