Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm type checker expected type 'None', got 'str' instead when using pandas dataframe.to_csv

Using PyCharm 2021.2 (Community Edition) and Pandas 1.3.1, with the following code:

import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.to_csv("testfile.csv")

PyCharm will produce a Warning, highlight "testfile.csv", and display "Expected type 'None', got 'str' instead" when hovering over the Warning.

testfile.csv is created and no issues appear to be happening.

Is there a way to fix this? Does anyone know why this Warning appears?

Thanks

like image 401
Matt Avatar asked Aug 14 '21 23:08

Matt


2 Answers

This appears to be a bug in Pycharm that prevents it from properly interpreting |; the new operator for typing.Union.

If I ctrl+p while inside of the argument list of to_csv, I get this

enter image description here

Note that it thinks the argument is of type None (indicated by : None).

The problem is, this is the actual signature of the function:

def to_csv(
           self,
           path_or_buf: FilePathOrBuffer[AnyStr] | None = None,
           . . .

The type of the parameter is actually FilePathOrBuffer[AnyStr] | None, which prior to Python 3.10 would be typing.Union[FilePathOrBuffer[AnyStr], None] or simply typing.Optional[FilePathOrBuffer[AnyStr]].

Pycharm apparently can't yet read fancy type hints, despite saying it supports Python 3.10.

like image 199
Carcigenicate Avatar answered Oct 23 '22 13:10

Carcigenicate


You can suppress the PyCharm warning as follows:

# noinspection PyTypeChecker
df.to_csv("testfile.csv")

You can also add the noinspection comment at the start of a function or class to disable warnings within, but careful not to hide other real warnings. I prefer per-statement suppression only as needed.

like image 23
DV82XL Avatar answered Oct 23 '22 13:10

DV82XL