Search code examples
pythonpandasmypytyping

mypy and "apply" of "Series" does not accept returns of an object of type set[Any]


Here is a MRE:

import pandas as pd

data = {'list1': [1, 2, 3], 'list2': ['a', 'b', 'c'], 'list3': [True, False, True]}
series_of_lists: pd.Series = pd.Series(data)

series_of_lists = series_of_lists.apply(lambda x: set(x))

The failure I get is the following:

6: error: Argument 1 to "apply" of "Series" has incompatible type "Callable[[Any], Set[Any]]"; expected "Callable[..., Union[str, bytes, date, timedelta, datetime64, timedelta64, int, float, complex, Sequence[Any], Mapping[Any, Any]]]"  [arg-type]
6: error: Incompatible return value type (got "Set[Any]", expected "Union[str, bytes, date, timedelta, datetime64, timedelta64, int, float, complex, Sequence[Any], Mapping[Any, Any]]")  [return-value]

It seems that mypy is still not satisfied with the lambda function used in the apply method, as it expects the return value to be one of the types listed in the error message.

I'm using Python 3.11.1, mypy 1.1.1, pytest-mypy 0.10.3, pandas 1.5.3 and pandas-stubs 1.5.3.230321.

What is even weirder is that when I print type(series_of_lists[0]), I do get <class 'set'>.


Solution

  • I made a PR. It's been merged. It should be fixed now.