Skip to content

Commit

Permalink
Merge pull request #1402 from burnash/bugfix/missing_spreadsheet_attr…
Browse files Browse the repository at this point in the history
…ibute

Fix missing attribute `spreadsheet` in `Worksheet`.
  • Loading branch information
lavigne958 authored Feb 5, 2024
2 parents 0c52198 + 704ecc2 commit cb1a63e
Show file tree
Hide file tree
Showing 4 changed files with 439 additions and 10 deletions.
13 changes: 6 additions & 7 deletions gspread/spreadsheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def get_worksheet(self, index):

try:
properties = sheet_data["sheets"][index]["properties"]
return Worksheet(self.id, self.client, properties)
return Worksheet(self, properties, self.id, self.client)
except (KeyError, IndexError):
raise WorksheetNotFound("index {} not found".format(index))

Expand Down Expand Up @@ -259,7 +259,7 @@ def get_worksheet_by_id(self, id: Union[str, int]):
lambda x: x["properties"]["sheetId"] == worksheet_id_int,
sheet_data["sheets"],
)
return Worksheet(self.id, self.client, item["properties"])
return Worksheet(self, item["properties"], self.id, self.client)
except (StopIteration, KeyError):
raise WorksheetNotFound("id {} not found".format(worksheet_id_int))

Expand All @@ -276,7 +276,7 @@ def worksheets(self, exclude_hidden: bool = False):
"""
sheet_data = self.fetch_sheet_metadata()
worksheets = [
Worksheet(self.id, self.client, s["properties"])
Worksheet(self, s["properties"], self.id, self.client)
for s in sheet_data["sheets"]
]
if exclude_hidden:
Expand Down Expand Up @@ -307,7 +307,7 @@ def worksheet(self, title):
lambda x: x["properties"]["title"] == title,
sheet_data["sheets"],
)
return Worksheet(self.id, self.client, item["properties"])
return Worksheet(self, item["properties"], self.id, self.client)
except (StopIteration, KeyError):
raise WorksheetNotFound(title)

Expand Down Expand Up @@ -349,9 +349,7 @@ def add_worksheet(self, title, rows, cols, index=None):

properties = data["replies"][0]["addSheet"]["properties"]

worksheet = Worksheet(self.id, self.client, properties)

return worksheet
return Worksheet(self, properties, self.id, self.client)

def duplicate_sheet(
self,
Expand Down Expand Up @@ -383,6 +381,7 @@ def duplicate_sheet(
self.client,
self.id,
source_sheet_id,
self,
insert_sheet_index=insert_sheet_index,
new_sheet_id=new_sheet_id,
new_sheet_name=new_sheet_name,
Expand Down
45 changes: 42 additions & 3 deletions gspread/worksheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import re
import warnings
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Expand Down Expand Up @@ -59,6 +60,9 @@
to_records,
)

if TYPE_CHECKING is True:
from .spreadsheet import Spreadsheet

CellFormat = TypedDict(
"CellFormat",
{
Expand Down Expand Up @@ -157,14 +161,42 @@ class Worksheet:

def __init__(
self,
spreadsheet_id: str,
client: HTTPClient,
spreadsheet: "Spreadsheet",
properties: MutableMapping[str, Any],
spreadsheet_id: Optional[str] = None,
client: Optional[HTTPClient] = None,
):
# This object is not intended to be created manually
# only using gspread code like: spreadsheet.get_worksheet(0)
# keep it backward compatible signarure but raise with explicit message
# in case of missing new attributes

if spreadsheet_id is None or "":
raise RuntimeError(
"""Missing spreadsheet_id parameter, it must be provided with a
valid spreadsheet ID.
Please allocate new Worksheet object using method like:
spreadsheet.get_worksheet(0)
"""
)

if client is None or not isinstance(client, HTTPClient):
raise RuntimeError(
"""Missing HTTP Client, it must be provided with a
valid instance of type gspread.http_client.HTTPClient .
Please allocate new Worksheet object using method like:
spreadsheet.get_worksheet(0)
"""
)

self.spreadsheet_id = spreadsheet_id
self.client = client
self._properties = properties

# kept for backward compatibility - publicly available
# do not use if possible.
self._spreadsheet = spreadsheet

def __repr__(self) -> str:
return "<{} {} id:{}>".format(
self.__class__.__name__,
Expand All @@ -177,6 +209,11 @@ def id(self) -> int:
"""Worksheet ID."""
return self._properties["sheetId"]

@property
def spreadsheet(self) -> "Spreadsheet":
"""Parent spreadsheet"""
return self._spreadsheet

@property
def title(self) -> str:
"""Worksheet title."""
Expand Down Expand Up @@ -2406,6 +2443,7 @@ def _duplicate(
client: HTTPClient,
spreadsheet_id: str,
sheet_id: int,
spreadsheet: Any,
insert_sheet_index: Optional[int] = None,
new_sheet_id: Optional[int] = None,
new_sheet_name: Optional[str] = None,
Expand Down Expand Up @@ -2448,7 +2486,7 @@ def _duplicate(

properties = data["replies"][0]["duplicateSheet"]["properties"]

return Worksheet(spreadsheet_id, client, properties)
return Worksheet(spreadsheet, properties, spreadsheet_id, client)

def duplicate(
self,
Expand All @@ -2475,6 +2513,7 @@ def duplicate(
self.client,
self.spreadsheet_id,
self.id,
self.spreadsheet,
insert_sheet_index=insert_sheet_index,
new_sheet_id=new_sheet_id,
new_sheet_name=new_sheet_name,
Expand Down
Loading

0 comments on commit cb1a63e

Please sign in to comment.