Skip to content

Commit

Permalink
Merge pull request #133 from rspencer01/add_typing
Browse files Browse the repository at this point in the history
Add further typing hints
  • Loading branch information
rspencer01 authored Jan 6, 2025
2 parents 19dc736 + 4720ea5 commit c94d010
Show file tree
Hide file tree
Showing 27 changed files with 619 additions and 354 deletions.
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.1
hooks:
- id: ruff-format
- id: ruff
3 changes: 3 additions & 0 deletions docs/source/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
[tool.ruff]
line-length = 88

[tool.ruff.lint]
ignore = ["ANN"]
4 changes: 2 additions & 2 deletions pybloqs/block/altair.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


class VegaAltairBlock(BaseBlock):
def __init__(self, contents, **kwargs):
def __init__(self, contents, **kwargs) -> None:
"""
A Block that renders Vega-Altair charts
"""
Expand All @@ -22,7 +22,7 @@ def __init__(self, contents, **kwargs):
super().__init__(**kwargs)
self._fig = contents

def _write_contents(self, container, *args, **kwargs):
def _write_contents(self, container, *args, **kwargs) -> None:
container.append(parse(self._fig.to_html(fullhtml=False)))


Expand Down
40 changes: 21 additions & 19 deletions pybloqs/block/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import uuid
import webbrowser
from io import BytesIO
from typing import Iterable, Optional, Tuple, Union
from typing import Any, Iterable, Iterator, Optional, Tuple, Union
from urllib.parse import urljoin

import pybloqs.htmlconv as htmlconv
Expand Down Expand Up @@ -38,7 +38,7 @@ def __init__(
classes: Union[str, Iterable[str]] = (),
anchor=None,
**kwargs,
):
) -> None:
self._settings = Cfg(
title=title,
title_level=title_level,
Expand All @@ -60,7 +60,7 @@ def render_html(
static_output: bool = False,
header_block: Optional["BaseBlock"] = None,
footer_block: Optional["BaseBlock"] = None,
):
) -> str:
"""
Returns html output of the block
Expand Down Expand Up @@ -142,7 +142,7 @@ def save(
footer_block: Optional["BaseBlock"] = None,
footer_spacing: Union[str, float] = 5,
**kwargs,
):
) -> str:
"""
Render and save the block. Depending on whether the filename or the format is
provided, the content will either be written out to a file or returned as a string.
Expand Down Expand Up @@ -212,7 +212,7 @@ def save(
)
return filename

def publish(self, name, *args, **kwargs):
def publish(self, name: str, *args, **kwargs) -> str:
"""
Publish the block so that others can access it.
Expand All @@ -235,7 +235,7 @@ def publish(self, name, *args, **kwargs):

def show(
self, fmt: str = "html", header_block: Optional["BaseBlock"] = None, footer_block: Optional["BaseBlock"] = None
):
) -> str:
"""
Show the block in a browser.
Expand Down Expand Up @@ -272,7 +272,7 @@ def email(
attachments=None,
convert_to_ascii: bool = True,
**kwargs,
):
) -> None:
"""
Send the rendered blocks as email. Each output format chosen will be added as an
attachment.
Expand Down Expand Up @@ -311,31 +311,31 @@ def email(
convert_to_ascii=convert_to_ascii,
)

def to_static(self):
def to_static(self) -> "BaseBlock":
return self._visit(lambda block: block._to_static())

def _to_static(self):
def _to_static(self) -> "BaseBlock":
"""
Subclasses can override this method to provide a static content version.
"""
return self

def _visit(self, visitor):
def _visit(self, visitor) -> Any:
"""
Calls the supplied visitor function on this block and any sub-blocks
:param visitor: Visitor function
:return: Return value of the visitor
"""
return visitor(self)

def _provide_default_cfg(self, defaults):
def _provide_default_cfg(self, defaults) -> None:
"""
Makes the supplied config to be part of the defaults for the block.
:param defaults: The default parameters that should be inherited.
"""
self._settings.default_cfg = self._settings.default_cfg.inherit(defaults)

def _combine_parent_cfg(self, parent_cfg):
def _combine_parent_cfg(self, parent_cfg) -> Cfg:
"""from pybloqs.config import user_config
Combine the supplied parent and the current Block's config.
Expand All @@ -353,7 +353,7 @@ def _combine_parent_cfg(self, parent_cfg):

return actual_cfg

def _get_styles_string(self, styles_cfg):
def _get_styles_string(self, styles_cfg) -> str:
"""
Converts the styles configuration to a CSS styles string.
Expand All @@ -371,7 +371,7 @@ def _get_styles_string(self, styles_cfg):
# Replace `_` with `-` and make values lowercase to get valid CSS names
return cfg_to_css_string(styles_cfg.override(sizing_cfg))

def _write_block(self, parent, parent_cfg, id_gen, resource_deps=None, static_output=False):
def _write_block(self, parent, parent_cfg, id_gen, resource_deps=None, static_output: bool = False) -> None:
"""
Writes out the block into the supplied stream, inheriting the parent_parameters.
Expand Down Expand Up @@ -400,7 +400,7 @@ def _write_block(self, parent, parent_cfg, id_gen, resource_deps=None, static_ou
self._write_title(container)
self._write_contents(container, actual_cfg, id_gen, resource_deps=resource_deps, static_output=static_output)

def _write_container_attrs(self, container, actual_cfg):
def _write_container_attrs(self, container, actual_cfg) -> None:
"""
Writes out the container attributes (styles, class, etc...).
Note that this method will only be called if the container tag is not `None`.
Expand All @@ -414,7 +414,7 @@ def _write_container_attrs(self, container, actual_cfg):

container["class"] = self._settings.classes

def _write_title(self, container):
def _write_title(self, container) -> None:
"""
Write out the title (if there is any).
Expand All @@ -428,7 +428,7 @@ def _write_title(self, container):
)
title.string = self._settings.title

def _write_anchor(self, container):
def _write_anchor(self, container) -> None:
"""
Write HTML anchor for linking within page
Expand All @@ -437,7 +437,9 @@ def _write_anchor(self, container):
if self._anchor is not None:
append_to(container, "a", name=self._anchor)

def _write_contents(self, container, actual_cfg, id_gen, resource_deps=None, static_output=None):
def _write_contents(
self, container, actual_cfg, id_gen: Iterator[str], resource_deps=None, static_output: Optional[bool] = None
) -> None:
"""
Write out the actual contents of the block. Deriving classes must override
this method.
Expand Down Expand Up @@ -488,6 +490,6 @@ class HRule(BaseBlock):
Draws a horizontal divider line.
"""

def _write_block(self, parent, *args, **kwargs):
def _write_block(self, parent, *_args, **_kwargs) -> None:
# Add a `hr` element to the parent
append_to(parent, "hr")
17 changes: 8 additions & 9 deletions pybloqs/block/convenience.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from collections.abc import Iterable
from typing import Optional
from typing import Any, Dict, Iterable, Optional, Type, Union

from pybloqs.block.base import BaseBlock
from pybloqs.block.text import Raw

_block_types = {}
_block_types: Dict[Type, Type[BaseBlock]] = {}


def add_block_types(objects, block_cls):
def add_block_types(objects: Union[Type, Iterable[Type]], block_cls: Type[BaseBlock]) -> None:
if not isinstance(objects, Iterable):
objects = [objects]
for o in objects:
Expand All @@ -16,13 +15,13 @@ def add_block_types(objects, block_cls):

# noinspection PyPep8Naming
def Block(
contents=None,
contents: Any = None,
title: Optional[str] = None,
title_level: int = 3,
title_wrap: bool = False,
inherit_cfg: bool = True,
**kwargs,
):
) -> BaseBlock:
"""
Constructs a composable layout element that will be rendered automatically by
IPython Notebooks. It can also be saved in HTML, PDF, PNG or JPEG formats.
Expand Down Expand Up @@ -71,15 +70,15 @@ def Block(
class _NestedBlock(BaseBlock):
container_tag = None

def __init__(self):
def __init__(self) -> None:
super().__init__(
title=title, title_level=title_level, title_wrap=title_wrap, inherit_cfg=inherit_cfg, **kwargs
)

def _to_static(self):
def _to_static(self) -> BaseBlock:
return contents._to_static()

def _write_contents(self, *sub_args, **sub_kwargs):
def _write_contents(self, *sub_args, **sub_kwargs) -> None:
contents._write_block(*sub_args, **sub_kwargs)

return _NestedBlock()
Expand Down
19 changes: 15 additions & 4 deletions pybloqs/block/data_tables.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from typing import List, Optional

import pandas as pd

from pybloqs.block.table import HTMLJinjaTableBlock
from pybloqs.block.table_formatters import (
TableFormatter,
Expand All @@ -13,13 +17,13 @@


class DataTablesCSSClass(TableFormatter):
def __init__(self, paging=True, searching=True, info=True):
def __init__(self, paging: bool = True, searching: bool = True, info: bool = True) -> None:
super().__init__()
self.paging = paging
self.searching = searching
self.info = info

def create_table_level_css_class(self):
def create_table_level_css_class(self) -> str:
no_paging = " dt-no-paging" if self.paging is False else ""
no_info = " dt-no-info" if self.info is False else ""
no_searching = " dt-no-searching" if self.searching is False else ""
Expand All @@ -36,8 +40,15 @@ class DataTablesHTMLJinjaTableBlock(HTMLJinjaTableBlock):
)

def __init__(
self, df, formatters=None, use_default_formatters=False, paging=True, searching=True, info=True, **kwargs
):
self,
df: pd.DataFrame,
formatters: Optional[List[TableFormatter]] = None,
use_default_formatters: bool = False,
paging: bool = True,
searching: bool = True,
info: bool = True,
**kwargs,
) -> None:
if formatters is None and use_default_formatters is False:
formatters = [
DataTablesCSSClass(paging, searching, info),
Expand Down
Loading

0 comments on commit c94d010

Please sign in to comment.