From 21a9251b53b73f6ed3c12bb13953c0b880eda0f9 Mon Sep 17 00:00:00 2001 From: Karel Vaculik Date: Thu, 31 Aug 2023 08:34:46 +0200 Subject: [PATCH] Improved documentation of references --- docs/references.md | 18 ++-- mkdocs.yml | 2 +- pyreball/html.py | 221 ++++++++++++++++++++++++--------------------- 3 files changed, 131 insertions(+), 110 deletions(-) diff --git a/docs/references.md b/docs/references.md index e10afbf..3d06f4d 100644 --- a/docs/references.md +++ b/docs/references.md @@ -11,8 +11,9 @@ a plot ([`plot_graph()`](../api/pyreball_html/#pyreball.html.plot_graph)), or a heading ([`print_h1()`](../api/pyreball_html/#pyreball.html.print_h1), ..., [`print_h6()`](../api/pyreball_html/#pyreball.html.print_h6)). Each such function then creates a target for the link. -To create a source, just retrieve the string representation of the reference (i.e. use `__str__()` method), or invoke a -call on the reference object (i.e. use `__call__()` method). +To create a source, just retrieve the string representation of the reference (i.e. +use [`__str__()`](../api/pyreball_html/#pyreball.html.Reference.__str__) method), or invoke a +call on the reference object (i.e. use [`__call__()`](../api/pyreball_html/#pyreball.html.Reference.__call__) method). The following snippet demonstrates a very simple usage of a reference object. @@ -22,9 +23,11 @@ The following snippet demonstrates a very simple usage of a reference object. The code above creates a reference object with default link text `My Table` and the reference object is assigned to the table. -The code also creates three instances of the same link pointing to the table. `__str__()` method uses the default string +The code also creates three instances of the same link pointing to the +table. [`__str__()`](../api/pyreball_html/#pyreball.html.Reference.__str__) method uses the default string that we passed to the constructor. -The last link was created by `__call__()` method, which takes a parameter that is used to override the default link +The last link was created by [`__call__()`](../api/pyreball_html/#pyreball.html.Reference.__call__) method, which takes +a parameter that is used to override the default link text. When default link text is not provided through the constructor, Pyreball uses table numbers as texts for links pointing @@ -39,6 +42,7 @@ The artificial example below demonstrates some of these features. !!! note - Creating references explicitly through the constructor of `Reference` class allows us to use - the reference object even before the target object is created. This would not be possible if the references - were created by functions like [`print_table()`](../api/pyreball_html/#pyreball.html.print_table). \ No newline at end of file + Creating references explicitly through the constructor of [`Reference`](../api/pyreball_html/#pyreball.html.Reference) + class allows us to use the reference object even before the target object is created. + This would not be possible if the references were created by functions like + [`print_table()`](../api/pyreball_html/#pyreball.html.print_table). \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 7c80220..333de4c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -15,7 +15,7 @@ plugins: options: members_order: alphabetical separate_signature: true - filters: [ "!^_", "!print_html" ] + filters: [ "!^_", "!print_html", "__str__", "__call__" ] docstring_options: ignore_init_summary: true merge_init_into_class: true diff --git a/pyreball/html.py b/pyreball/html.py index fd7cffa..df7952f 100644 --- a/pyreball/html.py +++ b/pyreball/html.py @@ -73,20 +73,38 @@ class Reference: """ def __init__(self, default_text: Optional[str] = None) -> None: - """Create a new reference. + """ + Create a new reference. Args: - default_text: + default_text: Default text of the link. This text can be overriden by parameter of `__call__` method. + If not provided, Pyreball automatically inserts a text. For tables and images, their number is used. + For headings, their text is used. """ self.id = f"id{random.getrandbits(64)}" self.text = default_text def __str__(self) -> str: + """ + Create a link string. + + Returns: + Link string. + """ return ( f'{self.id if self.text is None else self.text}' ) - def __call__(self, text: str): + def __call__(self, text: str) -> str: + """ + Create a link string with given text. + + Args: + text: Text of the link. + + Returns: + Link string. + """ return f'{text}' @@ -197,15 +215,15 @@ def _print_heading(string: str, level: int = 1, reference: Optional[Reference] = # increase the number in the level _heading_memory["heading_counting"][level - 1] = ( - _heading_memory["heading_counting"][level - 1] + 1 + _heading_memory["heading_counting"][level - 1] + 1 ) # reset all sub-levels _heading_memory["heading_counting"][level:] = [0] * (6 - level) # get the string of the numbered section and append non-breakable space non_breakable_spaces = "\u00A0\u00A0" heading_number_str = ( - _get_heading_number(level, _heading_memory["heading_counting"]) - + non_breakable_spaces + _get_heading_number(level, _heading_memory["heading_counting"]) + + non_breakable_spaces ) else: heading_number_str = "" @@ -224,7 +242,7 @@ def _print_heading(string: str, level: int = 1, reference: Optional[Reference] = if get_parameter_value("html_file_path"): pilcrow_sign = "\u00B6" header_contents = ( - string + f'{pilcrow_sign}' + string + f'{pilcrow_sign}' ) # For correct functioning of references, it is expected that single line contains at most one heading, # and the heading is whole there with all links. @@ -232,7 +250,6 @@ def _print_heading(string: str, level: int = 1, reference: Optional[Reference] = _heading_memory["heading_index"] += 1 - def print_h1(string: str, reference: Optional[Reference] = None) -> None: """ Print h1 heading. @@ -300,11 +317,11 @@ def print_h6(string: str, reference: Optional[Reference] = None) -> None: def print_div( - *values: Any, - cl: ClParameter = None, - attrs: AttrsParameter = None, - sep: str = "", - end: str = "\n", + *values: Any, + cl: ClParameter = None, + attrs: AttrsParameter = None, + sep: str = "", + end: str = "\n", ) -> None: """ Print values into a div element. @@ -327,12 +344,12 @@ def print_div( def print_code_block( - *values: Any, - cl: ClParameter = None, - attrs: AttrsParameter = None, - sep: str = "", - end: str = "\n", - syntax_highlight: Optional[Literal["python"]] = "python", + *values: Any, + cl: ClParameter = None, + attrs: AttrsParameter = None, + sep: str = "", + end: str = "\n", + syntax_highlight: Optional[Literal["python"]] = "python", ) -> None: """ Print values as a source code into a preformatted block. @@ -382,7 +399,7 @@ def print(*values: Any, sep: str = "", end: str = "\n") -> None: def _prepare_caption_element( - prefix: str, caption: Optional[str], numbered: bool, index: int, anchor_link: str + prefix: str, caption: Optional[str], numbered: bool, index: int, anchor_link: str ) -> str: if numbered: caption_text = f"{prefix} {index}" @@ -398,16 +415,16 @@ def _prepare_caption_element( def _prepare_table_html( - df: "pandas.DataFrame", - caption: Optional[str] = None, - align: str = "center", - full_table: bool = True, - numbered: bool = True, - reference: Optional[Reference] = None, - sortable: bool = False, - tab_index: int = 0, - sorting_definition: Optional[Tuple[str, str]] = None, - **kwargs: Any, + df: "pandas.DataFrame", + caption: Optional[str] = None, + align: str = "center", + full_table: bool = True, + numbered: bool = True, + reference: Optional[Reference] = None, + sortable: bool = False, + tab_index: int = 0, + sorting_definition: Optional[Tuple[str, str]] = None, + **kwargs: Any, ) -> str: align_mapping = { "center": "centered", @@ -442,42 +459,42 @@ def _prepare_table_html( expander_id = "table-expander-" + str(tab_index) if full_table: table_html = ( - caption_element - + '
\n' - + table_html - + "\n
\n" + caption_element + + '
\n' + + table_html + + "\n
\n" ) table_html += ( - '" + '" ) else: table_html = ( - caption_element - + '
\n' - + table_html - + "\n
\n" + caption_element + + '
\n' + + table_html + + "\n
\n" ) table_html += ( - '
" + '
" ) table_html = ( - f'
' - + table_html - + "
" + f'
' + + table_html + + "
" ) table_html = '
' + table_html + "
" if sorting_definition: @@ -503,15 +520,15 @@ def _prepare_table_html( def print_table( - df: "pandas.DataFrame", - caption: Optional[str] = None, - reference: Optional[Reference] = None, - align: Optional[str] = None, - numbered: Optional[bool] = None, - full_table: Optional[bool] = None, - sortable: Optional[bool] = None, - sorting_definition: Optional[Tuple[str, str]] = None, - **kwargs: Any, + df: "pandas.DataFrame", + caption: Optional[str] = None, + reference: Optional[Reference] = None, + align: Optional[str] = None, + numbered: Optional[bool] = None, + full_table: Optional[bool] = None, + sortable: Optional[bool] = None, + sorting_definition: Optional[Tuple[str, str]] = None, + **kwargs: Any, ) -> None: """Print pandas DataFrame into HTML. @@ -589,25 +606,25 @@ def _construct_plot_anchor_link(reference: Optional[Reference], plot_ind: int) - def _wrap_plot_element_by_outer_divs(img_element: str, align: str, hidden: bool) -> str: img_element = ( - f'
' - + img_element - + "
" + f'
' + + img_element + + "
" ) if hidden: return ( - f'" + f'" ) else: return f'
' + img_element + "
" def _prepare_matplotlib_plot_element( - fig: "matplotlib.figure.Figure", - l_plot_index: int, - plot_format: Optional[str] = None, - embedded: Optional[bool] = None, + fig: "matplotlib.figure.Figure", + l_plot_index: int, + plot_format: Optional[str] = None, + embedded: Optional[bool] = None, ) -> str: if plot_format is not None and plot_format not in ["svg", "png"]: raise ValueError('Matplotlib format can be only "svg" or "png".') @@ -666,17 +683,17 @@ def _prepare_bokeh_plot_element(fig: "bokeh.plotting._figure.figure") -> str: def _prepare_image_element( - fig: FigType, - plot_index: int, - matplotlib_format: Optional[str] = None, - embedded: Optional[bool] = None, + fig: FigType, + plot_index: int, + matplotlib_format: Optional[str] = None, + embedded: Optional[bool] = None, ): # Create the html string according to the figure type. # (if we checked type of fig, we would have to add the libraries to requirements) if ( - type(fig).__name__ == "Figure" and type(fig).__module__ == "matplotlib.figure" + type(fig).__name__ == "Figure" and type(fig).__module__ == "matplotlib.figure" ) or ( - type(fig).__name__ == "PairGrid" and type(fig).__module__ == "seaborn.axisgrid" + type(fig).__name__ == "PairGrid" and type(fig).__module__ == "seaborn.axisgrid" ): img_element = _prepare_matplotlib_plot_element( fig=fig, @@ -695,8 +712,8 @@ def _prepare_image_element( ]: img_element = _prepare_altair_plot_element(fig=fig, l_plot_index=plot_index) elif ( - type(fig).__name__ == "Figure" - and type(fig).__module__ == "plotly.graph_objs._figure" + type(fig).__name__ == "Figure" + and type(fig).__module__ == "plotly.graph_objs._figure" ): img_element = _prepare_plotly_plot_element(fig=fig) elif type(fig).__name__.lower() == "figure" and type(fig).__module__ in [ @@ -711,14 +728,14 @@ def _prepare_image_element( def _plot_graph( - fig: FigType, - caption: Optional[str] = None, - reference: Optional[Reference] = None, - align: str = "center", - numbered: bool = True, - matplotlib_format: Optional[str] = None, - embedded: Optional[bool] = None, - hidden: bool = False, + fig: FigType, + caption: Optional[str] = None, + reference: Optional[Reference] = None, + align: str = "center", + numbered: bool = True, + matplotlib_format: Optional[str] = None, + embedded: Optional[bool] = None, + hidden: bool = False, ) -> None: if not get_parameter_value("html_file_path"): # only when we don't print to HTML @@ -761,13 +778,13 @@ def _plot_graph( def plot_graph( - fig: FigType, - caption: Optional[str] = None, - reference: Optional[Reference] = None, - align: Optional[str] = None, - numbered: Optional[bool] = None, - matplotlib_format: Optional[str] = None, - embedded: Optional[bool] = None, + fig: FigType, + caption: Optional[str] = None, + reference: Optional[Reference] = None, + align: Optional[str] = None, + numbered: Optional[bool] = None, + matplotlib_format: Optional[str] = None, + embedded: Optional[bool] = None, ) -> None: """ Plot a graph. @@ -812,10 +829,10 @@ def plot_graph( def plot_multi_graph( - figs: List[FigType], - captions: Optional[List[Optional[str]]] = None, - align: Optional[str] = None, - numbered: Optional[bool] = None, + figs: List[FigType], + captions: Optional[List[Optional[str]]] = None, + align: Optional[str] = None, + numbered: Optional[bool] = None, ) -> None: if captions is None: captions = [None] * len(figs)