Skip to content

Commit

Permalink
style: convert docstrings to numpy format
Browse files Browse the repository at this point in the history
  • Loading branch information
juba committed May 24, 2024
1 parent 1edb912 commit a3f79ba
Show file tree
Hide file tree
Showing 6 changed files with 320 additions and 165 deletions.
51 changes: 33 additions & 18 deletions src/pyobsplot/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,26 @@

import pandas as pd
import polars as pl
import pyarrow as pa
import pyarrow.feather as pf


def serialize(data: Any, renderer: str) -> Any:
"""Serialize a data object.
"""
Serialize a data object.
Args:
data (Any): data object to serialize.
renderer (str): renderer.
Parameters
----------
data : Any
data object to serialize.
renderer : str
renderer type.
Returns:
Any: serialized data object.
Returns
-------
Any
serialized data object.
"""

# If polars DataFrame, serialize to Arrow IPC
if isinstance(data, pl.DataFrame):
value = pl_to_arrow(data)
Expand All @@ -40,29 +46,38 @@ def serialize(data: Any, renderer: str) -> Any:


def pd_to_arrow(df: pd.DataFrame) -> bytes:
"""Convert a pandas DataFrame to Arrow IPC bytes.
"""
Convert a pandas DataFrame to Arrow IPC bytes.
Args:
df (pd.DataFrame): pandas DataFrame to convert.
Parameters
----------
df : pd.DataFrame
pandas DataFrame to convert.
Returns:
bytes: Arrow IPC bytes
Returns
-------
bytes
Arrow IPC bytes.
"""
f = io.BytesIO()
df.to_feather(f, compression="uncompressed")
return f.getvalue()


def pl_to_arrow(df: pl.DataFrame) -> bytes:
"""Convert a polars DataFrame to Arrow IPC bytes.
"""
Convert a polars DataFrame to Arrow IPC bytes.
Args:
df (pl.DataFrame): polars DataFrame to convert.
Parameters
----------
df : pl.DataFrame
polars DataFrame to convert.
Returns:
bytes: Arrow IPC bytes.
Returns
-------
bytes
Arrow IPC bytes.
"""

f = io.BytesIO()
pf.write_feather(df.to_arrow(), f, compression="uncompressed")
return f.getvalue()
33 changes: 23 additions & 10 deletions src/pyobsplot/js_modules.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from functools import partial
from typing import Callable, Optional
from typing import Callable

from pyobsplot.obsplot import ObsplotJsdomCreator, ObsplotWidgetCreator
from pyobsplot.utils import PLOT_METHODS
Expand All @@ -11,10 +11,12 @@


class Plot:
"""Plot methods class."""
"""
Plot methods class.
"""

@staticmethod
def plot(*args, **kwargs) -> Optional[ObsplotWidget]:
def plot(*args, **kwargs) -> ObsplotWidget | None:
"""
Plot.plot static method. If called directly, create an ObsplotWidget
or an ObpsplotJsdom with args and kwargs.
Expand All @@ -29,11 +31,14 @@ def plot(*args, **kwargs) -> Optional[ObsplotWidget]:


def method_to_spec(*args, **kwargs) -> dict:
"""Function used for creating Plot.xyz static methods.
"""
Function used for creating Plot.xyz static methods.
Generates a dict of specification with method name and args.
Returns:
dict: Plot function specification.
Returns
-------
dict
Plot function specification.
"""
name = kwargs["name"]
if len(kwargs) > 1:
Expand All @@ -55,10 +60,14 @@ def method_to_spec(*args, **kwargs) -> dict:


class JSModule(type):
"""metaclass to allow JavaScript module and methods handling."""
"""
Metaclass to allow JavaScript module and methods handling.
"""

def __getattr__(cls: type, name: str) -> Callable:
"""Intercept methods calling and returns a parsed and typed dict object."""
"""
Intercept methods calling and returns a parsed and typed dict object.
"""

def wrapper(*args, **kwargs) -> dict:
if kwargs:
Expand All @@ -75,12 +84,16 @@ def wrapper(*args, **kwargs) -> dict:


class d3(metaclass=JSModule): # noqa: N801
"""JSModule class to allow d3 objects in specification."""
"""
JSModule class to allow d3 objects in specification.
"""

pass


class Math(metaclass=JSModule):
"""JSModule class to allow Math objects in specification."""
"""
JSModule class to allow Math objects in specification.
"""

pass
47 changes: 30 additions & 17 deletions src/pyobsplot/jsdom.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import json
import warnings
from typing import Any, Optional, Union
from typing import Any

import requests
from IPython.display import HTML, SVG
Expand All @@ -16,26 +16,34 @@


class ObsplotJsdom:
"""Obsplot JSDom class.
The class takes a plot specification as input and generates a plot as SVG or HTML
by calling a JSDom script with node.
The specification can be given as a dict, a Plot function call or as
Python kwargs.
"""

def __init__(
self,
*,
spec: Any,
port: int,
theme: str = DEFAULT_THEME,
default: Optional[dict] = None,
debug: bool = False, # noqa: FBT002, FBT001
default: dict | None = None,
debug: bool = False,
) -> None:
"""
Constructor. Parse the spec given as argument.
Obsplot JSDom class. The class takes a plot specification as input and generates
a plot as SVG or HTML by calling a JSDom script with node.
Parameters
----------
spec : Any
Plot specification as dict, Plot function call or Python kwargs.
port : int
port number of the jsdom server.
theme : {'light', 'dark', 'current'}, optional
color theme to use, by default 'light'
default : dict, optional
dict of default spec values, by default None
debug : bool, optional
activate debug mode, by default False
"""

# Create parser
parser = SpecParser(renderer="jsdom", default=default)
# Parse spec code
Expand All @@ -47,10 +55,13 @@ def __init__(
self.port = port
self.theme = theme

def plot(self) -> Union[SVG, HTML]:
"""Generates the plot by sending request to http node server.
def plot(self) -> SVG | HTML:
"""
Generates the plot by sending request to http node server.
Returns:
Returns
-------
HTML | SVG
Either an HTML or SVG IPython.display object.
"""

Expand All @@ -63,8 +74,10 @@ def plot(self) -> Union[SVG, HTML]:
timeout=600,
)
except ConnectionRefusedError:
msg = f"""Error: can't connect to generator server on port {self.port}.
Please recreate your generator object."""
msg = (
f"Error: can't connect to generator server on port {self.port}.\n"
f"Please recreate your generator object."
)
warnings.warn(msg, stacklevel=1)
# Read back result
if r.status_code == HTTP_SERVER_ERROR: # type: ignore
Expand Down
Loading

0 comments on commit a3f79ba

Please sign in to comment.