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(), andis_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 bothbdataanddtype.
Validator classes map closely to Plotly schema valTypes and special runtime cases:
- Primitive validators:
BooleanValidator,NumberValidator,IntegerValidator,StringValidator,AnyValidator,AngleValidator,EnumeratedValidator,FlaglistValidator,SubplotidValidator, andLiteralValidator. These enforce type, min/max, enum, regex, extras, blank-string, or read-only constraints and optionally validate arrays whenarray_okis enabled.EnumeratedValidatoralso handles schema regex enum values and normalizes subplot anchors likex1toxfor matching anchor-style regexes. - Data/vector validators:
DataArrayValidatoraccepts array-like trace data;InfoArrayValidatorvalidates 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, andColorscaleValidatorvalidate CSS color strings, DDKvar(--*)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, andBaseTemplateValidatorbridge from raw dicts/scalars to generated graph object classes. They importplotly.graph_objsclasses lazily withimport_module()only whendata_classor trace classes are needed.TitleValidatormaps strings/numbers to{"text": value}before constructing title objects.BaseDataValidatorconverts trace dicts or trace objects into concrete trace classes using thetypefield, defaults missing type toscatter, preserves the input dict'stype, and can assign newuidvalues.BaseTemplateValidatoralso accepts registered template names or+-joined template names fromplotly.io.templatesand treats an explicitly empty template specially. - Runtime special cases:
DashValidatorextendsEnumeratedValidatorwith a regex for dash length lists, andImageUriValidatoraccepts 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:
- _plotly_utils/basevalidators.py
- _plotly_utils/exceptions.py
- _plotly_utils/importers.py
- _plotly_utils/__init__.py
- _plotly_utils/README.md
- tests/…/test_basevalidators.py (owned glob; no file at HEAD)
tests/test_core/test_graph_objs/**
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()orCompoundArrayValidator.data_classchanges in _plotly_utils/basevalidators.py, verify generated graph object package paths underplotly/graph_objs/**: compound validators lazily import classes from paths derived fromparent_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 raisingAttributeErrorwhile known relative modules/classes import lazily. - If
_validateorskip_invalidbehavior changes in graph object assignment paths, keep tests/…/test_validate.py and tests/…/test_figure.py aligned with validator behavior:_validate=Falsepreserves raw invalid data, whileskip_invalid=Truedrops 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()orto_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 restoringtype. If an exception path fails before restore, callers that reuse the same dict could observe a missingtype; 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_classbehavior. tests/…/test_thread_safety.py exists because concurrent first reads of compound properties can race; replacing thesetdefaultpattern or changing validator data-class caching can reintroduce detached duplicate children.