Introducing a new way to review your PRs.

Read the announcement

plotly / plotly.py

The interactive graphing library for Python :sparkles:

View on GitHub

13 documents · Updated Nov 16, 2026

docs / validator-framework

Validator Framework

Overview

The core validation framework lives in _plotly_utils/basevalidators.py. It defines BaseValidator plus the concrete validator classes that generated Plotly graph objects use to validate, coerce, store, and present property values. _plotly_utils/README.md explains why these utilities are outside plotly/: they are shared by code generation and runtime and should avoid eager dependencies on the package being generated.

BaseValidator stores plotly_name, parent_name, role, and array_ok, and establishes the common contract: description() explains accepted values, validate_coerce(v) returns a stored representation or raises ValueError, and present(v) converts a stored representation back to a user-facing immutable-or-safe value. Its error helpers, raise_invalid_val() and raise_invalid_elements(), format ValueError messages with the offending property path and the validator's description().

The scalar and array validators in _plotly_utils/basevalidators.py share a few conversion helpers:

  • to_scalar_or_list() recursively converts tuples, numpy arrays, pandas series/indexes, Narwhals series, and numpy scalar-like values into Python scalars/lists where appropriate.
  • copy_to_readonly_numpy_array() converts homogeneous array-like values into contiguous read-only numpy arrays, optionally enforcing dtype kind and numeric-only content. It also adapts Narwhals series/dataframes and strips time zones from datetime columns before numpy conversion.
  • is_simple_array(), is_homogeneous_array(), and is_array() decide whether validators should treat a value as a Python list/tuple or a numpy/pandas/Narwhals-style homogeneous array.
  • Typed-array specs for Plotly.js are accepted by many validators through is_none_or_typed_array_spec() when a dict has both bdata and dtype.

Validator classes map closely to Plotly schema valTypes and special runtime cases:

  • Primitive validators: BooleanValidator, NumberValidator, IntegerValidator, StringValidator, AnyValidator, AngleValidator, EnumeratedValidator, FlaglistValidator, SubplotidValidator, and LiteralValidator. These enforce type, min/max, enum, regex, extras, blank-string, or read-only constraints and optionally validate arrays when array_ok is enabled. EnumeratedValidator also handles schema regex enum values and normalizes subplot anchors like x1 to x for matching anchor-style regexes.
  • Data/vector validators: DataArrayValidator accepts array-like trace data; InfoArrayValidator validates fixed/free-length 1D or 2D arrays by constructing nested validators from schema item definitions and rewriting item names while raising indexed errors.
  • Color validators: ColorValidator, ColorlistValidator, and ColorscaleValidator validate CSS color strings, DDK var(--*) syntax, optional numeric colors tied to a colorscale path, color lists, and named or explicit colorscales. ColorscaleValidator.present() returns immutable tuples of tuples.
  • Compound graph-object validators: CompoundValidator, TitleValidator, CompoundArrayValidator, BaseDataValidator, and BaseTemplateValidator bridge from raw dicts/scalars to generated graph object classes. They import plotly.graph_objs classes lazily with import_module() only when data_class or trace classes are needed. TitleValidator maps strings/numbers to {"text": value} before constructing title objects. BaseDataValidator converts trace dicts or trace objects into concrete trace classes using the type field, defaults missing type to scatter, preserves the input dict's type, and can assign new uid values. BaseTemplateValidator also accepts registered template names or +-joined template names from plotly.io.templates and treats an explicitly empty template specially.
  • Runtime special cases: DashValidator extends EnumeratedValidator with a regex for dash length lists, and ImageUriValidator accepts URI strings or converts PIL images to PNG data URIs if Pillow is importable.

Generated graph object classes, such as plotly/…/_scatter.py, expose Python properties whose setters call self["property"] = val; plotly/basedatatypes.py routes those assignments through validators. BasePlotlyType.__setitem__() distinguishes simple, compound, and compound-array validators, then delegates to _set_prop(), _set_compound_prop(), or _set_array_prop(). _set_prop() calls validator.validate_coerce() and stores the coerced value in _props; property reads call validator.present() so lists are commonly returned as tuples while stored JSON remains list-like. Figure construction in plotly/basedatatypes.py uses data, layout, and frame validators to coerce top-level traces, layout, and frames before reparenting graph objects to the figure.

Validator instances are loaded on demand rather than embedded in every generated class. plotly/validator_cache.py reads validator parameters from plotly/…/_validators.json, maps schema superclass names to classes in _plotly_utils/basevalidators.py, handles derived data/layout validators, and caches validators by (parent_path, prop_name). This means changes to validator constructor signatures or class names in _plotly_utils/basevalidators.py must remain compatible with the generated validator metadata.

_plotly_utils/importers.py provides a separate lazy-import helper, relative_import(parent_name, rel_modules=(), rel_classes=()), for generated package __init__ modules. It returns __all__, __getattr__, and __dir__; __getattr__ imports a relative submodule or a class/variable from a relative module only when that name is first accessed and raises AttributeError for unknown names. _plotly_utils/__init__.py is empty.

_plotly_utils/exceptions.py defines Plotly-specific exception types used around graph object validation and lookup: PlotlyError, PlotlyEmptyDataError, PlotlyGraphObjectError, PlotlyDictKeyError, PlotlyDictValueError, PlotlyListEntryError, PlotlyDataTypeError, and PlotlyKeyError. The validator classes themselves raise ValueError; graph object access in plotly/basedatatypes.py uses PlotlyKeyError for nicer invalid item access, while invalid assignment and coercion tests assert ValueError.

Tests under tests/test_core/test_graph_objs/** verify the integration points rather than each individual validator's full surface. tests/…/test_properties_validated.py confirms graph object attribute and item assignment call validators, invalid property names fail, data arrays are stored as lists but presented as tuples, compound arrays are presented as tuples of graph objects, and colorscales present as tuples of tuples. tests/…/test_validate.py checks _validate=False allows invalid figure data/layout through while _validate=True raises. tests/…/test_figure.py covers skip_invalid=True dropping invalid names/values across traces, layout, and frames. tests/…/test_figure_properties.py covers validation during nested path assignment and Plotly restyle/relayout/update helpers. tests/…/test_thread_safety.py protects lazy compound and compound-array first reads by ensuring concurrent readers share the same cached child object/list.

Coverage / Routing

This doc owns and should be routed for changes under:

Coupling

  • If a validator constructor, class name, or schema option handling changes in _plotly_utils/basevalidators.py, also verify plotly/validator_cache.py and the generated validator metadata in plotly/…/_validators.json: the cache instantiates classes by string name and passes params directly as keyword arguments.
  • If CompoundValidator.compute_graph_obj_module_str() or CompoundArrayValidator.data_class changes in _plotly_utils/basevalidators.py, verify generated graph object package paths under plotly/graph_objs/**: compound validators lazily import classes from paths derived from parent_name, with special remaps for frames and templates.
  • If present() behavior changes in _plotly_utils/basevalidators.py, verify graph object property expectations in tests/…/test_properties_validated.py: stored JSON and user-facing values intentionally differ for arrays, compound arrays, and colorscales.
  • If _plotly_utils/importers.py changes, verify generated package __init__ modules that assign __all__, __getattr__, and __dir__: callers depend on unknown names raising AttributeError while known relative modules/classes import lazily.
  • If _validate or skip_invalid behavior changes in graph object assignment paths, keep tests/…/test_validate.py and tests/…/test_figure.py aligned with validator behavior: _validate=False preserves raw invalid data, while skip_invalid=True drops invalid graph object properties instead of raising.

Risks

  • _plotly_utils/basevalidators.py contains many array branches that preserve numpy arrays as read-only while presenting simple arrays as tuples. If copy_to_readonly_numpy_array() or to_scalar_or_list() changes dtype or mutability behavior, tests/…/test_properties_validated.py can still pass for simple lists while numpy/pandas/Narwhals inputs regress in downstream validator paths.
  • BaseDataValidator.validate_coerce() in _plotly_utils/basevalidators.py mutates trace dicts temporarily by popping and restoring type. If an exception path fails before restore, callers that reuse the same dict could observe a missing type; the current code restores only after trace construction succeeds.
  • Lazy child initialization in plotly/basedatatypes.py depends on validators from _plotly_utils/basevalidators.py exposing stable data_class behavior. tests/…/test_thread_safety.py exists because concurrent first reads of compound properties can race; replacing the setdefault pattern or changing validator data-class caching can reintroduce detached duplicate children.