Plotly I/O rendering and export
Overview
This area is the public Plotly I/O subsystem surfaced through plotly/…/__init__.py. The module lazily exposes JSON conversion (to_json, from_json, read_json, write_json), HTML export (to_html, write_html), renderer configuration (renderers, show), templates (templates, to_templated), static image export (to_image, write_image, write_images, full_figure_for_development, defaults, get_chrome), and the Sphinx-Gallery scraper. Compatibility shim modules such as plotly/…/json.py, plotly/…/kaleido.py, plotly/…/base_renderers.py, and plotly/…/sg_scraper.py re-export selected private implementations.
JSON serialization is implemented in plotly/…/_json.py. Public figure-oriented calls first normalize inputs with plotly/io/_utils.py::validate_coerce_fig_to_dict, which accepts BaseFigure, dicts, and to_plotly_json() objects, optionally validating dicts through plotly.graph_objs.Figure. to_json() removes trace uid fields by default and delegates to to_json_plotly(). The JSON engine is controlled by the singleton JsonConfig.config: auto prefers orjson when installed and otherwise uses Python's json with _plotly_utils.utils.PlotlyJSONEncoder. The orjson path first tries native serialization with NumPy support, then falls back to clean_to_json_compatible() for Plotly objects, Sage scalars, NumPy arrays/datetimes, pandas Series/DatetimeIndex/NA values, decimals, and PIL images. Both engines sanitize unsafe script-breaking characters via _safe(). from_json_plotly() parses str or bytes; from_json() validates the output type with plotly/io/_utils.py::validate_coerce_output_type and constructs a go.Figure or go.FigureWidget. read_json() and write_json() accept strings, pathlib.Path, and file-like objects and use UTF-8 for path reads/writes.
HTML export is in plotly/…/_html.py. to_html() validates/coerces the figure, generates or accepts a div id, serializes data, layout, and frames with plotly.io.json.to_json_plotly, normalizes config with plotly.offline.offline._get_jconfig, defaults config responsive=True, and builds a Plotly.newPlot() script with optional Plotly.addFrames(), Plotly.animate(), and user post_script snippets. Width and height come from layout.width/layout.height, then layout.template.layout, then the supplied defaults; numeric values are converted to pixel strings and applied to the outer wrapper div. Plotly.js can be embedded from the bundled source (include_plotlyjs=True), referenced from the versioned CDN ('cdn'), referenced as plotly.min.js in the output directory ('directory'), referenced by a custom .js URL, or omitted. The CDN branch computes a SHA-256 Subresource Integrity hash from plotly.offline.offline.get_plotlyjs(). write_html() writes to a path or file-like object, copies the bundled plotly.min.js next to full HTML files when include_plotlyjs='directory', and can open the saved file in a browser.
Renderer registration and selection live in plotly/…/_renderers.py, with renderer classes in plotly/…/_base_renderers.py. The singleton renderers behaves like a dict and accepts only MimetypeRenderer or ExternalRenderer instances. renderers.default is a +-separated renderer string; setting it validates names, stores the renderer objects, and queues them for activation. show() validates/coerces a figure, builds a MIME bundle from matching MimetypeRenderers, displays it through IPython.display.display(raw=True) when non-empty, then invokes matching ExternalRenderers. Registered names include Plotly MIME renderers (plotly_mimetype, jupyterlab, nteract, vscode), HTML notebook renderers (notebook, notebook_connected, kaggle, azure, colab, cocalc, databricks), json, static image renderers (png, jpeg/jpg, svg, pdf), browser renderers (browser, firefox, chrome, chromium), iframe renderers, and Sphinx-Gallery renderers. The initial default honors PLOTLY_RENDERER, otherwise detects Colab/Kaggle/Azure/VSCode/nteract/CoCalc/Databricks/IPython terminal/ipykernel contexts, falling back to plotly_mimetype+notebook in IPython or browser when a system browser is available. renderers.render_on_display is enabled so figure display hooks can use the default MIME renderers.
Renderer classes in plotly/…/_base_renderers.py bridge I/O paths. JsonRenderer and PlotlyRenderer return JSON MIME bundles produced through to_json(..., validate=False, remove_uids=False). ImageRenderer subclasses call plotly.io.to_image() and return base64 PNG/JPEG/PDF or raw SVG MIME content. HtmlRenderer and its notebook/cloud subclasses call plotly.io.to_html() with notebook-appropriate Plotly.js and MathJax loading and, when activated globally, inject notebook initialization scripts. IFrameRenderer writes full HTML files under iframe_figures/ with write_html() and returns an iframe tag. BrowserRenderer renders full inline HTML and serves it once through an in-process HTTP server before opening it with webbrowser. DatabricksRenderer finds the notebook displayHTML function in outer frames. SphinxGalleryPngRenderer appends shown figure dicts to the module-level sphinx_gallery_figures queue for the scraper.
Templates and image defaults are separate global configuration objects. plotly/…/_templates.py creates a singleton templates whose built-ins are lazily loaded from JSON files in plotly/…/*.json using pkgutil.get_data('plotly', ...). Built-ins include plotly, plotly_white, plotly_dark, ggplot2, seaborn, simple_white, presentation, grid variants, and special none; plotly/…/__init__.py sets the default template to plotly on import. Template strings can combine names with +; merge_templates() merges left to right with rightmost precedence and cycles template trace defaults to a least-common-multiple length before update. to_templated() deep-copies a figure and moves styling properties into its layout template, skipping title/text and always skipping trace UIDs. Static image defaults are in plotly/…/_defaults.py: default_format='png', width 700, height 500, scale 1, optional mathjax, topojson, plotlyjs, and an OpenStreetMap policy header X-Requested-With: plotly.py.
Kaleido static export is implemented in plotly/…/_kaleido.py. kaleido_available() caches whether kaleido>=1.0.0 is importable. to_image() validates/coerces the figure, rejects EPS, resolves width/height from explicit arguments, layout, template layout, then defaults, and calls kaleido.calc_fig_sync() with image options, defaults.topojson, and kopts for configured Plotly.js, MathJax, and headers. Missing Kaleido raises an installation-focused RuntimeError; missing Chrome is translated from kaleido.errors.ChromeNotFoundError to a message pointing at plotly_get_chrome. write_image() infers format from the output path when omitted, requests image bytes before writing, and accepts paths or file-like objects. write_images() broadcasts scalar/list arguments with plotly/io/_utils.py::broadcast_args_to_dicts, prepares per-figure Kaleido specs, and uses kaleido.write_fig_from_object_sync() for batch export. full_figure_for_development() asks Kaleido/Plotly.js for JSON defaults and returns either a dict or go.Figure(skip_invalid=True). get_chrome() and plotly_get_chrome() wrap Kaleido's Chrome installer, validating user-specified install directories.
Sphinx-Gallery integration is in plotly/…/_sg_scraper.py and re-exported by plotly/…/sg_scraper.py. Importing the private module selects the sphinx_gallery_png renderer, whose renderer queues shown figures in plotly/io/_base_renderers.py::sphinx_gallery_figures. plotly_sg_scraper() consumes that queue plus a trailing BaseFigure expression captured by Sphinx-Gallery in block_vars['example_globals']['___']; shown figures are embedded inline as HTML via plotly.io.to_html(include_plotlyjs='cdn', full_html=False), while shown and repr figures are exported as PNG or SVG thumbnails when static export is available. The scraper probes static export once per process with _static_export_available(), starts a shared Kaleido browser with kaleido.start_sync_server() when possible, falls back to per-export browsers if the shared browser dies, and logs Sphinx-typed warnings when export is unavailable. It always clears the figure queue in a finally block to avoid cross-block leakage. reset_renderer() exists for parallel Sphinx-Gallery workers that need the renderer selected through reset_modules.
Package data under plotly/package_data/** is consumed by these flows rather than imported as Python. plotly/…/plotly.min.js and widgetbundle.js are bundled JavaScript assets used by offline/notebook/html rendering paths via plotly.offline.offline.get_plotlyjs() and related code. plotly/…/*.json are the lazy-loaded templates described above. plotly/package_data/datasets/*.csv.gz and *.geojson.gz are dataset assets outside the I/O implementation, but changes to package-data inclusion can still affect I/O because this subsystem relies on package resource loading.
Tests under tests/test_io/** cover the contracts most likely to regress. tests/…/test_to_from_json.py and test_to_from_plotly_json.py cover validation, UID removal, file/path encoding, output types, engine selection, NumPy/pandas/datetime/PIL-style cleaning, NaN/NA handling, byte parsing, and script-character sanitization. tests/…/test_html.py covers versioned CDN output, deterministic div_id, SRI hashes matching bundled Plotly.js, and wrapper dimensions. tests/…/test_renderers.py covers renderer defaults, MIME/external rendering, notebook initialization, browser one-shot serving, Sphinx-Gallery queueing, renderer validation, repr MIME bundles, and environment detection. tests/…/test_sg_scraper.py drives the real Sphinx-Gallery scraper API, including PNG/SVG output, thumbnail ordering, repr figures, bad formats, export-server fallback, missing static export, named scraper resolution, and reset hooks. tests/…/test_pathlib.py verifies HTML export accepts StringIO, pathlib.Path, and file descriptors; test_deepcopy_pickle.py protects graph object copy/pickle behavior that JSON/template flows depend on indirectly.
Coverage/routing
This doc owns:
plotly/io/**plotly/package_data/**tests/test_io/**
Coupling
- If plotly/…/*.json is renamed, removed, or repackaged, update plotly/…/_templates.py: built-in template names are hard-coded and loaded with
pkgutil.get_data('plotly', 'package_data/templates/<name>.json'), so packaging drift becomes a runtime template failure. - If the bundled Plotly.js asset or CDN versioning changes, verify plotly/…/_html.py, plotly/…/_base_renderers.py, and tests/…/test_html.py: CDN HTML includes an SRI hash generated from
get_plotlyjs(), and renderer repr tests compare that hash and URL. - If JSON serialization semantics change in plotly/…/_json.py, verify both HTML and renderer output: plotly/…/_html.py embeds serialized data/layout/frames directly into scripts, while
JsonRenderer,PlotlyRenderer, and image renderers in plotly/…/_base_renderers.py callto_json()orto_image()with validation disabled. - If renderer names or default-detection rules change in plotly/…/_renderers.py, update tests and any docs that name
PLOTLY_RENDERER: the default string is validated against registered names and may be a+-joined combination whose activation order determines notebook initialization behavior. - If Kaleido options/defaults change in plotly/…/_kaleido.py or plotly/…/_defaults.py, verify Sphinx-Gallery export in plotly/…/_sg_scraper.py: the scraper starts a shared Kaleido server with the same
defaults.plotlyjs,defaults.mathjax, anddefaults.headersassumptions used by per-image export. - If
show()orSphinxGalleryPngRendererchanges, verify plotly/…/_sg_scraper.py: the scraper depends on shown figures being appended tosphinx_gallery_figuresand then cleared after each block.
Risks
- plotly/…/_html.py embeds figure JSON inside executable script tags. If
_safe()behavior in plotly/…/_json.py stops escaping</script>-relevant characters or Unicode separators,to_html()can generate malformed or unsafe HTML;tests/test_io/test_to_from_plotly_json.py::test_sanitize_jsonis the regression guard. - plotly/…/_html.py and plotly/…/_base_renderers.py couple CDN output to a hash of bundled plotly.min.js. If
get_plotlyjs()content andplotly_cdn_url()version stop matching, browsers may reject the CDN script because the SRI hash is for different content; tests/…/test_html.py and renderer repr tests compute the expected hash from the bundle. - plotly/…/_sg_scraper.py keeps global state in
sphinx_gallery_figuresand_export_server_state. If cleanup inplotly_sg_scraper()is bypassed or the shared browser fallback state is mishandled, figures can leak between Sphinx-Gallery blocks or thumbnail generation can fail after one browser crash; tests/…/test_sg_scraper.py exercises both queue clearing and fallback.