Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code is unreachable after pd.concat - Python [duplicate]

Koda Ulaşılamıyor -> Code is unreachable

Koda Ulaşılamıyor -> Code is unreachable

Visual Studio code is graying out my code and saying it is unreachable after I used pd.concat(). The IDE seems to run smoothly but it's disturbing and I want my colorful editor back.

How do I disable the editor graying out my code without changing the current language?

like image 944
wwyyaa Avatar asked Aug 25 '26 02:08

wwyyaa


2 Answers

This is a bug currently existing in pandas-stubs.

The matching overload of concat in pandas-stubs currently returns Never.

According to this suggestion in Pylance github, you could work around the pandas-stubs issue by commenting out the Never overload in ...\.vscode\extensions\ms-python.vscode-pylance-2024.3.1\dist\bundled\stubs\pandas\core\reshape\concat.pyi.

@overload
def concat(
    objs: Iterable[None] | Mapping[HashableT1, None],
    *,
    axis: Axis = ...,
    join: Literal["inner", "outer"] = ...,
    ignore_index: bool = ...,
    keys: Iterable[HashableT2] = ...,
    levels: Sequence[list[HashableT3] | tuple[HashableT3, ...]] = ...,
    names: list[HashableT4] = ...,
    verify_integrity: bool = ...,
    sort: bool = ...,
    copy: bool = ...,
) -> Never: ...
like image 173
MingJie-MSFT Avatar answered Aug 27 '26 14:08

MingJie-MSFT


The reason is because there is an overloaded method signature in pandas-stubs which states that giving an Iterable[None] will always throw an exception. Instead it only accepts Iterable[Series] or Iterable[DataFrame]. VSCode's static analysis doesn't check whether this is true, of course, so it falsely claims there is unreachable code.

There is some debate about who's responsibility it is to make this work as expected (see github issue), but I'd like to offer an easy solution that doesn't involve monkey-patching the stubs, and should always work.

If you add type hints to reassure VSCode that the input will be one of the accepted types, then it won't think that the program will crash.

In your case, the problem is that sort_values says it will return Any. So, you can fix that by just add type hints to the preceding variables:

sorted_excel_file_1: pd.DataFrame = df.iloc[:82].sort_values(by='H-arm', ascending=True)
sorted_excel_file_2: pd.DataFrame = df.iloc[82:].sort_values(by='H-arm', ascending=True)
like image 25
Multihunter Avatar answered Aug 27 '26 15:08

Multihunter