Skip to content

openpyxl: Workbook opened in readonly mode should return ReadOnlyCell | EmptyCell from worksheet.rows #9940

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jamesbeith opened this issue Mar 25, 2023 · 5 comments
Labels
stubs: improvement Improve/refactor existing annotations, other stubs issues

Comments

@jamesbeith
Copy link
Contributor

jamesbeith commented Mar 25, 2023

Currently the type hints for worksheet.rows returns Cell objects. However, opening a workbook in readonly mode results in ReadOnlyCell or EmptyCell objects being returned.

>>> workbook = openpyxl_excel_reader.load_workbook(file, read_only=True)
>>> worksheet = workbook.worksheets[0]  # openpyxl.worksheet._read_only.ReadOnlyWorksheet
>>> [row for row in worksheet.rows]
[
    (<ReadOnlyCell 'Sheet1'.A1>, <EmptyCell>, <ReadOnlyCell 'Sheet1'.C1>),
    (<ReadOnlyCell 'Sheet1'.A2>, <EmptyCell>, <ReadOnlyCell 'Sheet1'.C2>),
]
@sobolevn
Copy link
Member

The problem is that .worksheets always return Worksheet and does not ever return _ReadOnlyWorksheet: https://github.com/python/typeshed/blob/main/stubs/openpyxl/openpyxl/workbook/workbook.pyi#L61

And load_workbook always returns Workbook

So, we don't have enough typing information right now to make this work.

Ideas?

@jamesbeith
Copy link
Contributor Author

Could we use @overload and Literal for the load_workbook() function, where if read_only is the literal True then we instead return some kind of new ReadOnlyWorkbook type which itself returns _ReadOnlyWorksheet from .worksheets (and then ReadOnlyCell | EmptyCell for it's rows). Is that a feasible idea?

https://mypy.readthedocs.io/en/stable/literal_types.html#literal-types

@sobolevn
Copy link
Member

Yes, seems ok to me :)
Do you want to work on this?

@jamesbeith
Copy link
Contributor Author

Do you want to work on this?

@sobolevn I'll aim to take a look 👍🏼

@Avasam
Copy link
Collaborator

Avasam commented Apr 4, 2024

Do note that this problem goes one step further: ReadOnlyWorksheet cell methods come from Worksheet, so you'd have to specialize ReadOnlyWorksheet's cell-related method types on top of making Workbook generic.

@Avasam Avasam added the stubs: improvement Improve/refactor existing annotations, other stubs issues label Mar 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: improvement Improve/refactor existing annotations, other stubs issues
Projects
None yet
Development

No branches or pull requests

3 participants