Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 29 additions & 28 deletions gptables/core/api.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import warnings
import pandas as pd
from pathlib import Path

from typing import Optional, Dict, Any, Union
from gptables.core.wrappers import GPWorkbook


def produce_workbook(
filename,
sheets,
theme=None,
cover=None,
contentsheet_label="Contents",
contentsheet_options={},
notes_table=None,
notesheet_label="Notes",
notesheet_options={},
auto_width=True,
gridlines="hide_all",
cover_gridlines=False,
):
filename: str,
sheets: Dict[str, "GPTable"],
theme: Optional["Theme"] = None,
cover: Optional["Cover"] = None,
contentsheet_label: str = "Contents",
contentsheet_options: Optional[Dict[str, Any]] = None,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default argument has been changed from empty dict to None, this caused fails in unit tests

notes_table: Optional[pd.DataFrame] = None,
notesheet_label: str = "Notes",
notesheet_options: Optional[Dict[str, Any]] = None,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above

auto_width: Union[bool, Dict[str, bool]] = True,
gridlines: str = "hide_all",
cover_gridlines: bool = False,
) -> "GPWorkbook":
"""
Produces a GPWorkbook, ready to be written to the specified `.xlsx` file
using the ``.close()`` method.
Expand Down Expand Up @@ -119,20 +120,20 @@ def produce_workbook(


def write_workbook(
filename,
sheets,
theme=None,
cover=None,
contentsheet=None,
contentsheet_label="Contents",
contentsheet_options={},
notes_table=None,
notesheet_label="Notes",
notesheet_options={},
auto_width=True,
gridlines="hide_all",
cover_gridlines=False,
):
filename: str,
sheets: Dict[str, "GPTable"],
theme: Optional["Theme"] = None,
cover: Optional["Cover"] = None,
contentsheet: Optional[str] = None,
contentsheet_label: str = "Contents",
contentsheet_options: Optional[Dict[str, Any]] = None,
notes_table: Optional[pd.DataFrame] = None,
notesheet_label: str = "Notes",
notesheet_options: Optional[Dict[str, Any]] = None,
auto_width: Union[bool, Dict[str, bool]] = True,
gridlines: str = "hide_all",
cover_gridlines: bool = False,
) -> None:
"""
Writes a GPWorkbook to the specified `.xlsx` file.

Expand Down
4 changes: 2 additions & 2 deletions gptables/core/cover.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def __init__(
contact: List = None,
cover_label: str = "Cover",
width: int = 85,
):
) -> None:

self.title = title
self.intro = self._parse_formatting(intro)
Expand All @@ -45,7 +45,7 @@ def __init__(
# TODO: Add input validation (e.g. empty list)

@staticmethod
def _parse_formatting(attribute):
def _parse_formatting(attribute) -> List:
"""Check attribute for a list. If there is a list then cast the list to a FormatList in attribute.

Parameters
Expand Down
93 changes: 48 additions & 45 deletions gptables/core/gptable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pandas as pd
from xlsxwriter.format import Format

from typing import List, Dict, Any, Optional, Union

class GPTable:
"""
Expand Down Expand Up @@ -46,19 +46,19 @@ class GPTable:

def __init__(
self,
table,
table_name,
title,
scope=None,
source=None,
units=None,
table_notes=None,
subtitles=[],
instructions="",
legend=[],
index_columns={2: 0},
additional_formatting=[],
):
table: pd.DataFrame,
table_name: str,
title: str,
scope: Optional[str] = None,
source: Optional[str] = None,
units: Optional[Dict[Any, Any]] = None,
table_notes: Optional[Dict[Any, Any]] = None,
subtitles: Optional[List[Any]] = None,
instructions: str = "",
legend: Optional[List[Any]] = None,
index_columns: Optional[Dict[int, int]] = None,
additional_formatting: Optional[List[Dict[str, Any]]] = None,
) -> None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default args for subtitles, legend, index column and additional formatting have been updated which might be causing test failures


# Attributes
self.title = None
Expand Down Expand Up @@ -102,8 +102,12 @@ def __init__(
self._set_data_range()

def set_table(
self, new_table, new_index_columns=None, new_units=None, new_table_notes=None
):
self,
new_table: pd.DataFrame,
new_index_columns: Optional[Dict[int, int]] = None,
new_units: Optional[Dict[Any, Any]] = None,
new_table_notes: Optional[Dict[Any, Any]] = None,
) -> None:
"""
Set the `table`, `index_columns`, `units` and `table_notes` attributes. Overwrites
existing values for these attributes.
Expand Down Expand Up @@ -138,7 +142,7 @@ def set_table(
new_table_notes = self.table_notes
self.set_table_notes(new_table_notes)

def set_index_columns(self, new_index_columns):
def set_index_columns(self, new_index_columns: Dict[int, int]) -> None:
"""
Set the `index_columns` attribute. Overwrites any existing values.
A dict must be supplied. This dict should map index level to a
Expand Down Expand Up @@ -184,21 +188,21 @@ def set_index_columns(self, new_index_columns):
)
raise ValueError(msg)

def _valid_column_index(self, column_index):
def _valid_column_index(self, column_index: int) -> bool:
"""
Check if `column_index` is valid, given the `table` shape.
"""
return column_index in range(self.table.shape[1])

def _set_column_headings(self): # TODO: check custom formatting in headers
def _set_column_headings(self)-> None: # TODO: check custom formatting in headers
"""
Sets the `column_headings` attribute to the set of column indexes that
are not assigned to `index_columns`.
"""
index_cols = set(self.index_columns.values())
self._column_headings = {x for x in range(self.table.shape[1])} - index_cols

def _validate_all_column_names_have_text(self):
def _validate_all_column_names_have_text(self) -> None:
"""
Validate that all column names in header row have text.
"""
Expand All @@ -212,15 +216,15 @@ def _validate_all_column_names_have_text(self):
msg = "Empty column name found in table data - column names must all have text"
raise ValueError(msg)

def _validate_no_duplicate_column_names(self):
def _validate_no_duplicate_column_names(self)-> None:
"""
Validate that there are no duplicate column names in table data.
"""
if len(self.table.columns) != len(set(self.table.columns)):
msg = "Duplicate column names found in table data - column names must be unique"
raise ValueError(msg)

def set_table_name(self, new_table_name):
def set_table_name(self, new_table_name: str) -> None:
"""
Set the `table_name` attribute.
"""
Expand All @@ -235,7 +239,7 @@ def set_table_name(self, new_table_name):
else:
self.table_name = new_table_name

def set_title(self, new_title):
def set_title(self, new_title: Any) -> None:
"""
Set the `title` attribute.
"""
Expand All @@ -246,7 +250,7 @@ def set_title(self, new_title):

self.title = new_title

def add_subtitle(self, new_subtitle):
def add_subtitle(self, new_subtitle: Any) -> None:
"""
Add a single subtitle to the existing list of `subtitles`.
"""
Expand All @@ -257,7 +261,7 @@ def add_subtitle(self, new_subtitle):

self.subtitles.append(new_subtitle)

def set_subtitles(self, new_subtitles, overwrite=True):
def set_subtitles(self, new_subtitles: Optional[List[Any]], overwrite: bool = True) -> None:
"""
Set a list of subtitles to the `subtitles` attribute. Overwrites
existing ist of subtitles by default. If `overwrite` is False, new list
Expand Down Expand Up @@ -287,7 +291,7 @@ def set_subtitles(self, new_subtitles, overwrite=True):
else:
self.subtitles += new_subtitles

def set_instructions(self, new_instructions):
def set_instructions(self, new_instructions: Any) -> None:
"""
Set `instructions` attribute.
"""
Expand All @@ -300,7 +304,7 @@ def set_instructions(self, new_instructions):
else:
self.instructions = new_instructions

def set_scope(self, new_scope):
def set_scope(self, new_scope: Any) -> None:
"""
Set the `scope` attribute.
"""
Expand All @@ -315,7 +319,7 @@ def set_scope(self, new_scope):

self.scope = new_scope

def set_units(self, new_units): # TODO: custom formatting in units?
def set_units(self, new_units: Optional[Dict[Any, Any]]) -> None: # TODO: custom formatting in units?
"""
Adds units to column headers.
Units should be in the format {column: units_text}. Column can be column name or 0-indexed column
Expand Down Expand Up @@ -361,7 +365,7 @@ def set_units(self, new_units): # TODO: custom formatting in units?

self.units = new_units

def _update_column_names_in_additional_formatting(self, col_names):
def _update_column_names_in_additional_formatting(self, col_names: Dict[Any, Any]) -> None:
"""
Parameters
----------
Expand All @@ -385,8 +389,7 @@ def _update_column_names_in_additional_formatting(self, col_names):
self.additional_formatting = formatting_list

def set_table_notes(
self, new_table_notes
): # TODO: custom formatting in column headers?
self, new_table_notes: Optional[Dict[Any, Any]]) -> None: # TODO: custom formatting in column headers?
"""
Adds note references to column headers.
`table_notes` should be in the format {column: "$$note_reference$$"}.
Expand Down Expand Up @@ -431,7 +434,7 @@ def set_table_notes(

self.table_notes = new_table_notes

def set_source(self, new_source):
def set_source(self, new_source: Any) -> None:
"""
Set the source attribute to the specified str.
"""
Expand All @@ -446,7 +449,7 @@ def set_source(self, new_source):

self.source = new_source

def add_legend(self, new_legend):
def add_legend(self, new_legend: Any) -> None:
"""
Add a single legend entry to the existing `legend` list.
"""
Expand All @@ -457,7 +460,7 @@ def add_legend(self, new_legend):

self.legend.append(new_legend)

def set_legend(self, new_legend, overwrite=True):
def set_legend(self, new_legend: Optional[List[Any]], overwrite: bool = True) -> None:
"""
Set a list of legend entries to the `legend` attribute. Overwrites
existing legend entries by default. If overwrite is False, new entries
Expand All @@ -481,7 +484,7 @@ def set_legend(self, new_legend, overwrite=True):
else:
self.legend += new_legend

def _set_annotations(self, description_order):
def _set_annotations(self, description_order: List[str]) -> None:
"""
Set a list of note references to the `_annotations` attribute.
"""
Expand All @@ -507,7 +510,7 @@ def _set_annotations(self, description_order):
# remove duplicates from ordered_refs and assign to self._annotations
self._annotations = list(dict.fromkeys(ordered_refs))

def _get_references_from_attr(self, data):
def _get_references_from_attr(self, data: Any) -> List[str]:
"""
Finds references in a string or list/dict of strings. Works
recursively on list elements and dict values. Other types are ignored.
Expand Down Expand Up @@ -540,7 +543,7 @@ def _get_references_from_attr(self, data):
return ordered_refs

# Deprecated as of v1.1.0 - instead use `table_notes` to add references to column headers
def _get_references_from_table(self):
def _get_references_from_table(self) -> List[str]:
"""
Get note references in the table column headings and index columns.
"""
Expand All @@ -561,7 +564,7 @@ def _get_references_from_table(self):
return ordered_refs

@staticmethod
def _get_references(string):
def _get_references(string: str) -> List[str]:
"""
Given a single string, return occurrences of note references (denoted by
flanking dollar signs [$$reference$$]).
Expand All @@ -583,7 +586,7 @@ def _get_references(string):

return ordered_refs

def set_additional_formatting(self, new_formatting):
def set_additional_formatting(self, new_formatting: List[Dict[str, Any]]) -> None:
"""
Set a dictionary of additional formatting to be applied to this table.
"""
Expand All @@ -603,7 +606,7 @@ def set_additional_formatting(self, new_formatting):

self.additional_formatting = new_formatting

def _validate_format_labels(self, format_list):
def _validate_format_labels(self, format_list: List[Dict[str, Any]]) -> None:
"""
Validate that format labels are valid property of XlsxWriter Format.
"""
Expand All @@ -618,7 +621,7 @@ def _validate_format_labels(self, format_list):
msg = f"`{label}` is not a valid XlsxWriter Format property"
raise ValueError(msg)

def _set_data_range(self):
def _set_data_range(self) -> None:
"""
Get the top-left and bottom-right cell reference of the table data.
"""
Expand Down Expand Up @@ -647,7 +650,7 @@ def _set_data_range(self):
]

@staticmethod
def _validate_text(obj, attr):
def _validate_text(obj: Any, attr: str) -> None:
"""
Validate that an object contains valid text elements. These are either
strings or list of strings and dictionaries.
Expand Down Expand Up @@ -680,11 +683,11 @@ class FormatList:
Dictionaries specify additional formatting to be applied to the following string.
"""

def __init__(self, list):
self.list = list
def __init__(self, items: List[Union[str, Dict[str, Any]]]) -> None:
self.list = items
self._set_string_property()

def _set_string_property(self):
def _set_string_property(self) -> None:
string = ""
for entry in self.list:
if isinstance(entry, str):
Expand Down
Loading
Loading