Search code examples
pythonpython-typingpyright

Python Type Issue - Pylance - Cannot access member "..." for type "..." Member "..." is unknown


I get the "Member is unknown" issue from Pylance in VSCode a lot.

For example: If I have a pandas DataFrame with a datetime index and do this:

df.index.month

I get:

Cannot access member "month" for type "Index" Member "month" is unknown

It seems to happen a lot when I access something with "."

The code works as intended, I just get these annoying errors in VSCode. Am I doing something wrong or is there a way to avoid these (without turning off type checking all together)?


Solution

  • It is not perfect but now you only have 1 error:

    pd.DataFrame is incompatible with DataFrameDTI

    The month not member of Index errors are gone.

    Define a sub class of pd.DataFrame and give the index property a different type.

    class DataFrameDTI(pd.DataFrame):
      @property
      def index(self) -> pd.DatetimeIndex: ...
      @index.setter
      def index(self, idx: pd.DatetimeIndex) -> None: ...
    
    # .....
    
    df2 : DataFrameDTI = df.set_index(datetime_index)
    
    print(df2.index.month)