Search code examples
pythonpython-typingpylance

Type hints with Python ^3.10 and Pylance for VSCode


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?


Solution

  • 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):