pandas-stubs icon indicating copy to clipboard operation
pandas-stubs copied to clipboard

Make it possible for type checking to detect "The truth value of a DataFrame is ambiguous."

Open karolzlot opened this issue 2 years ago • 5 comments

I described the problem here: https://github.com/microsoft/pyright/issues/5024 and also here: https://github.com/microsoft/pylance-release/issues/4289

karolzlot avatar Apr 27 '23 23:04 karolzlot

Maybe annotate __bool__ on pd.DataFrame and pd.Series to return typing.Never ?

gandhis1 avatar Apr 27 '23 23:04 gandhis1

I think the solution here is that DataFrame.__eq__() needs to have a stub in core/frame.pyi returning a DataFrame

Dr-Irv avatar Apr 28 '23 12:04 Dr-Irv

I think the solution here is that DataFrame.__eq__() needs to have a stub in core/frame.pyi returning a DataFrame

I'm not sure I follow what that will accomplish. This error is triggered when someone does the equivalent of casting a DataFrame to a bool - which calls __bool__, no?

Even pandas itself has it annotated the way I suggested:

    @final
    def __nonzero__(self) -> NoReturn:
        raise ValueError(
            f"The truth value of a {type(self).__name__} is ambiguous. "
            "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
        )

    __bool__ = __nonzero__

gandhis1 avatar Apr 30 '23 03:04 gandhis1

I'm not sure I follow what that will accomplish. This error is triggered when someone does the equivalent of casting a DataFrame to a bool - which calls __bool__, no?

You're right, and actually DataFrame.__eq__() is return a DataFrame already.

So I tried with a simple class, and it didn't work with pyright. See https://github.com/microsoft/pyright/issues/5039

Dr-Irv avatar Apr 30 '23 15:04 Dr-Irv

pyright fixed the issue, in 1.1.306 so we should define __bool__() for Series and DataFrame as NoReturn, and add some tests.

Dr-Irv avatar May 04 '23 00:05 Dr-Irv