Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] I have confirmed this bug exists on the latest version of pandas.
-
[ ] I have confirmed this bug exists on the master branch of pandas.
Reproducible Example
from unittest import mock
import pandas as pd
from pandas.core.dtypes.common import is_list_like
class C:
m = staticmethod(lambda x: x+1)
# This raises ValueError(No objects to concatenate) since the mock is
# interpreted as a list by is_list_like.
with mock.patch.object(C, 'm', side_effect=lambda x: x):
pd.Series([10, 2]).apply(C.m)
# This is False.
print(is_list_like(C.m))
with mock.patch.object(C, 'm', side_effect=lambda x: x):
# This is True.
print(is_list_like(C.m))
Issue Description
In a context manager, a mocked function in Series.apply
calls the function to aggregate instead of the standard one. That mock is possible in Pandas 1.2.x, but not with 1.3.x.
Expected Behavior
from unittest import mock
import pandas as pd
from pandas.core.dtypes.common import is_list_like
class C:
m = staticmethod(lambda x: x+1)
with mock.patch.object(C, 'm', side_effect=lambda x: x):
pd.Series([10, 2]).apply(C.m)
with mock.patch.object(C, 'm', side_effect=lambda x: x):
assert is_list_like(C.m)
Installed Versions
Comment From: mmas
Using mock.Mock
instead of mock.MagicMock
works as expected:
with mock.patch.object(C, 'm', side_effect=lambda x: x, new_callable=mock.Mock):
print(pd.Series([10, 2]).apply(C.m))
# This is true.
is_list_like(mock.MagicMock())
# This is false.
is_list_like(mock.Mock())
Comment From: debugduck
I ran into this exact issue today using 1.4.4
. Ended up adding the new_callable
arg as shown above to change the mock object type, but before I came across this thread I also found that wrapping the mocked function worked as well. something like,
series.apply(lambda x: mockedFunction(x))
I chose the above option though as it felt safer to change only the unit test rather than modifying code that would be used for unit testing and regular usage.