-1

I try to follow the new features for type hinting that came with Python 3.10. I use VSCode with the pylance extension.

For instance I have a methos like this in a class:

def execute(
        self, query: str, return_type: str | None = None
    ) -> pd.DataFrame | list[Any] | None:
    ...

Then I get the following seen in the screenshot below:

enter image description here

So, my question is: Is Pylance not yet ready for Python 3.10 when there could be multiple return types or am I doing something wrong?

Lewi Uberg
  • 1,055
  • 7
  • 14
  • I think value of `df_sync_records` might be something other than `pd.Dataframe` in runtime? In that case `NoneType` or `list` doesnt have `.loc` ? – Bijay Regmi May 05 '23 at 12:52
  • In the case here, I can verify the the return type is `DataFrame`. I tried to `from pandas import DataFrame` and drop the `pd.` part, but the result was there same. – Lewi Uberg May 05 '23 at 12:58
  • Can you try the old fashion way of `from typing import Union` and then declare the return type to union of those data types? – Bijay Regmi May 05 '23 at 13:04
  • I did now, and the result is the same. Maybe Pylance never supported variable return type hints..? – Lewi Uberg May 05 '23 at 13:07

1 Answers1

0

I found out how to do this propper now.

    @overload
    def execute(self, query: str, return_type: Literal["df"]) -> pd.DataFrame:
        ...

    @overload
    def execute(self, query: str, return_type: Literal["list"]) -> list[Any]:
        ...

    @overload
    def execute(self, query: str, return_type: Literal["none"]) -> None:
        ...

    def execute(self, query: str, return_type: str | None = None):
Lewi Uberg
  • 1,055
  • 7
  • 14