Skip to content

Series.apply() should accept None as Callable return type #557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
chetanpepper opened this issue Mar 1, 2023 · 1 comment · Fixed by #670
Closed

Series.apply() should accept None as Callable return type #557

chetanpepper opened this issue Mar 1, 2023 · 1 comment · Fixed by #670
Labels
Apply Apply, Aggregate, Transform good first issue

Comments

@chetanpepper
Copy link

chetanpepper commented Mar 1, 2023

Describe the bug
Pandas is fine if the Callable passed to series.apply(...) returns None, but mypy throws an error. Passing a null-returning Callable to df.apply() does not throw an error.

To Reproduce

import pandas as pd

s = pd.Series([{'a': 1, 'b':2}])
s['c'] = s.apply(lambda x: None)

mypy fails with

a.py:4: error: Argument 1 to "apply" of "Series" has incompatible type "Callable[[Any], None]"; expected "Callable[..., Union[str, bytes, date, datetime, timedelta, datetime64, timedelta64, bool, int, float, Timestamp, Timedelta, complex, Sequence[Any], Mapping[Any, Any]]]"  [arg-type]
a.py:4: error: Incompatible return value type (got "None", expected "Union[str, bytes, date, datetime, timedelta, datetime64, timedelta64, bool, int, float, Timestamp, Timedelta, complex, Sequence[Any], Mapping[Any, Any]]")  [return-value]
Found 2 errors in 1 file (checked 1 source file)

Please complete the following information:

  • MacOS
  • 12.6
  • python3.10
  • mypy 1.0.1
  • pandas-stubs 1.5.3.230227

Additional context
Using a data frame instead of a series results in no error:

import pandas as pd

df = pd.DataFrame([{'a': 1, 'b':2}])
df['c'] = df.apply(lambda x: None)
@Dr-Irv
Copy link
Collaborator

Dr-Irv commented Mar 2, 2023

Thanks for the report. At least with pyright, I am seeing this as a problem for both Series.apply() and DataFrame.apply().

In the case of Series.apply(), just have to change

func: Callable[..., Scalar | Sequence | Mapping],

to include None as a possible result in Callable.

For DataFrame.apply(), have to duplicate lines that have S1 as an argument to another overload that returns Series instead of Series[S1], as appropriate.

Tests needed for both cases.

@Dr-Irv Dr-Irv added good first issue Apply Apply, Aggregate, Transform labels Mar 2, 2023
@Dr-Irv Dr-Irv mentioned this issue May 1, 2023
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Apply Apply, Aggregate, Transform good first issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants