How can I stop mypy complaining when comparing a pd.Series to single value?
Question:
I have the following code:
result = pd.Series([pd.Timedelta(minutes=2)]) > pd.Timedelta(hours=1)
However mypy complains with the following:
error: Unsupported operand types for > ("Series[Any]" and "Timedelta")
I also tried:
s: pd.Series[pd.Timedelta] = pd.Series([pd.Timedelta(minutes=2)])
result = s > pd.Timedelta(hours=1)
But that also gives an error:
error: Unsupported operand types for > ("Series[Timedelta]" and "Timedelta")
Note that mypy doesn’t complain if I just have a series with int
s such as pd.Series([10]) > 3
.
What am I doing wrong?
Answers:
pandas-stubs
1.4.3.220724 does not allow Timedelta
in pandas.Series.__gt__
.
This has been fixed in pandas-stubs
1.4.3.220801.
Workarounds for earlier versions
1. Exclude that line from type checking
s = pd.Series([pd.Timedelta(minutes=2)])
result = s > pd.Timedelta(hours=1) # type: ignore
2. Use the flexible wrapper of that comparison operator
In this case, pandas.Series.gt
.
s = pd.Series([pd.Timedelta(minutes=2)])
result = s.gt(pd.Timedelta(hours=1))
3. Explicitly declare to type checkers that it’s actually supported
from typing import cast
import pandas as pd
class SupportsGtTimedelta:
def __gt__(self, other: pd.Timedelta): ...
s = cast(SupportsGtTimedelta, pd.Series([pd.Timedelta(minutes=2)]))
result = s > pd.Timedelta(hours=1)
I have the following code:
result = pd.Series([pd.Timedelta(minutes=2)]) > pd.Timedelta(hours=1)
However mypy complains with the following:
error: Unsupported operand types for > ("Series[Any]" and "Timedelta")
I also tried:
s: pd.Series[pd.Timedelta] = pd.Series([pd.Timedelta(minutes=2)])
result = s > pd.Timedelta(hours=1)
But that also gives an error:
error: Unsupported operand types for > ("Series[Timedelta]" and "Timedelta")
Note that mypy doesn’t complain if I just have a series with int
s such as pd.Series([10]) > 3
.
What am I doing wrong?
pandas-stubs
1.4.3.220724 does not allow Timedelta
in pandas.Series.__gt__
.
This has been fixed in pandas-stubs
1.4.3.220801.
Workarounds for earlier versions
1. Exclude that line from type checking
s = pd.Series([pd.Timedelta(minutes=2)])
result = s > pd.Timedelta(hours=1) # type: ignore
2. Use the flexible wrapper of that comparison operator
In this case, pandas.Series.gt
.
s = pd.Series([pd.Timedelta(minutes=2)])
result = s.gt(pd.Timedelta(hours=1))
3. Explicitly declare to type checkers that it’s actually supported
from typing import cast
import pandas as pd
class SupportsGtTimedelta:
def __gt__(self, other: pd.Timedelta): ...
s = cast(SupportsGtTimedelta, pd.Series([pd.Timedelta(minutes=2)]))
result = s > pd.Timedelta(hours=1)