forked from vega/altair
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_schema_wrapper.py
1405 lines (1190 loc) · 46.3 KB
/
generate_schema_wrapper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Generate a schema wrapper from a schema."""
from __future__ import annotations
import argparse
import copy
import json
import sys
import textwrap
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from itertools import chain
from operator import attrgetter
from pathlib import Path
from typing import TYPE_CHECKING, Any, Final, Generic, Literal, TypeVar
from urllib import request
if sys.version_info >= (3, 14):
from typing import TypedDict
else:
from typing_extensions import TypedDict
import vl_convert as vlc
sys.path.insert(0, str(Path.cwd()))
from tools.codemod import ruff
from tools.markup import rst_syntax_for_class
from tools.schemapi import CodeSnippet, SchemaInfo, arg_kwds, arg_required_kwds, codegen
from tools.schemapi.utils import (
RemapContext,
SchemaProperties,
TypeAliasTracer,
finalize_type_reprs,
get_valid_identifier,
import_type_checking,
import_typing_extensions,
indent_docstring,
resolve_references,
spell_literal,
)
from tools.vega_expr import write_expr_module
from tools.versioning import VERSIONS
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
from tools.schemapi.codegen import ArgInfo, AttrGetter
from vl_convert import VegaThemes
T = TypeVar("T", bound="str | Iterable[str]")
SCHEMA_VERSION: Final = VERSIONS["vega-lite"]
HEADER_COMMENT = """\
# The contents of this file are automatically written by
# tools/generate_schema_wrapper.py. Do not modify directly.
"""
HEADER: Final = f"""{HEADER_COMMENT}
from __future__ import annotations\n
"""
SCHEMA_URL_TEMPLATE: Final = "https://vega.github.io/schema/{library}/{version}.json"
VL_PACKAGE_TEMPLATE = (
"https://raw.githubusercontent.com/vega/vega-lite/refs/tags/{version}/package.json"
)
SCHEMA_FILE = "vega-lite-schema.json"
THEMES_FILE = "vega-themes.json"
EXPR_FILE: Path = (
Path(__file__).parent / ".." / "altair" / "expr" / "__init__.py"
).resolve()
CHANNEL_MYPY_IGNORE_STATEMENTS: Final = """\
# These errors need to be ignored as they come from the overload methods
# which trigger two kind of errors in mypy:
# * all of them do not have an implementation in this file
# * some of them are the only overload methods -> overloads usually only make
# sense if there are multiple ones
# However, we need these overloads due to how the propertysetter works
# mypy: disable-error-code="no-overload-impl, empty-body, misc"
"""
BASE_SCHEMA: Final = """
class {basename}(SchemaBase):
_rootschema = load_schema()
@classmethod
def _default_wrapper_classes(cls) -> Iterator[type[Any]]:
return _subclasses({basename})
"""
LOAD_SCHEMA: Final = '''
def load_schema() -> dict:
"""Load the json schema associated with this module's functions"""
schema_bytes = pkgutil.get_data(__name__, "{schemafile}")
if schema_bytes is None:
raise ValueError("Unable to load {schemafile}")
return json.loads(
schema_bytes.decode("utf-8")
)
'''
CHANNEL_MIXINS: Final = """
class FieldChannelMixin:
_encoding_name: str
def to_dict(
self,
validate: bool = True,
ignore: list[str] | None = None,
context: dict[str, Any] | None = None,
) -> dict | list[dict]:
context = context or {}
ignore = ignore or []
shorthand = self._get("shorthand") # type: ignore[attr-defined]
field = self._get("field") # type: ignore[attr-defined]
if shorthand is not Undefined and field is not Undefined:
msg = f"{self.__class__.__name__} specifies both shorthand={shorthand} and field={field}. "
raise ValueError(msg)
if isinstance(shorthand, (tuple, list)):
# If given a list of shorthands, then transform it to a list of classes
kwds = self._kwds.copy() # type: ignore[attr-defined]
kwds.pop("shorthand")
return [
self.__class__(sh, **kwds).to_dict( # type: ignore[call-arg]
validate=validate, ignore=ignore, context=context
)
for sh in shorthand
]
if shorthand is Undefined:
parsed = {}
elif isinstance(shorthand, str):
data: nw.DataFrame | Any = context.get("data", None)
parsed = parse_shorthand(shorthand, data=data)
type_required = "type" in self._kwds # type: ignore[attr-defined]
type_in_shorthand = "type" in parsed
type_defined_explicitly = self._get("type") is not Undefined # type: ignore[attr-defined]
if not type_required:
# Secondary field names don't require a type argument in VegaLite 3+.
# We still parse it out of the shorthand, but drop it here.
parsed.pop("type", None)
elif not (type_in_shorthand or type_defined_explicitly):
if isinstance(data, nw.DataFrame):
msg = (
f'Unable to determine data type for the field "{shorthand}";'
" verify that the field name is not misspelled."
" If you are referencing a field from a transform,"
" also confirm that the data type is specified correctly."
)
raise ValueError(msg)
else:
msg = (
f"{shorthand} encoding field is specified without a type; "
"the type cannot be automatically inferred because "
"the data is not specified as a pandas.DataFrame."
)
raise ValueError(msg)
else:
# Shorthand is not a string; we pass the definition to field,
# and do not do any parsing.
parsed = {"field": shorthand}
context["parsed_shorthand"] = parsed
return super(FieldChannelMixin, self).to_dict(
validate=validate, ignore=ignore, context=context
)
class ValueChannelMixin:
_encoding_name: str
def to_dict(
self,
validate: bool = True,
ignore: list[str] | None = None,
context: dict[str, Any] | None = None,
) -> dict:
context = context or {}
ignore = ignore or []
condition = self._get("condition", Undefined) # type: ignore[attr-defined]
copy = self # don't copy unless we need to
if condition is not Undefined:
if isinstance(condition, core.SchemaBase):
pass
elif "field" in condition and "type" not in condition:
kwds = parse_shorthand(condition["field"], context.get("data", None))
copy = self.copy(deep=["condition"]) # type: ignore[attr-defined]
copy["condition"].update(kwds) # type: ignore[index]
return super(ValueChannelMixin, copy).to_dict(
validate=validate, ignore=ignore, context=context
)
class DatumChannelMixin:
_encoding_name: str
def to_dict(
self,
validate: bool = True,
ignore: list[str] | None = None,
context: dict[str, Any] | None = None,
) -> dict:
context = context or {}
ignore = ignore or []
datum = self._get("datum", Undefined) # type: ignore[attr-defined] # noqa
copy = self # don't copy unless we need to
return super(DatumChannelMixin, copy).to_dict(
validate=validate, ignore=ignore, context=context
)
"""
MARK_MIXIN: Final = '''
class MarkMethodMixin:
"""A mixin class that defines mark methods"""
{methods}
'''
MARK_METHOD: Final = '''
@use_signature({decorator})
def mark_{mark}(self, **kwds: Any) -> Self:
"""Set the chart's mark to '{mark}' (see :class:`{mark_def}`)."""
copy = self.copy(deep=False) # type: ignore[attr-defined]
if any(val is not Undefined for val in kwds.values()):
copy.mark = core.{mark_def}(type="{mark}", **kwds)
else:
copy.mark = "{mark}"
return copy
'''
CONFIG_METHOD: Final = """
@use_signature(core.{classname})
def {method}(self, *args, **kwargs) -> Self:
copy = self.copy(deep=False) # type: ignore[attr-defined]
copy.config = core.{classname}(*args, **kwargs)
return copy
"""
CONFIG_PROP_METHOD: Final = """
@use_signature(core.{classname})
def configure_{prop}(self, *args, **kwargs) -> Self:
copy = self.copy(deep=['config']) # type: ignore[attr-defined]
if copy.config is Undefined:
copy.config = core.Config()
copy.config["{prop}"] = core.{classname}(*args, **kwargs)
return copy
"""
UNIVERSAL_TYPED_DICT = '''
class {name}(TypedDict{metaclass_kwds}):{comment}
"""
{summary}
Parameters
----------
{doc}"""
{td_args}
'''
ENCODE_KWDS: Literal["EncodeKwds"] = "EncodeKwds"
THEME_CONFIG: Literal["ThemeConfig"] = "ThemeConfig"
PADDING_KWDS: Literal["PaddingKwds"] = "PaddingKwds"
ROW_COL_KWDS: Literal["RowColKwds"] = "RowColKwds"
TEMPORAL: Literal["Temporal"] = "Temporal"
# NOTE: `api.py` typing imports
BIN: Literal["Bin"] = "Bin"
IMPUTE: Literal["Impute"] = "Impute"
INTO_CONDITION: Literal["IntoCondition"] = "IntoCondition"
CHART_DATA_TYPE: Literal["ChartDataType"] = "ChartDataType"
# NOTE: `core.py` typing imports
DATETIME: Literal["DateTime"] = "DateTime"
BIN_PARAMS: Literal["BinParams"] = "BinParams"
IMPUTE_PARAMS: Literal["ImputeParams"] = "ImputeParams"
TIME_UNIT_PARAMS: Literal["TimeUnitParams"] = "TimeUnitParams"
SCALE: Literal["Scale"] = "Scale"
AXIS: Literal["Axis"] = "Axis"
LEGEND: Literal["Legend"] = "Legend"
REPEAT_REF: Literal["RepeatRef"] = "RepeatRef"
HEADER_COLUMN: Literal["Header"] = "Header"
ENCODING_SORT_FIELD: Literal["EncodingSortField"] = "EncodingSortField"
ENCODE_KWDS_SUMMARY: Final = (
"Encoding channels map properties of the data to visual properties of the chart."
)
THEME_CONFIG_SUMMARY: Final = (
"Top-Level Configuration ``TypedDict`` for creating a consistent theme."
)
EXTRA_ITEMS_MESSAGE: Final = """\
Notes
-----
The following keys may be specified as string literals **only**:
{invalid_kwds}
See `PEP728`_ for type checker compatibility.
.. _PEP728:
https://peps.python.org/pep-0728/#reference-implementation
"""
ENCODE_METHOD: Final = '''
class _EncodingMixin:
def encode(self, *args: Any, {method_args}) -> Self:
"""Map properties of the data to visual properties of the chart (see :class:`FacetedEncoding`)
{docstring}"""
kwargs = {dict_literal}
if args:
kwargs = {{k: v for k, v in kwargs.items() if v is not Undefined}}
# Convert args to kwargs based on their types.
kwargs = _infer_encoding_types(args, kwargs)
# get a copy of the dict representation of the previous encoding
# ignore type as copy method comes from SchemaBase
copy = self.copy(deep=['encoding']) # type: ignore[attr-defined]
encoding = copy._get('encoding', {{}})
if isinstance(encoding, core.VegaLiteSchema):
encoding = {{k: v for k, v in encoding._kwds.items() if v is not Undefined}}
# update with the new encodings, and apply them to the copy
encoding.update(kwargs)
copy.encoding = core.FacetedEncoding(**encoding)
return copy
'''
# Enables use of ~, &, | with compositions of selection objects.
DUNDER_PREDICATE_COMPOSITION = """
def __invert__(self) -> PredicateComposition:
return PredicateComposition({"not": self.to_dict()})
def __and__(self, other: SchemaBase) -> PredicateComposition:
return PredicateComposition({"and": [self.to_dict(), other.to_dict()]})
def __or__(self, other: SchemaBase) -> PredicateComposition:
return PredicateComposition({"or": [self.to_dict(), other.to_dict()]})
"""
# NOTE: Not yet reasonable to generalize `TypeAliasType`, `TypeVar`
# Revisit if this starts to become more common
TYPING_EXTRA: Final = '''
T = TypeVar("T")
OneOrSeq = TypeAliasType("OneOrSeq", Union[T, Sequence[T]], type_params=(T,))
"""
One of ``T`` specified type(s), or a `Sequence` of such.
Examples
--------
The parameters ``short``, ``long`` accept the same range of types::
# ruff: noqa: UP006, UP007
def func(
short: OneOrSeq[str | bool | float],
long: Union[str, bool, float, Sequence[Union[str, bool, float]],
): ...
"""
class Value(TypedDict, Generic[T]):
"""
A `Generic`_ single item ``dict``.
Parameters
----------
value: T
Wrapped value.
.. _Generic:
https://typing.readthedocs.io/en/latest/spec/generics.html#generics
"""
value: T
ColorHex = Annotated[
LiteralString,
re.compile(r"#[0-9a-f]{2}[0-9a-f]{2}[0-9a-f]{2}([0-9a-f]{2})?", re.IGNORECASE),
]
"""
A `hexadecimal`_ color code.
Corresponds to the ``json-schema`` string format:
{"format": "color-hex", "type": "string"}
Examples
--------
:
"#f0f8ff"
"#7fffd4"
"#000000"
"#0000FF"
"#0000ff80"
.. _hexadecimal:
https://www.w3schools.com/html/html_colors_hex.asp
"""
def is_color_hex(obj: Any) -> TypeIs[ColorHex]:
"""Return ``True`` if the object is a hexadecimal color code."""
# NOTE: Extracts compiled pattern from metadata,
# to avoid defining in multiple places.
it = iter(get_args(ColorHex))
next(it)
pattern: re.Pattern[str] = next(it)
return bool(pattern.fullmatch(obj))
class RowColKwds(TypedDict, Generic[T], total=False):
"""
A `Generic`_ two-item ``dict``.
Parameters
----------
column: T
row: T
.. _Generic:
https://typing.readthedocs.io/en/latest/spec/generics.html#generics
"""
column: T
row: T
class PaddingKwds(TypedDict, total=False):
bottom: float
left: float
right: float
top: float
Temporal: TypeAlias = Union[date, datetime]
'''
_ChannelType = Literal["field", "datum", "value"]
class SchemaGenerator(codegen.SchemaGenerator):
schema_class_template = textwrap.dedent(
'''
class {classname}({basename}):
"""{docstring}"""
_schema = {schema!r}
{init_code}
'''
)
class MethodSchemaGenerator(SchemaGenerator):
"""Base template w/ an extra slot `{method_code}` after `{init_code}`."""
schema_class_template = textwrap.dedent(
'''
class {classname}({basename}):
"""{docstring}"""
_schema = {schema!r}
{init_code}
{method_code}
'''
)
SchGen = TypeVar("SchGen", bound=SchemaGenerator)
class OverridesItem(TypedDict, Generic[SchGen]):
tp: type[SchGen]
kwds: dict[str, Any]
CORE_OVERRIDES: dict[str, OverridesItem[SchemaGenerator]] = {
"PredicateComposition": OverridesItem(
tp=MethodSchemaGenerator, kwds={"method_code": DUNDER_PREDICATE_COMPOSITION}
)
}
class FieldSchemaGenerator(SchemaGenerator):
schema_class_template = textwrap.dedent(
'''
@with_property_setters
class {classname}(FieldChannelMixin, core.{basename}):
"""{docstring}"""
_class_is_valid_at_instantiation = False
_encoding_name = "{encodingname}"
{method_code}
{init_code}
'''
)
haspropsetters = True
class ValueSchemaGenerator(SchemaGenerator):
schema_class_template = textwrap.dedent(
'''
@with_property_setters
class {classname}(ValueChannelMixin, core.{basename}):
"""{docstring}"""
_class_is_valid_at_instantiation = False
_encoding_name = "{encodingname}"
{method_code}
{init_code}
'''
)
haspropsetters = True
class DatumSchemaGenerator(SchemaGenerator):
schema_class_template = textwrap.dedent(
'''
@with_property_setters
class {classname}(DatumChannelMixin, core.{basename}):
"""{docstring}"""
_class_is_valid_at_instantiation = False
_encoding_name = "{encodingname}"
{method_code}
{init_code}
'''
)
haspropsetters = True
class ModuleDef(Generic[T]):
def __init__(self, contents: T, all: Iterable[str], /) -> None:
self.contents: T = contents
self.all: list[str] = list(all)
def schema_class(*args, **kwargs) -> str:
return SchemaGenerator(*args, **kwargs).schema_class()
def schema_url(version: str = SCHEMA_VERSION) -> str:
return SCHEMA_URL_TEMPLATE.format(library="vega-lite", version=version)
def download_schemafile(
version: str, schemapath: Path, skip_download: bool = False
) -> Path:
url = schema_url(version=version)
schemadir = Path(schemapath)
schemadir.mkdir(parents=True, exist_ok=True)
fp = schemadir / SCHEMA_FILE
if not skip_download:
request.urlretrieve(url, fp)
elif not fp.exists():
msg = f"Cannot skip download: {fp!s} does not exist"
raise ValueError(msg)
return fp
def _vega_lite_props_only(
themes: dict[VegaThemes, dict[str, Any]], props: SchemaProperties, /
) -> Iterator[tuple[VegaThemes, dict[str, Any]]]:
"""
Removes properties that are allowed in `Vega` but not `Vega-Lite` from theme definitions.
Each theme is then nested as ``ThemeConfig["config"] = ...``
"""
keep = props.keys()
for name, theme_spec in themes.items():
yield name, {"config": {k: v for k, v in theme_spec.items() if k in keep}}
def update_vega_themes(fp: Path, /, indent: str | int | None = 2) -> None:
root = load_schema(fp.parent / SCHEMA_FILE)
vl_props = SchemaInfo.from_refname("Config", root).properties
themes = dict(_vega_lite_props_only(vlc.get_themes(), vl_props))
data = json.dumps(themes, indent=indent, sort_keys=True)
fp.write_text(data, encoding="utf8")
theme_names = sorted(iter(themes))
TypeAliasTracer.update_aliases(("VegaThemes", spell_literal(theme_names)))
def load_schema(fp: Path, /) -> dict[str, Any]:
"""Reads and returns the root schema from ``fp``."""
with fp.open(encoding="utf8") as f:
root_schema = json.load(f)
return root_schema
def load_schema_with_shorthand_properties(fp: Path, /) -> dict[str, Any]:
schema = load_schema(fp)
encoding_def = "FacetedEncoding"
encoding = SchemaInfo(schema["definitions"][encoding_def], rootschema=schema)
shorthand = {
"anyOf": [
{"type": "string"},
{"type": "array", "items": {"type": "string"}},
{"$ref": "#/definitions/RepeatRef"},
],
"description": "shorthand for field, aggregate, and type",
}
for propschema in encoding.properties.values():
def_dict = get_field_datum_value_defs(propschema, schema)
if field_ref := def_dict.get("field", None):
defschema: dict[str, Any] = {"$ref": field_ref}
defschema = copy.deepcopy(resolve_references(defschema, schema))
# For Encoding field definitions, we patch the schema by adding the
# shorthand property.
defschema["properties"]["shorthand"] = shorthand
if "required" not in defschema:
defschema["required"] = ["shorthand"]
elif "shorthand" not in defschema["required"]:
defschema["required"].append("shorthand")
schema["definitions"][field_ref.split("/")[-1]] = defschema
return schema
def copy_schemapi_util() -> None:
"""Copy the schemapi utility into altair/utils/ and its test file to tests/utils/."""
# copy the schemapi utility file
source_fp = Path(__file__).parent / "schemapi" / "schemapi.py"
destination_fp = Path(__file__).parent / ".." / "altair" / "utils" / "schemapi.py"
print(f"Copying\n {source_fp!s}\n -> {destination_fp!s}")
with (
source_fp.open(encoding="utf8") as source,
destination_fp.open("w", encoding="utf8") as dest,
):
dest.write(HEADER_COMMENT)
dest.writelines(chain(source.readlines(), VERSIONS.iter_inline_literal()))
ruff.format(destination_fp)
def recursive_dict_update(schema: dict, root: dict, def_dict: dict) -> None:
if "$ref" in schema:
next_schema = resolve_references(schema, root)
if "properties" in next_schema:
definition = schema["$ref"]
properties = next_schema["properties"]
for k in def_dict:
if k in properties:
def_dict[k] = definition
else:
recursive_dict_update(next_schema, root, def_dict)
elif "anyOf" in schema:
for sub_schema in schema["anyOf"]:
recursive_dict_update(sub_schema, root, def_dict)
def get_field_datum_value_defs(
propschema: SchemaInfo, root: dict[str, Any]
) -> dict[_ChannelType, str]:
def_dict: dict[_ChannelType, str | None] = dict.fromkeys(
("field", "datum", "value")
)
_schema = propschema.schema
schema = _schema if isinstance(_schema, dict) else dict(_schema)
if propschema.is_reference() and "properties" in schema:
if "field" in schema["properties"]:
def_dict["field"] = propschema.ref
else:
msg = "Unexpected schema structure"
raise ValueError(msg)
else:
recursive_dict_update(schema, root, def_dict)
return {i: j for i, j in def_dict.items() if j}
def toposort(graph: dict[str, list[str]]) -> list[str]:
"""
Topological sort of a directed acyclic graph.
Parameters
----------
graph : dict of lists
Mapping of node labels to list of child node labels.
This is assumed to represent a graph with no cycles.
Returns
-------
order : list
topological order of input graph.
"""
# Once we drop support for Python 3.8, this can potentially be replaced
# with graphlib.TopologicalSorter from the standard library.
stack: list[str] = []
visited: dict[str, Literal[True]] = {}
def visit(nodes):
for node in sorted(nodes, reverse=True):
if not visited.get(node):
visited[node] = True
visit(graph.get(node, []))
stack.insert(0, node)
visit(graph)
return stack
def generate_vegalite_schema_wrapper(fp: Path, /) -> ModuleDef[str]:
"""Generate a schema wrapper at the given path."""
# TODO: generate simple tests for each wrapper
basename = "VegaLiteSchema"
rootschema = load_schema_with_shorthand_properties(fp)
definitions: dict[str, SchemaGenerator] = {}
graph: dict[str, list[str]] = {}
for name in rootschema["definitions"]:
defschema = {"$ref": "#/definitions/" + name}
defschema_repr = {"$ref": "#/definitions/" + name}
name = get_valid_identifier(name)
if overrides := CORE_OVERRIDES.get(name):
tp = overrides["tp"]
kwds = overrides["kwds"]
else:
tp = SchemaGenerator
kwds = {}
definitions[name] = tp(
name,
schema=defschema,
schemarepr=defschema_repr,
rootschema=rootschema,
basename=basename,
rootschemarepr=CodeSnippet(f"{basename}._rootschema"),
**kwds,
)
for name, schema in definitions.items():
graph[name] = []
for child_name in schema.subclasses():
child_name = get_valid_identifier(child_name)
graph[name].append(child_name)
child: SchemaGenerator = definitions[child_name]
if child.basename == basename:
child.basename = [name]
else:
assert isinstance(child.basename, list)
child.basename.append(name)
# Specify __all__ explicitly so that we can exclude the ones from the list
# of exported classes which are also defined in the channels or api modules which takes
# precedent in the generated __init__.py files one and two levels up.
# Importing these classes from multiple modules confuses type checkers.
EXCLUDE = {"Color", "Text", "LookupData", "Dict", "FacetMapping"}
it = (c for c in definitions.keys() - EXCLUDE if not c.startswith("_"))
all_ = [*sorted(it), "Root", "VegaLiteSchema", "SchemaBase", "load_schema"]
contents = [
HEADER,
"from collections.abc import Iterator, Sequence",
"from typing import Any, Literal, Union, Protocol, TYPE_CHECKING",
"import pkgutil",
"import json\n",
"import narwhals.stable.v1 as nw\n",
"from altair.utils.schemapi import SchemaBase, Undefined, UndefinedType, _subclasses # noqa: F401\n",
import_type_checking(
"from datetime import date, datetime",
"from altair import Parameter",
"from altair.typing import Optional",
f"from altair.vegalite.v5.api import {CHART_DATA_TYPE}",
"from ._typing import * # noqa: F403",
),
f"\n__all__ = {all_}\n",
LOAD_SCHEMA.format(schemafile=SCHEMA_FILE),
BASE_SCHEMA.format(basename=basename),
schema_class(
"Root",
schema=rootschema,
basename=basename,
schemarepr=CodeSnippet(f"{basename}._rootschema"),
),
]
for name in toposort(graph):
contents.append(definitions[name].schema_class())
contents.append("") # end with newline
return ModuleDef("\n".join(contents), all_)
@dataclass
class ChannelInfo:
supports_arrays: bool
deep_description: str
field_class_name: str
datum_class_name: str | None = None
value_class_name: str | None = None
@property
def is_field_only(self) -> bool:
return not (self.datum_class_name or self.value_class_name)
@property
def all_names(self) -> Iterator[str]:
"""All channels are expected to have a field class."""
yield self.field_class_name
yield from self.non_field_names
@property
def non_field_names(self) -> Iterator[str]:
if self.is_field_only:
yield from ()
else:
if self.datum_class_name:
yield self.datum_class_name
if self.value_class_name:
yield self.value_class_name
def generate_vegalite_channel_wrappers(fp: Path, /) -> ModuleDef[list[str]]:
schema = load_schema_with_shorthand_properties(fp)
encoding_def = "FacetedEncoding"
encoding = SchemaInfo(schema["definitions"][encoding_def], rootschema=schema)
channel_infos: dict[str, ChannelInfo] = {}
class_defs: list[Any] = []
for prop, propschema in encoding.properties.items():
def_dict = get_field_datum_value_defs(propschema, schema)
supports_arrays = any(
schema_info.is_array() for schema_info in propschema.anyOf
)
classname: str = prop[0].upper() + prop[1:]
channel_info = ChannelInfo(
supports_arrays=supports_arrays,
deep_description=propschema.deep_description,
field_class_name=classname,
)
for encoding_spec, definition in def_dict.items():
basename = definition.rsplit("/", maxsplit=1)[-1]
basename = get_valid_identifier(basename)
gen: SchemaGenerator
defschema = {"$ref": definition}
kwds: dict[str, Any] = {
"basename": basename,
"schema": defschema,
"rootschema": schema,
"encodingname": prop,
}
if encoding_spec == "field":
gen = FieldSchemaGenerator(classname, nodefault=[], **kwds)
elif encoding_spec == "datum":
temp_name = f"{classname}Datum"
channel_info.datum_class_name = temp_name
gen = DatumSchemaGenerator(temp_name, nodefault=["datum"], **kwds)
elif encoding_spec == "value":
temp_name = f"{classname}Value"
channel_info.value_class_name = temp_name
gen = ValueSchemaGenerator(temp_name, nodefault=["value"], **kwds)
else:
raise NotImplementedError
class_defs.append(gen.schema_class())
channel_infos[prop] = channel_info
# NOTE: See https://github.com/vega/altair/pull/3482#issuecomment-2241577342
COMPAT_EXPORTS = (
"DatumChannelMixin",
"FieldChannelMixin",
"ValueChannelMixin",
"with_property_setters",
)
it = chain.from_iterable(info.all_names for info in channel_infos.values())
all_ = sorted(chain(it, COMPAT_EXPORTS))
imports = [
"import sys",
"from collections.abc import Sequence",
"from typing import Any, overload, Literal, Union, TYPE_CHECKING, TypedDict",
import_typing_extensions((3, 10), "TypeAlias"),
"import narwhals.stable.v1 as nw",
"from altair.utils.schemapi import Undefined, with_property_setters",
"from altair.utils import infer_encoding_types as _infer_encoding_types",
"from altair.utils import parse_shorthand",
"from . import core",
"from ._typing import * # noqa: F403",
]
TYPING_CORE = (
DATETIME,
TIME_UNIT_PARAMS,
SCALE,
AXIS,
LEGEND,
REPEAT_REF,
HEADER_COLUMN,
ENCODING_SORT_FIELD,
)
TYPING_API = INTO_CONDITION, BIN, IMPUTE
contents: list[str] = [
HEADER,
CHANNEL_MYPY_IGNORE_STATEMENTS,
*imports,
import_type_checking(
"from datetime import date, datetime",
"from altair import Parameter, SchemaBase",
"from altair.typing import Optional",
f"from altair.vegalite.v5.schema.core import {', '.join(TYPING_CORE)}",
f"from altair.vegalite.v5.api import {', '.join(TYPING_API)}",
textwrap.indent(import_typing_extensions((3, 11), "Self"), " "),
),
f"\n__all__ = {all_}\n",
CHANNEL_MIXINS,
*class_defs,
*generate_encoding_artifacts(
channel_infos, ENCODE_METHOD, facet_encoding=encoding
),
]
return ModuleDef(contents, all_)
def generate_vegalite_mark_mixin(fp: Path, /, markdefs: dict[str, str]) -> str:
schema = load_schema(fp)
code: list[str] = []
it_dummy = (
SchemaGenerator(
classname=f"_{mark_def}",
schema={"$ref": "#/definitions/" + mark_def},
rootschema=schema,
schemarepr={"$ref": "#/definitions/" + mark_def},
exclude_properties={"type"},
summary=f"{mark_def} schema wrapper.",
).schema_class()
for mark_def in markdefs.values()
)
for mark_enum, mark_def in markdefs.items():
_def = schema["definitions"][mark_enum]
marks: list[Any] = _def["enum"] if "enum" in _def else [_def["const"]]
for mark in marks:
# TODO: only include args relevant to given type?
mark_method = MARK_METHOD.format(
decorator=f"_{mark_def}", mark=mark, mark_def=mark_def
)
code.append("\n ".join(mark_method.splitlines()))
return "\n".join(chain(it_dummy, [MARK_MIXIN.format(methods="\n".join(code))]))
def generate_typed_dict(
info: SchemaInfo,
name: str,
*,
summary: str | None = None,
groups: Iterable[str] | AttrGetter[ArgInfo, set[str]] = arg_required_kwds,
exclude: str | Iterable[str] | None = None,
override_args: Iterable[str] | None = None,
) -> str:
"""
Return a fully typed & documented ``TypedDict``.
Parameters
----------
info
JSON Schema wrapper.
name
Full target class name.
Include a pre/post-fix if ``SchemaInfo.title`` already exists.
summary
When provided, used instead of generated summary line.
groups
A subset of ``ArgInfo``, or a callable that can derive one.
exclude
Property name(s) to omit if they appear during iteration.
override_args
When provided, used instead of any ``ArgInfo`` related handling.
.. note::
See ``EncodeKwds``.
Notes
-----
- Internally handles keys that are not valid python identifiers
- The union of their types will be added to ``__extra_items__``
"""
TARGET: Literal["annotation"] = "annotation"
arg_info = codegen.get_args(info)
metaclass_kwds = ", total=False"
comment = ""
args_it: Iterable[str] = (
(
f"{p}: {p_info.to_type_repr(target=TARGET, use_concrete=True)}"
for p, p_info in arg_info.iter_args(groups, exclude=exclude)
)
if override_args is None
else override_args
)
args = "\n ".join(args_it)
doc = indent_docstring(
chain.from_iterable(
(p, f" {p_info.deep_description}")
for p, p_info in arg_info.iter_args(groups, exclude=exclude)