Reputation: 7267
I'm using PyCharm for python coding. In a class, I have few fields, whose value will not be passed when instantiating the class, but will be set later. So, in __init__()
method, I'm setting their values to be None
. Also, to utilize PyCharm auto code completion, I'm specifying the data-type of these fields.
class SelectFrame():
index_data: pandas.DataFrame
index_filepath: Path
def __init__(self):
self.index_data = None
self.index_filepath = None
But with this, PyCharm is giving a warning Expected Type 'DataFrame', got 'None' instead
. How can I remove this warning?
Note: I don't want to suppress the TypeChecker warning altogether, neither do I want to put the comment # noinspection PyTypeChecker
everywhere I use such code. My question is
Is the None initialization correct? Or is there a better way to initialize and avoid the warning?
Upvotes: 3
Views: 798
Reputation: 5745
The None initialization is correct (unless you can know it during construction) but you declared index_data as pandas.DataFrame and None is not pandas.DataFrame so it warns you.
You should enhance the type declaration to include None as well by using Optional.
from typing import Optional
class SelectFrame():
index_data: Optional[pandas.DataFrame]
index_filepath: Optional[Path]
def __init__(self):
self.index_data = None
self.index_filepath = None
Upvotes: 6