Mypy type hints for arguments which are pandas series

Viewed 1103

I have the following, which I would expect to raise an error:

# check.py
import pandas as pd

def f(s : str) -> None:
    print(s)

def main() -> None:
    f(s = pd.Series([1,2]))

if __name__ == "__main__":
    main()

However, mypy check.py returns Success: no issues found in 1 source file.

How is one supposed to provide typehints for pandas series?

In the pandas code (https://github.com/pandas-dev/pandas/blob/98e22297bb66f81ff4c1d4f1c3277cfe8c6b9ce7/pandas/core/series.py#L511) there's:

    def _constructor(self) -> type[Series]:
        return Series

type[Series], I'm not sure if this is how we're supposed to typehint series though?

edit

updating the code to:

# check.py
import pandas as pd

def f(s : str) -> None:
    print(s)

def g(s : str) -> None:
    print(s)

def main() -> None:
    f(s = pd.Series([1,2]))
    g(s = 12.9)

if __name__ == "__main__":
    main()

gives the output:

check.py:12: error: Argument "s" to "g" has incompatible type "float"; expected "str"  [arg-type]
Found 1 error in 1 file (checked 1 source file)
1 Answers

This is a common issue in mypy - it will not check types on functions if they don't have the output type annotation - you need to add -> None to main.

This will then give you the error:

test.py:7: error: Argument "s" to "f" has incompatible type "Series[int]"; expected "str"

Which can be fixed with the annotation s: pd.Series[int]


So this is the full script:

import pandas as pd

def f(s: pd.Series[int]) -> None:
    print(s)

def main() -> None:
    f(s = pd.Series([1,2]))

if __name__ == "__main__":
    main()

Note: You may also need to pip install data-science-types as depending on how you installed pandas it may not come with type stubs.

Related