pyright icon indicating copy to clipboard operation
pyright copied to clipboard

Unreachable code complain

Open acampove opened this issue 1 year ago • 2 comments

Pyright complains about unreachable code that is reachable

Code or Screenshots

Image
import pandas as pd

def _add_eff(df: pd.DataFrame) -> pd.DataFrame:
    df['Eff'] = df['Passed'] / df['All']
    df['Cum'] = df['Eff'].cumprod()
    return df

acampove avatar Sep 16 '25 11:09 acampove

I'm not able to repro. Which version of pandas do you have installed? Are you using pandas-stubs? If so, what version?

This is unlikely to be a bug in pyright. It's more likely an issue with the library or stubs that you're using.

If you're able to reduce this to an MRE (one that doesn't depend on pd), that would also be helpful.

erictraut avatar Sep 16 '25 14:09 erictraut

I could repro the problem with pandas-stubs.

repro log
$ docker run --rm -it python:3.12 bash
root@6593ae67e432:/# pip install pandas
(snip)
Installing collected packages: pytz, tzdata, six, numpy, python-dateutil, pandas
Successfully installed numpy-2.3.3 pandas-2.3.2 python-dateutil-2.9.0.post0 pytz-2025.2 six-1.17.0 tzdata-2025.2
(snip)
root@6593ae67e432:/# pip install pandas-stubs
(snip)
Installing collected packages: types-pytz, pandas-stubs
Successfully installed pandas-stubs-2.3.2.250827 types-pytz-2025.2.0.20250809
(snip)
root@6593ae67e432:/# pip install pyright
(snip)
Installing collected packages: typing-extensions, nodeenv, pyright
Successfully installed nodeenv-1.9.1 pyright-1.1.405 typing-extensions-4.15.0
(snip)
root@6593ae67e432:/# cat > foo.py
import pandas as pd

def f(s: pd.DataFrame):
   s['foo'].cumprod()

reveal_type(f)

root@6593ae67e432:/# pyright foo.py
 * Install prebuilt node (24.8.0) ../usr/local/lib/python3.12/site-packages/nodeenv.py:639: DeprecationWarning: Python 3.14 will, by default, filter extracted tar archives and reject files or modify their metadata. Use the filter argument to control this behavior.
  archive.extractall(src_dir, extract_list)
... done.
/foo.py
  /foo.py:6:13 - information: Type of "f" is "(s: DataFrame) -> NoReturn"
0 errors, 0 warnings, 1 information

I think the root cause is these overloads, and not a bug in pyright: https://github.com/pandas-dev/pandas-stubs/blob/c38b6a3cbf029361d88bafa89e87e4263f0b0982/pandas-stubs/core/series.pyi#L3506-L3521

The stub author’s intention seems to be that the return type of cumprod is Never for Series[str], and Series[T] for other Series[T]. However, according to the current typing spec, it looks like the first overload (which returns Never) would be selected for Series[Any] (the type of df['Eff']).

pinterior avatar Sep 17 '25 11:09 pinterior