Codegen Schema Pipeline
Overview
The schema code generation pipeline turns the vendored Plotly.js schema at codegen/…/plot-schema.json into the runtime graph object package, figure classes, and validator metadata under plotly/. Its command entrypoint is commands.py: python commands.py codegen calls codegen.perform_codegen(outdir, noformat=args.noformat) with outdir set to plotly, while format and lint call codegen.reformat_code() and codegen.lint_code() over the generated output paths. The Plotly.js update commands in commands.py also feed this pipeline: updateplotlyjs downloads plotly.min.js and plot-schema.json from the npm package, verifies the tarball integrity, writes codegen/…/plot-schema.json, then runs perform_codegen; updateplotlyjsdev copies the same artifacts from a local Plotly.js repository before running perform_codegen.
codegen/__init__.py orchestrates generation. perform_codegen() deletes the previous plotly/validators and plotly/graph_objs directories, loads codegen/…/plot-schema.json, and mutates the in-memory schema through preprocess_schema(). That preprocessing injects a codegen-friendly layout.template subtree for every trace type and renames Sankey link concentrationscales items to colorscale when present. It then builds schema node trees for traces, layout, and frames using TraceNode, LayoutNode, and FrameNode from codegen/utils.py.
codegen/utils.py is the schema interpretation layer. PlotlyNode normalizes schema paths, Python class names, property names, validator superclass names, child datatype discovery, and docstring text. TraceNode reads plotly_schema["traces"], LayoutNode combines layout.layoutAttributes with per-trace layoutAttributes via ChainMap and folds barpolar layout attributes into layout["polar"], and FrameNode reads plotly_schema["frames"] while mapping the schema's frames_entry path to the public frame name. ElementDefaultsNode adds template defaults objects such as layout.annotationdefaults; MappedPropNode preserves deprecated title-style properties such as layout.title_font by mapping them to the newer nested title properties.
Validator generation is data-driven rather than one Python class per validator. codegen/validators.py walks every layout, trace, frame, and root data node, asks each PlotlyNode for constructor kwargs and a base validator class name, and writes the result to plotly/…/_validators.json. That JSON maps fully qualified property paths such as layout.yaxis.zerolinewidth to { "superclass": "NumberValidator", "params": ... }. At runtime, plotly/validator_cache.py loads plotly/…/_validators.json, instantiates classes from _plotly_utils.basevalidators, and handles derived aliases for DataValidator and LayoutValidator; generated graph object classes then request validators through ValidatorCache.get_validator(...) in their base datatype behavior.
Graph object datatype generation happens in codegen/datatypes.py. For each compound non-defaults node, write_datatype_py() writes plotly/…/_<name>.py. build_datatype_py() emits classes that inherit the appropriate runtime base (BaseTraceType, BaseTraceHierarchyType, BaseLayoutType, BaseLayoutHierarchyType, or BaseFrameHierarchyType as chosen by the node subclass), defines _parent_path_str, _path_str, _valid_props, property getters/setters, constructor signatures, property docstrings, literal type handling, and _mapped_properties for deprecated mapped title properties. Template trace/layout nodes are special-cased to import their corresponding public graph object classes instead of duplicating class definitions.
Figure class generation is handled by codegen/figure.py. write_figure_classes() writes both plotly/…/_figure.py and plotly/…/_figurewidget.py from the same schema-derived inputs. Generated Figure and FigureWidget classes inherit BaseFigure and BaseFigureWidget, wrap core mutator methods to return the concrete figure type, create add_<trace>() methods for every trace type, generate subplot selector/update helpers for layout subplot objects, and generate add/select/update helpers for layout arrays that have xref and yref such as annotations, shapes, and images.
Compatibility artifacts are generated by codegen/compatibility.py and the tail of codegen/__init__.py. write_deprecated_datatypes() writes plotly/…/_deprecations.py containing deprecated list/dict stand-ins such as Data, Marker, and XAxis that warn and point users to modern graph object types. write_graph_objs_graph_objs() writes plotly/…/graph_objs.py as a legacy from plotly.graph_objs import * module. perform_codegen() writes package __init__.py files through write_init_py()/build_from_imports_py(), using _plotly_utils.importers.relative_import for lazy runtime imports and adding a custom lazy FigureWidget branch that falls back to plotly.missing_anywidget.FigureWidget when ipywidgets is unavailable or too old. It also writes plotly/…/__init__.py as an alias surface over top-level plotly.graph_objs classes and modules.
Generated files all carry the CAVEAT string from codegen/utils.py, and perform_codegen() reformats the generated validator, graph object, and graph object alias paths with ruff format unless --noformat is passed. write_source_py() appends generated source after creating parent directories, so the orchestrator's initial removal of plotly/graph_objs and plotly/validators is what prevents stale/generated duplicate content during a full run.
Coverage / Routing
This doc owns:
codegen/**- commands.py
- plotly/…/_validators.json
Route changes here when they alter the schema resource, schema node interpretation, code generation entrypoints, generated graph object or figure output, validator JSON production, or compatibility/lazy-import artifacts.
Coupling
- If codegen/…/plot-schema.json changes shape, verify
PlotlyNode,TraceNode,LayoutNode, andFrameNodein codegen/utils.py: they hard-code schema roots liketraces,layout.layoutAttributes,frames, traceattributes, and tracelayoutAttributes, and generation will fail or silently omit properties if those paths drift. - If validator constructor parameters or class names change in
_plotly_utils.basevalidators, updatePlotlyNode.get_validator_params()andPlotlyNode.name_base_validatorin codegen/utils.py plus plotly/validator_cache.py; the generated plotly/…/_validators.json stores only superclass names and kwargs, and runtime validation depends onValidatorCacheresolving those names correctly. - If generated graph object base classes change in
plotly.basedatatypesorplotly.basewidget, update the nodename_base_datatypeimplementations in codegen/utils.py and figure generation in codegen/figure.py; generated classes import those bases directly and delegate constructor/property behavior to them. - If commands.py changes Plotly.js update behavior, verify both
update_bundle_schema()andupdate_schema_bundle_from_local(): the former writes codegen/…/plot-schema.json from the npm tarball and the latter writes it from dist/plot-schema.json, and both must leave the schema resource ready forperform_codegen(). - If package import behavior changes, update
build_from_imports_py()in codegen/utils.py and theoptional_figure_widget_importblock in codegen/__init__.py; generated plotly/…/__init__.py and plotly/…/__init__.py rely on the same lazy import helper and FigureWidget fallback logic. - If deprecated title properties or template defaults change in the schema, verify
MappedPropNode,ElementDefaultsNode, andbuild_datatype_py()together: the former two synthesize nodes that are not direct schema objects, while generated datatype constructors and_mapped_propertiesmake those compatibility properties usable at runtime.
Risks
- codegen/utils.py and codegen/validators.py use
eval()on repr-like validator parameter strings before writing or instantiating validators. If untrusted schema content reaches codegen/…/plot-schema.json, code generation can execute it; keep schema updates limited to verified Plotly.js artifacts from commands.py or trusted local builds. perform_codegen()in codegen/__init__.py deletesplotly/validatorsandplotly/graph_objsbefore loading and processing the schema. If schema loading or generation fails after deletion, the working tree is left without those generated runtime packages until codegen is rerun successfully.write_source_py()in codegen/utils.py opens generated Python files in append mode. If a caller writes a generated file without first removing the old generated tree, the new content can be appended to stale content;perform_codegen()avoids this only forplotly/validatorsandplotly/graph_objs, while one-off generator calls must clean their targets themselves.