pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

Argument `BytesIO` is not assignable to parameter `excel_writer` for Pandas

Open wyfok opened this issue 2 months ago • 3 comments

Describe the Bug

When df.to_excel to a BytesIO , the VS extension flags below error

Argument `BytesIO` is not assignable to parameter `excel_writer` with type `ExcelWriter[Unknown] | PathLike[str] | WriteExcelBuffer | str` in function `pandas.core.generic.NDFrame.to_excel`  

code:

from io import BytesIO
import pandas as pd 
import openpyxl

bytesio = BytesIO()
df = pd.DataFrame(columns = pd.Index(["A","B","C"]))
df.to_excel(bytesio, engine="openpyxl", index=False) 

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

wyfok avatar Nov 19 '25 21:11 wyfok

Hi @yangdanny97,

I looked into this issue and managed to reproduce it. Here is what I found:

Root Cause: The issue stems from the upstream pandas library's inline type definitions. Pyrefly falls back to reading the pandas source when stubs aren't found. In pandas._typing, WriteExcelBuffer is defined as a Protocol requiring a truncate method:

class WriteExcelBuffer(WriteBuffer[bytes], Protocol):
    def truncate(self, size: int | None = ...) -> int: ...

However, io.BytesIO.truncate is positional-only (def truncate(self, size: int | None = None, /) -> int), which technically fails to satisfy the Protocol's signature (which implies keyword argument support).

The Fix: Installing the official pandas-stubs fixes this immediately because it redefines WriteExcelBuffer as a Union (e.g., Union[ExcelWriter, str, Path, BytesIO]), explicitly allowing BytesIO and bypassing the strict Protocol mismatch.

Proposal: Since Pyrefly already bundles stubs for libraries like openpyxl, would you be open to bundling pandas-stubs as well? This would solve the issue out-of-the-box for users without requiring them to install extra dependencies.

I can open a PR to add pandas-stubs to the bundled third-party types if that sounds like the right approach!

Imran-S-heikh avatar Nov 20 '25 09:11 Imran-S-heikh

Thanks for looking into this!

cc @jvansch1 regarding potentially bundling pandas-stubs w/ Pyrefly

Maybe we could do what we do for django, which is to prompt the user to install the right stubs.

yangdanny97 avatar Nov 21 '25 01:11 yangdanny97

@yangdanny97 Thanks for calling this out. I can look into bundling pandas stubs soon.

jvansch1 avatar Nov 24 '25 17:11 jvansch1

This issue has someone assigned, but has not had recent activity for more than 2 weeks.

If you are still working on this issue, please add a comment so everyone knows. Otherwise, please unassign yourself and allow someone else to take over.

Thank you for your contributions!

github-actions[bot] avatar Dec 12 '25 00:12 github-actions[bot]