Utilities

General utilities.

codePost Utilities

Utilities involving the codePost SDK.

@codepost_powertools.utils.codepost_utils.with_course

Decorates a function to fetch a course before calling.

This decorator will fetch a Course if necessary to call the decorated function.

func(course: CourseArg, *args, **kwargs) -> RT
# becomes
func(course: Course | None, *args, **kwargs) -> RT

If the retrieval is unsuccessful, course will be passed as None, which the function should handle itself.

New in version 0.1.0.

@codepost_powertools.utils.codepost_utils.with_course_and_assignment

Decorates a function to fetch a course and assignment before calling.

This decorator will fetch a Course and Assignment if necessary to call the decorated function.

func(
  course: CourseArg, assignment: AssignmentArg,
  *args, **kwargs
) -> RT
# becomes
func(
  course: Course | None, assignment: Assignment | None,
  *args, **kwargs
) -> RT

If any retrievals are unsuccessful, course and assignment will both be passed as None, which the function should handle itself.

New in version 0.1.0.

codepost_powertools.utils.codepost_utils.get_course(name, period, *, log=False)

Gets a codePost course.

If there are multiple courses with the same name and period, the first one found is returned.

Parameters:
  • name (str) – The course name.

  • period (str) – The course period.

  • log (bool) – Whether to show log messages.

Returns:

The course.

Return type:

SuccessOrNone [Course]

Raises:

ValueError – If no course is found.

New in version 0.1.0.

codepost_powertools.utils.codepost_utils.course_str(course, *, delim=' ')

Returns a str representation of a course.

Parameters:
  • course (Course) – The course.

  • delim (str) – A delimiting string between the name and the period.

Returns:

A string representation of the course.

Return type:

str

New in version 0.1.0.

codepost_powertools.utils.codepost_utils.get_course_roster(course, *, log=False)

Gets the roster for the given course.

Parameters:
  • course (CourseArg) – The course.

  • log (bool) – Whether to show log messages.

Returns:

The roster.

Return type:

SuccessOrNone [Roster]

New in version 0.1.0.

codepost_powertools.utils.codepost_utils.get_assignment(course, assignment_name, *, log=False)

Gets a codePost assignment from a course.

Parameters:
  • course (CourseArg) – The course.

  • assignment_name (str) – The assignment name.

  • log (bool) – Whether to show log messages.

Returns:

The assignment.

Return type:

SuccessOrNone [Assignment]

Raises:

ValueError – If the assignment is not found.

New in version 0.1.0.

Changed in version 0.2.0: codePost does not allow multiple assignments to have the same name, so the extra checks for that were removed.

gspread Utilities

Wrapper classes around gspread.spreadsheet.Spreadsheet and gspread.worksheet.Worksheet.

This module uses Sheets API helper objects.

class codepost_powertools.utils.gspread_wrappers.Spreadsheet

A wrapper class around gspread.spreadsheet.Spreadsheet.

The add_worksheet() method will change the specified title so that there is no worksheet title conflict.

New in version 0.2.0.

static wrap(spreadsheet)

Converts a gspread.spreadsheet.Spreadsheet into an instance of the Spreadsheet wrapper.

Parameters:

spreadsheet (gspread.spreadsheet.Spreadsheet) –

Return type:

Spreadsheet

New in version 0.2.0.

get_valid_worksheet_title(title, *, fmt='{title} {num}')

Returns a valid worksheet title from the given title.

If the title already exists in the spreadsheet, a number will be appended to the end of the title and incremented until there is no longer a conflict.

Parameters:
  • title (str) – The title.

  • fmt (str) – A template format for how the number is appended to the title. Requires "{title}" and "{num}" to be included in the string.

Returns:

The valid title.

Return type:

str

Raises:

ValueError – If fmt is invalid.

add_worksheet(title='Sheet', *, rows=1, cols=1, index=None)

Adds a new worksheet to the spreadsheet.

If index is given, the worksheet will be inserted before the given 0-indexed index. For example, index = 0 will insert the worksheet at the very beginning, and index = 1 will insert the worksheet between the first and second sheets. If index is not given, the worksheet will be added at the end.

Parameters:
  • title (str) – The title of the worksheet.

  • rows (int) – The number of rows.

  • cols (int) – The number of columns.

  • index (int) – The index position to insert the worksheet (0-indexed).

Returns:

The worksheet.

Return type:

gspread.worksheet.Worksheet

New in version 0.2.0.

codepost_powertools.utils.gspread_wrappers.col_letter_to_index(col)

Converts a column letter to its numerical index.

Parameters:

col (str) – The column letter.

Returns:

The column number (1-indexed).

Return type:

int

Raises:

gspread.exceptions.InvalidInputValue – If the input is invalid.

New in version 0.2.0.

codepost_powertools.utils.gspread_wrappers.col_index_to_letter(col)

Converts a column index to its A1 notation letter.

Parameters:

col (int) – The column number (1-indexed).

Returns:

The column letter.

Return type:

str

Raises:

gspread.exceptions.InvalidInputValue – If the input is invalid.

New in version 0.2.0.

class codepost_powertools.utils.gspread_wrappers.Worksheet

A wrapper class around gspread.worksheet.Worksheet.

New in version 0.2.0.

DEFAULT_ROW_HEIGHT: int = 21

The default height of a row.

DEFAULT_COL_WIDTH: int = 120

The default width of a column.

Note

Newly created spreadsheets will have column widths of 100, but the “Resize Column” popup says the default is 120.

__init__(worksheet)

Initializes a worksheet.

Parameters:

worksheet (gspread.worksheet.Worksheet) – The worksheet returned from gspread.

New in version 0.2.0.

property title: str

The worksheet title. Can be set.

New in version 0.2.0.

property num_rows: int

The number of rows in the worksheet.

New in version 0.2.0.

property num_cols: int

The number of columns in the worksheet.

New in version 0.2.0.

property num_frozen_rows: int

The number of frozen rows in the worksheet.

New in version 0.2.0.

property num_frozen_cols: int

The number of frozen columns in the worksheet.

New in version 0.2.0.

update()

Updates the Google Sheet with the cached requests.

Any method with update set to False will cache its request. If a method doesn’t have the update keyword argument, its change takes effect immediately.

The requests are processed in the given order. If an exception occurs, the rest of the requests are ignored. However, all the pending requests will be cleared, even if they weren’t processed. (This is done so that interactive Python sessions can run into errors and still be used after.)

New in version 0.2.0.

get_cell(cell_a1)

Gets a cell of the worksheet.

Parameters:

cell_a1 (str) – The cell in A1 notation.

Return type:

gspread.cell.Cell

New in version 0.2.0.

get_values()

Gets all the values of the worksheet as a 2D list.

Return type:

List[List[str]]

New in version 0.2.0.

get_records(empty2zero=False, header_row=1, default_blank='')

Gets the values of the worksheet with the head row as keys.

Parameters:
  • empty2zero (bool) – Whether empty cells are converted to 0.

  • header_row (int) – The header row number (1-indexed). All above rows will be ignored.

  • default_blank (Any) – The default value of blank cells.

Returns:

The row values with each row in the format: { header1: val1, header2: val2, ... }

Return type:

List[Dict[str, Any]]

New in version 0.2.0.

set_values(values, range_a1='A1')

Sets the values of the worksheet.

The data will be inserted starting at the top-left cell of range_a1. The size of the range itself doesn’t matter, so a single value of the top-left cell of the data is enough.

Parameters:
  • values (List[List[Any]]) – The values.

  • range_a1 (str) – The range in A1 notation.

New in version 0.2.0.

add_formula(range_a1, formula, *, update=False)

Adds a formula to the given cell(s).

Note

From the Sheets API request documentation:

The formula’s ranges will automatically increment for each field in the range. For example, if writing a cell with formula =A1 into range B2:C4, B2 would be =A1, B3 would be =A2, B4 would be =A3, C2 would be =B1, C3 would be =B2, C4 would be =B3.

To keep the formula’s ranges static, use the $ indicator. For example, use the formula =$A$1 to prevent both the row and the column from incrementing.

Parameters:
  • range_a1 (str) – The cell range in A1 notation.

  • formula (str) – The formula.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

Adds a hyperlink to the given cell(s).

Note

text is a literal string to use as the label text, so any formulas in it will not be processed. To achieve that, use add_formula() with the HYPERLINK formula.

Parameters:
  • range_a1 (str) – The cell range in A1 notation.

  • link (str) – The link.

  • text (str) – The label text.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

resize(*, rows=None, cols=None)

Resizes the worksheet.

Non-positive values will be simply ignored (deleting all rows or columns is an error).

Parameters:
  • rows (int) – The number of rows.

  • cols (int) – The number of columns.

New in version 0.2.0.

bulk_format(*, freeze_rows=None, freeze_cols=None, hide_rows=None, hide_cols=None, row_heights=None, col_widths=None, range_formats=None, number_formats=None, merge_ranges=None, update=False)

Formats the worksheet in bulk.

For row_heights, each tuple should be the row number and the height. For col_widths, each tuple should be either the column number or letter and the width. Ranges are also accepted, such as "1:3" for rows or "A:E" for columns. Sizes less than 1 will be clamped to 1.

For hide_rows, each element should be the row number or a range of rows. For hide_cols, each element should be the column number, column letter, or a range of columns.

Parameters:
  • freeze_rows (int) – The number of rows to freeze.

  • freeze_cols (int) – The number of columns to freeze.

  • hide_rows (Iterable[Union[str, int]]) – The rows to hide.

  • hide_cols (Iterable[Union[str, int]]) – The columns to hide.

  • row_heights (Iterable[Tuple[Union[str, int], int]]) – The row heights to set.

  • col_widths (Iterable[Tuple[Union[str, int], int]]) – The column widths to set.

  • range_formats (Iterable[Tuple[str, Mapping]]) – Pairs of ranges and kwargs for format_cell().

  • number_formats (Iterable[Tuple[str, Mapping]]) – Pairs of ranges and kwargs for format_number_cell().

  • merge_ranges (Iterable[str]) – The ranges to merge.

  • update (bool) – Whether to update the worksheet.

See the other methods for possible exceptions raised.

New in version 0.2.0.

freeze(*, rows=None, cols=None, update=False)

Freezes a number of rows or columns.

Set the value to 0 to unfreeze all rows or columns.

Negative values will be simply ignored.

Parameters:
  • rows (int) – The number of rows to freeze.

  • cols (int) – The number of columns to freeze.

  • update (bool) – Whether to update the worksheet.

Raises:

gspread.exceptions.APIError – If all the visible rows or columns are frozen.

New in version 0.2.0.

hide_row(row, *, update=False)

Hides the given row(s).

Parameters:
  • row (Union[str, int]) – The row number or range.

  • update (bool) – Whether to update the worksheet.

Raises:

gspread.exceptions.APIError – If all the visible rows are hidden.

New in version 0.2.0.

hide_col(col_a1, *, update=False)

Hides the given column(s).

Parameters:
  • col_a1 (str) – The column range in A1 notation.

  • update (bool) – Whether to update the worksheet.

Raises:

gspread.exceptions.APIError – If all the visible columns are hidden.

New in version 0.2.0.

reset_row_height(row, *, update=False)

Resets the height of the given row(s) to DEFAULT_ROW_HEIGHT.

Parameters:
  • row (Union[str, int]) – The row number or range.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

set_row_height(row, height, *, update=False)

Sets the height of the given row(s).

Sizes less than 1 will be clamped to 1.

Parameters:
  • row (Union[str, int]) – The row number or range.

  • height (int) – The height.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

reset_col_width(col_a1, *, update=False)

Resets the width of the given column(s) to DEFAULT_COL_WIDTH.

Parameters:
  • col_a1 (str) – The column range in A1 notation.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

set_col_width(col_a1, width, *, update=False)

Sets the width of the given column(s).

Sizes less than 1 will be clamped to 1.

Parameters:
  • col_a1 (str) – The column range in A1 notation.

  • width (int) – The width.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

merge_cells(range_a1, *, merge_type=MergeType.MERGE_ALL, update=False)

Merges the given range of cells.

Parameters:
  • range_a1 (str) – The cell range in A1 notation.

  • merge_type (MergeType) – The merge type.

  • update (bool) – Whether to update the worksheet.

Raises:

New in version 0.2.0.

format_cell(range_a1, *, font_family=None, font_size=None, bold=None, italic=None, strikethrough=None, underline=None, background_color=None, text_color=None, text_align=None, vertical_align=None, wrap=None, update=False)

Formats the given cell(s).

Parameters:
  • range_a1 (str) – The cell range in A1 notation.

  • font_family (str) – The font family.

  • font_size (int) – The font size.

  • bold (bool) – Whether the text is bold.

  • italic (bool) – Whether the text is in italics.

  • strikethrough (bool) – Whether the text has a strikethrough.

  • underline (bool) – Whether the text is has an underline.

  • background_color (Color or Tuple[int, int, int] or Tuple[float, float, float]) – The background color.

  • text_color (Color or Tuple[int, int, int] or Tuple[float, float, float]) – The text color.

  • text_align (HorizontalAlign) – The text (horizontal) alignment type.

  • vertical_align (VerticalAlign) – The vertical alignment type.

  • wrap (WrapStrategy) – The wrapping type.

  • update (bool) – Whether to update the worksheet.

New in version 0.2.0.

format_number_cell(range_a1, fmt_type, pattern, *, update=False)

Formats the given number cell(s).

Parameters:

New in version 0.2.0.