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
Courseif 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,
coursewill be passed asNone, 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
CourseandAssignmentif 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,
courseandassignmentwill both be passed asNone, 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:
- Returns:
The course.
- Return type:
- 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:
- Returns:
A string representation of the course.
- Return type:
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:
- Returns:
The roster.
- Return type:
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:
- Returns:
The assignment.
- Return type:
- 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.Spreadsheetinto an instance of theSpreadsheetwrapper.- Parameters:
spreadsheet (
gspread.spreadsheet.Spreadsheet) –- Return type:
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:
- Returns:
The valid title.
- Return type:
- Raises:
ValueError – If
fmtis invalid.
- add_worksheet(title='Sheet', *, rows=1, cols=1, index=None)
Adds a new worksheet to the spreadsheet.
If
indexis given, the worksheet will be inserted before the given 0-indexed index. For example,index = 0will insert the worksheet at the very beginning, andindex = 1will insert the worksheet between the first and second sheets. Ifindexis not given, the worksheet will be added at the end.- Parameters:
- Returns:
The worksheet.
- Return type:
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:
- 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:
- 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_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 fromgspread.
New in version 0.2.0.
- update()
Updates the Google Sheet with the cached requests.
Any method with
updateset to False will cache its request. If a method doesn’t have theupdatekeyword 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:
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:
- 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
=A1into 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$1to prevent both the row and the column from incrementing.- Parameters:
New in version 0.2.0.
- add_hyperlink(range_a1, link, text=None, *, update=False)
Adds a hyperlink to the given cell(s).
Note
textis a literal string to use as the label text, so any formulas in it will not be processed. To achieve that, useadd_formula()with theHYPERLINKformula.- Parameters:
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).
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. Forcol_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. Forhide_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 forformat_cell().number_formats (
Iterable[Tuple[str, Mapping]]) – Pairs of ranges and kwargs forformat_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:
- 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:
- 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:
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:
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:
New in version 0.2.0.
- merge_cells(range_a1, *, merge_type=MergeType.MERGE_ALL, update=False)
Merges the given range of cells.
- Parameters:
- Raises:
gspread.exceptions.APIError – If frozen and non-frozen cells are merged together.
gspread.exceptions.APIError – If the merge fails, such as if the given range includes already merged cells.
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 (
ColororTuple[int, int, int]orTuple[float, float, float]) – The background color.text_color (
ColororTuple[int, int, int]orTuple[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:
range_a1 (
str) – The cell range.fmt_type (
NumberFormatType) – The format type.pattern (
str) – The formatting pattern. See https://developers.google.com/sheets/api/guides/formats.update (
bool) – Whether to update the worksheet.
New in version 0.2.0.