-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
bokeh_model.py
189 lines (136 loc) · 6.12 KB
/
bokeh_model.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
# -----------------------------------------------------------------------------
# Copyright (c) 2012 - 2024, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -----------------------------------------------------------------------------
""" Thoroughly document Bokeh model classes.
The ``bokeh-model`` directive will automatically document all the attributes
(including Bokeh properties) of a Bokeh Model subclass. A JSON prototype showing
all the possible JSON fields will also be generated.
This directive takes the name of a Bokeh model class as an argument and its
module as an option:
.. code-block:: rest
.. bokeh-model:: Foo
:module: bokeh.sphinxext.sample
Examples
--------
For the following definition of ``bokeh.sphinxext.sample.Foo``:
.. code-block:: python
class Foo(Model):
''' This is a Foo model. '''
index = Either(Auto, Enum('abc', 'def', 'xzy'), help="doc for index")
value = Tuple(Float, Float, help="doc for value")
usage yields the output:
=====
.. bokeh-model:: Foo
:module: bokeh.sphinxext.sample
=====
The ``bokeh-model`` direction may be used explicitly, but it can also be used
in conjunction with the :ref:`bokeh.sphinxext.bokeh_autodoc` extension.
To enable this extension, add `"bokeh.sphinxext.bokeh_model"` to the
extensions list in your Sphinx configuration module.
"""
# -----------------------------------------------------------------------------
# Boilerplate
# -----------------------------------------------------------------------------
from __future__ import annotations
import logging # isort:skip
log = logging.getLogger(__name__)
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
# Standard library imports
import importlib
import json
import warnings
from os import getenv
from typing import Any
# External imports
from docutils.parsers.rst.directives import unchanged
from sphinx.errors import SphinxError
# Bokeh imports
from bokeh.core.property.singletons import Undefined
from bokeh.core.serialization import AnyRep, Serializer, SymbolRep
from bokeh.model import Model
from bokeh.util.warnings import BokehDeprecationWarning
# Bokeh imports
from . import PARALLEL_SAFE
from .bokeh_directive import BokehDirective, py_sig_re
from .templates import MODEL_DETAIL
# -----------------------------------------------------------------------------
# Globals and constants
# -----------------------------------------------------------------------------
__all__ = (
"BokehModelDirective",
"setup",
)
# -----------------------------------------------------------------------------
# General API
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Dev API
# -----------------------------------------------------------------------------
class BokehModelDirective(BokehDirective):
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
"module": unchanged,
"canonical": unchanged,
}
def run(self):
sig = " ".join(self.arguments)
m = py_sig_re.match(sig)
if m is None:
raise SphinxError(f"Unable to parse signature for bokeh-model: {sig!r}")
name_prefix, model_name, arglist, retann = m.groups()
if getenv("BOKEH_SPHINX_QUICK") == "1":
return self.parse(f"{model_name}\n{'-'*len(model_name)}\n", "<bokeh-model>")
module_name = self.options["module"]
try:
module = importlib.import_module(module_name)
except ImportError:
raise SphinxError(f"Unable to generate model reference docs for {model_name}, couldn't import module {module_name}")
model = getattr(module, model_name, None)
if model is None:
raise SphinxError(f"Unable to generate model reference docs: no model for {model_name} in module {module_name}")
if not issubclass(model, Model):
raise SphinxError(f"Unable to generate model reference docs: {model_name}, is not a subclass of Model")
# We may need to instantiate deprecated objects as part of documenting
# them in the reference guide. Suppress any warnings here to keep the
# docs build clean just for this case
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=BokehDeprecationWarning)
model_obj = model()
model_json = json.dumps(to_json_rep(model_obj), sort_keys=True, indent=2, separators=(", ", ": "))
# we only want to document things as coming from top-level `bokeh.models`
adjusted_module_name = "bokeh.models" if module_name.startswith("bokeh.models") else module_name
rst_text = MODEL_DETAIL.render(
name=model_name,
module_name=adjusted_module_name,
model_json=model_json,
)
return self.parse(rst_text, "<bokeh-model>")
def setup(app):
""" Required Sphinx extension setup function. """
app.add_directive_to_domain("py", "bokeh-model", BokehModelDirective)
return PARALLEL_SAFE
# -----------------------------------------------------------------------------
# Private API
# -----------------------------------------------------------------------------
class DocsSerializer(Serializer):
def _encode(self, obj: Any) -> AnyRep:
if obj is Undefined:
return SymbolRep(type="symbol", name="unset")
else:
return super()._encode(obj)
def to_json_rep(obj: Model) -> dict[str, AnyRep]:
serializer = DocsSerializer()
properties = obj.properties_with_values(include_defaults=True, include_undefined=True)
attributes = {key: serializer.encode(val) for key, val in properties.items()}
return dict(id=obj.id, **attributes)
# -----------------------------------------------------------------------------
# Code
# -----------------------------------------------------------------------------