Skip to content

Commit 546394e

Browse files
committed
Add comments
1 parent d68b95d commit 546394e

3 files changed

Lines changed: 119 additions & 6 deletions

File tree

src/py/kaleido/_utils/fig_tools.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ class Spec(TypedDict):
5858
)
5959

6060

61-
# validation function
6261
def is_figurish(o: Any) -> TypeGuard[Figurish]:
62+
"""Detect if input is a plotly figure or equivalent."""
6363
# so if data isn't in the dict things get weird.
6464
valid = hasattr(o, "to_dict") or (isinstance(o, dict) and "data" in o)
6565
if not valid:
@@ -72,7 +72,8 @@ def is_figurish(o: Any) -> TypeGuard[Figurish]:
7272

7373

7474
def _coerce_format(extension: str) -> FormatString:
75-
# wrap this condition as a typeguard for typechecker's sake
75+
"""Satisfies a type checker that our format string is an accepted format."""
76+
7677
def is_fmt(s: str) -> TypeGuard[FormatString]:
7778
return s in SUPPORTED_FORMATS
7879

@@ -93,6 +94,14 @@ def coerce_for_js(
9394
path: Path | str | None,
9495
opts: LayoutOpts | None,
9596
) -> Spec:
97+
"""
98+
Package fig, path, and opts into a dictionary that javascript understands.
99+
100+
This will
101+
- validate the inputs
102+
- coerce the inputs if needed (eg. jpeg --> jpg)
103+
- provide defaults if we can
104+
"""
96105
if not is_figurish(fig): # VALIDATE FIG
97106
raise TypeError("Figure supplied doesn't seem to be a valid plotly figure.")
98107
if hasattr(fig, "to_dict"): # COERCE FIG

src/py/kaleido/_utils/path_tools.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717

1818
def _next_filename(path: Path | str, prefix: str, ext: str) -> str:
19+
"""Figure out proper suffix for generated file name."""
1920
path = path if isinstance(path, Path) else Path(path)
2021
default = 1 if (path / f"{prefix}.{ext}").exists() else 0
2122
re_number = re.compile(
@@ -37,6 +38,17 @@ def determine_path(
3738
fig: dict,
3839
ext: fig_tools.FormatString,
3940
) -> Path:
41+
"""
42+
Determine the filename by the algorithm described below.
43+
44+
If path is a directory (which exists), we try to create a filename from the
45+
chart title, or we use the word "fig". If we are generating these filenames,
46+
we check to see if a file with that name already exists and if so, we suffix
47+
our generated name with a number.
48+
49+
If we are given a full path name, we simple make sure that all the subdirs
50+
exist and we accept the user's argument.
51+
"""
4052
path = Path(path) if path else Path()
4153

4254
if not path.suffix or path.is_dir(): # they gave us a directory
@@ -62,6 +74,17 @@ def determine_path(
6274

6375

6476
def get_path(p: str | Path) -> Path:
77+
"""
78+
Ensure we have a path object.
79+
80+
Args:
81+
p: p might be a Path or a string, which might be a plain path: /path/to
82+
or a URI format: file:///path/to.
83+
84+
Returns:
85+
A coerced and parsed path, obeying operating system weirdness.
86+
87+
"""
6588
if isinstance(p, Path):
6689
return p
6790
elif not isinstance(p, str):
@@ -75,4 +98,5 @@ def get_path(p: str | Path) -> Path:
7598

7699

77100
def is_httpish(p: str) -> bool:
101+
"""Use urlparser to see if the path we've been given is a URL."""
78102
return urlparse(str(p)).scheme.startswith("http")

src/py/kaleido/kaleido.py

Lines changed: 84 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def __init__(
190190
self._saved_page_arg = page
191191

192192
async def open(self):
193-
"""Build page and temporary file if we need one, then opens browser."""
193+
"""Build page and temporary file if we need one, then open browser."""
194194
page = self._saved_page_arg
195195
del self._saved_page_arg
196196

@@ -423,7 +423,35 @@ async def write_fig_from_object(
423423
_write: bool = True, # backwards compatibility!
424424
stepper: bool = False,
425425
) -> None | bytes | tuple[Exception]:
426-
"""Temp."""
426+
"""
427+
Create one or more plotly figures from a specification dictionary.
428+
429+
If every figure needs a different `opts` or `path` argument, you use
430+
this instead of `write_fig`.
431+
432+
Args:
433+
fig_dicts:
434+
Any single figure dict, or an iterable of figure dictionaries. The
435+
figure dictionaries *must* have a "fig" key with a plotly figure or
436+
its dict representation. It can have the following keys: path, opts,
437+
and topojson. This is roughly equal to the `write_fig` arguments.
438+
439+
cancel_on_error (boolean, default: False):
440+
If False, any errors during rendering will be returned from the function
441+
call in a list. If True, any error will be raised immediately and the
442+
rest of the renders will be cancelled.
443+
444+
stepper (boolean, default False):
445+
This is a debugging argument and is not part of the stable API.
446+
If set to true, kaleido will wait for a key press to render each
447+
image, in case one would want to inspect the browser environment.
448+
449+
Returns:
450+
If cancel_on_error is True, it always returns None on success.
451+
If cancel_on_error is False, it always returns a tuple, possibly
452+
with errors.
453+
454+
"""
427455
if not _write:
428456
cancel_on_error = True
429457

@@ -479,7 +507,51 @@ async def write_fig( # noqa: PLR0913
479507
cancel_on_error: bool = False,
480508
stepper: bool = False,
481509
) -> tuple[Exception] | None:
482-
"""Temp."""
510+
"""
511+
Create one or more plotly figures.
512+
513+
While fig may be an iterable, only a single path and opts may be passed.
514+
Use write_fig_from_object if you need to specify different paths or opts
515+
for each figure.
516+
517+
Args:
518+
fig:
519+
A plotly figure or its dict representation. It can have the
520+
following keys: path, opts, and topojson. This is roughly equal
521+
to the `write_fig` arguments.
522+
523+
path (None, Path, str):
524+
The path where the image will be written. The default is the
525+
current directory. If a filename isn't specified, we try to
526+
generate one from the title or use a default "fig-". If you
527+
pass many figures, this argument should be a directory.
528+
529+
opts (None, LayoutOpts dict):
530+
The layout options are a dictionary with the following optional keys:
531+
- scale: a number to multiply the image by.
532+
- width: a number to set the pixel width.
533+
- height: a number to set the pixel height.
534+
- format: One of jpg, png, svg, pdf, json, or webp.
535+
536+
topojson:
537+
An optional json-format map specification when using geomaps.
538+
539+
cancel_on_error (boolean, default: False):
540+
If False, any errors during rendering will be returned from the function
541+
call in a list. If True, any error will be raised immediately and the
542+
rest of the renders will be cancelled.
543+
544+
stepper (boolean, default False):
545+
This is a debugging argument and is not part of the stable API.
546+
If set to true, kaleido will wait for a key press to render each
547+
image, in case one would want to inspect the browser environment.
548+
549+
Returns:
550+
If cancel_on_error is True, it always returns None on success.
551+
If cancel_on_error is False, it always returns a tuple, possibly
552+
with errors.
553+
554+
"""
483555
if fig_tools.is_figurish(fig) or not isinstance(
484556
fig,
485557
(Iterable, AsyncIterable),
@@ -511,7 +583,15 @@ async def calc_fig(
511583
topojson: str | None = None,
512584
stepper: bool = False,
513585
) -> bytes:
514-
"""Temp."""
586+
"""
587+
Run write_fig but instead of writing a file, return the bytes.
588+
589+
The arguments are the same as write_fig, but path does nothing.
590+
591+
Returns:
592+
The calculated bytes.
593+
594+
"""
515595
if path is not None:
516596
warnings.warn(
517597
"The path argument is deprecated in `kaleido.calc_fig`. "

0 commit comments

Comments
 (0)