Skip to content

Commit 2b3d47b

Browse files
committed
feat: modifying code generation to reduce bundle size
1. Add `bin/get_size.py` so that `python bin/get_size.py plotly build` reports the number of files and total size in bytes of the `plotly` directory (where generated code is put) and the `build` directory that is populated by `python setup.py build`. 1. Modify `codegen/__init__.py` and `./setup.py` so that `python setup.py --reformat=false` disables reformatting. 1. Alias name of base validator during import in `codegen/validators.py`. 1. Remove the long list of CSS colors from help strings for color properties. 1. Assign an empty string to the `data_docs` field of generated validators. 1. Introduce a method `_init_provided` for `BaseFigure` and `BasePlotlyType` that calls a helper function `_initialize_provided` to replace repetitions of: ``` _v = arg.pop("something", None) _v = something if something is not None else _v if _v is not None: self["something"] = _v ``` Original size of plotly/**/*.py: 50365842 bytes Current size of plotly/**/*.py: 38256842 bytes Change: -26%
1 parent 3d36f14 commit 2b3d47b

File tree

14,849 files changed

+245607
-460318
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

14,849 files changed

+245607
-460318
lines changed

packages/python/plotly/_plotly_utils/basevalidators.py

+4-23
Original file line numberDiff line numberDiff line change
@@ -1328,25 +1328,14 @@ def numbers_allowed(self):
13281328
return self.colorscale_path is not None
13291329

13301330
def description(self):
1331-
1332-
named_clrs_str = "\n".join(
1333-
textwrap.wrap(
1334-
", ".join(self.named_colors),
1335-
width=79 - 16,
1336-
initial_indent=" " * 12,
1337-
subsequent_indent=" " * 12,
1338-
)
1339-
)
1340-
13411331
valid_color_description = """\
13421332
The '{plotly_name}' property is a color and may be specified as:
13431333
- A hex string (e.g. '#ff0000')
13441334
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
13451335
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
13461336
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
1347-
- A named CSS color:
1348-
{clrs}""".format(
1349-
plotly_name=self.plotly_name, clrs=named_clrs_str
1337+
- A named CSS color""".format(
1338+
plotly_name=self.plotly_name
13501339
)
13511340

13521341
if self.colorscale_path:
@@ -2483,15 +2472,11 @@ def description(self):
24832472
that may be specified as:
24842473
- An instance of :class:`{module_str}.{class_str}`
24852474
- A dict of string/value properties that will be passed
2486-
to the {class_str} constructor
2487-
2488-
Supported dict properties:
2489-
{constructor_params_str}"""
2475+
to the {class_str} constructor"""
24902476
).format(
24912477
plotly_name=self.plotly_name,
24922478
class_str=self.data_class_str,
24932479
module_str=self.module_str,
2494-
constructor_params_str=self.data_docs,
24952480
)
24962481

24972482
return desc
@@ -2560,15 +2545,11 @@ def description(self):
25602545
{class_str} that may be specified as:
25612546
- A list or tuple of instances of {module_str}.{class_str}
25622547
- A list or tuple of dicts of string/value properties that
2563-
will be passed to the {class_str} constructor
2564-
2565-
Supported dict properties:
2566-
{constructor_params_str}"""
2548+
will be passed to the {class_str} constructor"""
25672549
).format(
25682550
plotly_name=self.plotly_name,
25692551
class_str=self.data_class_str,
25702552
module_str=self.module_str,
2571-
constructor_params_str=self.data_docs,
25722553
)
25732554

25742555
return desc
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""Calculate total size and total number of files of package."""
2+
3+
from pathlib import Path
4+
import sys
5+
6+
7+
def main():
8+
"""Main driver."""
9+
assert len(sys.argv) == 3, "Usage: get_size.py src_dir build_dir"
10+
src_files, src_bytes = get_size(sys.argv[1])
11+
build_files, build_bytes = get_size(sys.argv[2])
12+
print(f"src,files,{src_files}")
13+
print(f"src,bytes,{src_bytes}")
14+
print(f"build,files,{build_files}")
15+
print(f"build,bytes,{build_bytes}")
16+
17+
18+
def get_size(root_dir):
19+
"""Count files and size in bytes."""
20+
num_files, num_bytes = 0, 0
21+
for f in Path(root_dir).glob("**/*.*"):
22+
if "__pycache__" not in str(f):
23+
num_files += 1
24+
num_bytes += f.stat().st_size
25+
return num_files, num_bytes
26+
27+
28+
if __name__ == "__main__":
29+
main()

packages/python/plotly/codegen/__init__.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def preprocess_schema(plotly_schema):
8585
items["colorscale"] = items.pop("concentrationscales")
8686

8787

88-
def perform_codegen():
88+
def perform_codegen(reformat=True):
8989
# Set root codegen output directory
9090
# ---------------------------------
9191
# (relative to project root)
@@ -337,9 +337,12 @@ def __getattr__(import_name):
337337
f.write(graph_objects_init_source)
338338

339339
# ### Run black code formatter on output directories ###
340-
subprocess.call(["black", "--target-version=py36", validators_pkgdir])
341-
subprocess.call(["black", "--target-version=py36", graph_objs_pkgdir])
342-
subprocess.call(["black", "--target-version=py36", graph_objects_path])
340+
if reformat:
341+
subprocess.call(["black", "--target-version=py36", validators_pkgdir])
342+
subprocess.call(["black", "--target-version=py36", graph_objs_pkgdir])
343+
subprocess.call(["black", "--target-version=py36", graph_objects_path])
344+
else:
345+
print("skipping reformatting")
343346

344347

345348
if __name__ == "__main__":

packages/python/plotly/codegen/datatypes.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -373,10 +373,7 @@ def __init__(self"""
373373
name_prop = subtype_node.name_property
374374
buffer.write(
375375
f"""
376-
_v = arg.pop('{name_prop}', None)
377-
_v = {name_prop} if {name_prop} is not None else _v
378-
if _v is not None:
379-
self['{name_prop}'] = _v"""
376+
self._init_provided('{name_prop}', arg, {name_prop})"""
380377
)
381378

382379
# ### Literals ###

packages/python/plotly/codegen/utils.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -456,9 +456,7 @@ def get_validator_params(self):
456456

457457
if self.is_compound:
458458
params["data_class_str"] = repr(self.name_datatype_class)
459-
params["data_docs"] = (
460-
'"""' + self.get_constructor_params_docstring() + '\n"""'
461-
)
459+
params["data_docs"] = '"""\n"""'
462460
else:
463461
assert self.is_simple
464462

packages/python/plotly/codegen/validators.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ def build_validator_py(node: PlotlyNode):
2424
# ---------------
2525
assert node.is_datatype
2626

27-
# Initialize source code buffer
28-
# -----------------------------
27+
# Initialize
2928
buffer = StringIO()
29+
import_alias = "_bv"
3030

3131
# Imports
3232
# -------
3333
# ### Import package of the validator's superclass ###
3434
import_str = ".".join(node.name_base_validator.split(".")[:-1])
35-
buffer.write(f"import {import_str }\n")
35+
buffer.write(f"import {import_str} as {import_alias}\n")
3636

3737
# Build Validator
3838
# ---------------
@@ -41,11 +41,11 @@ def build_validator_py(node: PlotlyNode):
4141

4242
# ### Write class definition ###
4343
class_name = node.name_validator_class
44-
superclass_name = node.name_base_validator
44+
superclass_name = node.name_base_validator.split(".")[-1]
4545
buffer.write(
4646
f"""
4747
48-
class {class_name}({superclass_name}):
48+
class {class_name}({import_alias}.{superclass_name}):
4949
def __init__(self, plotly_name={params['plotly_name']},
5050
parent_name={params['parent_name']},
5151
**kwargs):"""

packages/python/plotly/plotly/basedatatypes.py

+28
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,18 @@ def _generator(i):
385385
yield x
386386

387387

388+
def _initialize_provided(obj, name, arg, provided):
389+
"""
390+
Initialize a property of this object using the provided value
391+
or a value popped from the arguments dictionary. If neither
392+
is available, do not set the property.
393+
"""
394+
val = arg.pop(name, None)
395+
val = provided if provided is not None else val
396+
if val is not None:
397+
obj[name] = val
398+
399+
388400
class BaseFigure(object):
389401
"""
390402
Base class for all figure types (both widget and non-widget)
@@ -834,6 +846,14 @@ def _ipython_display_(self):
834846
else:
835847
print(repr(self))
836848

849+
def _init_provided(self, name, arg, provided):
850+
"""
851+
Initialize a property of this object using the provided value
852+
or a value popped from the arguments dictionary. If neither
853+
is available, do not set the property.
854+
"""
855+
_initialize_provided(self, name, arg, provided)
856+
837857
def update(self, dict1=None, overwrite=False, **kwargs):
838858
"""
839859
Update the properties of the figure with a dict and/or with
@@ -4329,6 +4349,14 @@ def _get_validator(self, prop):
43294349

43304350
return ValidatorCache.get_validator(self._path_str, prop)
43314351

4352+
def _init_provided(self, name, arg, provided):
4353+
"""
4354+
Initialize a property of this object using the provided value
4355+
or a value popped from the arguments dictionary. If neither
4356+
is available, do not set the property.
4357+
"""
4358+
_initialize_provided(self, name, arg, provided)
4359+
43324360
@property
43334361
def _validators(self):
43344362
"""
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import sys
22
from typing import TYPE_CHECKING
3-
43
if sys.version_info < (3, 7) or TYPE_CHECKING:
54
from ..graph_objs import Waterfall
65
from ..graph_objs import Volume
@@ -131,148 +130,17 @@
131130
from ..graph_objs import layout
132131
else:
133132
from _plotly_utils.importers import relative_import
134-
135133
__all__, __getattr__, __dir__ = relative_import(
136134
__name__,
137-
[
138-
"..graph_objs.waterfall",
139-
"..graph_objs.volume",
140-
"..graph_objs.violin",
141-
"..graph_objs.treemap",
142-
"..graph_objs.table",
143-
"..graph_objs.surface",
144-
"..graph_objs.sunburst",
145-
"..graph_objs.streamtube",
146-
"..graph_objs.splom",
147-
"..graph_objs.scatterternary",
148-
"..graph_objs.scattersmith",
149-
"..graph_objs.scatterpolargl",
150-
"..graph_objs.scatterpolar",
151-
"..graph_objs.scattermapbox",
152-
"..graph_objs.scattermap",
153-
"..graph_objs.scattergl",
154-
"..graph_objs.scattergeo",
155-
"..graph_objs.scattercarpet",
156-
"..graph_objs.scatter3d",
157-
"..graph_objs.scatter",
158-
"..graph_objs.sankey",
159-
"..graph_objs.pie",
160-
"..graph_objs.parcoords",
161-
"..graph_objs.parcats",
162-
"..graph_objs.ohlc",
163-
"..graph_objs.mesh3d",
164-
"..graph_objs.isosurface",
165-
"..graph_objs.indicator",
166-
"..graph_objs.image",
167-
"..graph_objs.icicle",
168-
"..graph_objs.histogram2dcontour",
169-
"..graph_objs.histogram2d",
170-
"..graph_objs.histogram",
171-
"..graph_objs.heatmap",
172-
"..graph_objs.funnelarea",
173-
"..graph_objs.funnel",
174-
"..graph_objs.densitymapbox",
175-
"..graph_objs.densitymap",
176-
"..graph_objs.contourcarpet",
177-
"..graph_objs.contour",
178-
"..graph_objs.cone",
179-
"..graph_objs.choroplethmapbox",
180-
"..graph_objs.choroplethmap",
181-
"..graph_objs.choropleth",
182-
"..graph_objs.carpet",
183-
"..graph_objs.candlestick",
184-
"..graph_objs.box",
185-
"..graph_objs.barpolar",
186-
"..graph_objs.bar",
187-
"..graph_objs.layout",
188-
],
189-
[
190-
"..graph_objs.Waterfall",
191-
"..graph_objs.Volume",
192-
"..graph_objs.Violin",
193-
"..graph_objs.Treemap",
194-
"..graph_objs.Table",
195-
"..graph_objs.Surface",
196-
"..graph_objs.Sunburst",
197-
"..graph_objs.Streamtube",
198-
"..graph_objs.Splom",
199-
"..graph_objs.Scatterternary",
200-
"..graph_objs.Scattersmith",
201-
"..graph_objs.Scatterpolargl",
202-
"..graph_objs.Scatterpolar",
203-
"..graph_objs.Scattermapbox",
204-
"..graph_objs.Scattermap",
205-
"..graph_objs.Scattergl",
206-
"..graph_objs.Scattergeo",
207-
"..graph_objs.Scattercarpet",
208-
"..graph_objs.Scatter3d",
209-
"..graph_objs.Scatter",
210-
"..graph_objs.Sankey",
211-
"..graph_objs.Pie",
212-
"..graph_objs.Parcoords",
213-
"..graph_objs.Parcats",
214-
"..graph_objs.Ohlc",
215-
"..graph_objs.Mesh3d",
216-
"..graph_objs.Isosurface",
217-
"..graph_objs.Indicator",
218-
"..graph_objs.Image",
219-
"..graph_objs.Icicle",
220-
"..graph_objs.Histogram2dContour",
221-
"..graph_objs.Histogram2d",
222-
"..graph_objs.Histogram",
223-
"..graph_objs.Heatmap",
224-
"..graph_objs.Funnelarea",
225-
"..graph_objs.Funnel",
226-
"..graph_objs.Densitymapbox",
227-
"..graph_objs.Densitymap",
228-
"..graph_objs.Contourcarpet",
229-
"..graph_objs.Contour",
230-
"..graph_objs.Cone",
231-
"..graph_objs.Choroplethmapbox",
232-
"..graph_objs.Choroplethmap",
233-
"..graph_objs.Choropleth",
234-
"..graph_objs.Carpet",
235-
"..graph_objs.Candlestick",
236-
"..graph_objs.Box",
237-
"..graph_objs.Barpolar",
238-
"..graph_objs.Bar",
239-
"..graph_objs.Layout",
240-
"..graph_objs.Frame",
241-
"..graph_objs.Figure",
242-
"..graph_objs.Data",
243-
"..graph_objs.Annotations",
244-
"..graph_objs.Frames",
245-
"..graph_objs.AngularAxis",
246-
"..graph_objs.Annotation",
247-
"..graph_objs.ColorBar",
248-
"..graph_objs.Contours",
249-
"..graph_objs.ErrorX",
250-
"..graph_objs.ErrorY",
251-
"..graph_objs.ErrorZ",
252-
"..graph_objs.Font",
253-
"..graph_objs.Legend",
254-
"..graph_objs.Line",
255-
"..graph_objs.Margin",
256-
"..graph_objs.Marker",
257-
"..graph_objs.RadialAxis",
258-
"..graph_objs.Scene",
259-
"..graph_objs.Stream",
260-
"..graph_objs.XAxis",
261-
"..graph_objs.YAxis",
262-
"..graph_objs.ZAxis",
263-
"..graph_objs.XBins",
264-
"..graph_objs.YBins",
265-
"..graph_objs.Trace",
266-
"..graph_objs.Histogram2dcontour",
267-
],
135+
['..graph_objs.waterfall', '..graph_objs.volume', '..graph_objs.violin', '..graph_objs.treemap', '..graph_objs.table', '..graph_objs.surface', '..graph_objs.sunburst', '..graph_objs.streamtube', '..graph_objs.splom', '..graph_objs.scatterternary', '..graph_objs.scattersmith', '..graph_objs.scatterpolargl', '..graph_objs.scatterpolar', '..graph_objs.scattermapbox', '..graph_objs.scattermap', '..graph_objs.scattergl', '..graph_objs.scattergeo', '..graph_objs.scattercarpet', '..graph_objs.scatter3d', '..graph_objs.scatter', '..graph_objs.sankey', '..graph_objs.pie', '..graph_objs.parcoords', '..graph_objs.parcats', '..graph_objs.ohlc', '..graph_objs.mesh3d', '..graph_objs.isosurface', '..graph_objs.indicator', '..graph_objs.image', '..graph_objs.icicle', '..graph_objs.histogram2dcontour', '..graph_objs.histogram2d', '..graph_objs.histogram', '..graph_objs.heatmap', '..graph_objs.funnelarea', '..graph_objs.funnel', '..graph_objs.densitymapbox', '..graph_objs.densitymap', '..graph_objs.contourcarpet', '..graph_objs.contour', '..graph_objs.cone', '..graph_objs.choroplethmapbox', '..graph_objs.choroplethmap', '..graph_objs.choropleth', '..graph_objs.carpet', '..graph_objs.candlestick', '..graph_objs.box', '..graph_objs.barpolar', '..graph_objs.bar', '..graph_objs.layout'],
136+
['..graph_objs.Waterfall', '..graph_objs.Volume', '..graph_objs.Violin', '..graph_objs.Treemap', '..graph_objs.Table', '..graph_objs.Surface', '..graph_objs.Sunburst', '..graph_objs.Streamtube', '..graph_objs.Splom', '..graph_objs.Scatterternary', '..graph_objs.Scattersmith', '..graph_objs.Scatterpolargl', '..graph_objs.Scatterpolar', '..graph_objs.Scattermapbox', '..graph_objs.Scattermap', '..graph_objs.Scattergl', '..graph_objs.Scattergeo', '..graph_objs.Scattercarpet', '..graph_objs.Scatter3d', '..graph_objs.Scatter', '..graph_objs.Sankey', '..graph_objs.Pie', '..graph_objs.Parcoords', '..graph_objs.Parcats', '..graph_objs.Ohlc', '..graph_objs.Mesh3d', '..graph_objs.Isosurface', '..graph_objs.Indicator', '..graph_objs.Image', '..graph_objs.Icicle', '..graph_objs.Histogram2dContour', '..graph_objs.Histogram2d', '..graph_objs.Histogram', '..graph_objs.Heatmap', '..graph_objs.Funnelarea', '..graph_objs.Funnel', '..graph_objs.Densitymapbox', '..graph_objs.Densitymap', '..graph_objs.Contourcarpet', '..graph_objs.Contour', '..graph_objs.Cone', '..graph_objs.Choroplethmapbox', '..graph_objs.Choroplethmap', '..graph_objs.Choropleth', '..graph_objs.Carpet', '..graph_objs.Candlestick', '..graph_objs.Box', '..graph_objs.Barpolar', '..graph_objs.Bar', '..graph_objs.Layout', '..graph_objs.Frame', '..graph_objs.Figure', '..graph_objs.Data', '..graph_objs.Annotations', '..graph_objs.Frames', '..graph_objs.AngularAxis', '..graph_objs.Annotation', '..graph_objs.ColorBar', '..graph_objs.Contours', '..graph_objs.ErrorX', '..graph_objs.ErrorY', '..graph_objs.ErrorZ', '..graph_objs.Font', '..graph_objs.Legend', '..graph_objs.Line', '..graph_objs.Margin', '..graph_objs.Marker', '..graph_objs.RadialAxis', '..graph_objs.Scene', '..graph_objs.Stream', '..graph_objs.XAxis', '..graph_objs.YAxis', '..graph_objs.ZAxis', '..graph_objs.XBins', '..graph_objs.YBins', '..graph_objs.Trace', '..graph_objs.Histogram2dcontour']
268137
)
269138

270139

271140
if sys.version_info < (3, 7) or TYPE_CHECKING:
272141
try:
273142
import ipywidgets as _ipywidgets
274143
from packaging.version import Version as _Version
275-
276144
if _Version(_ipywidgets.__version__) >= _Version("7.0.0"):
277145
from ..graph_objs._figurewidget import FigureWidget
278146
else:
@@ -282,7 +150,6 @@
282150
else:
283151
__all__.append("FigureWidget")
284152
orig_getattr = __getattr__
285-
286153
def __getattr__(import_name):
287154
if import_name == "FigureWidget":
288155
try:
@@ -297,7 +164,7 @@ def __getattr__(import_name):
297164
raise ImportError()
298165
except Exception:
299166
from ..missing_anywidget import FigureWidget
300-
301167
return FigureWidget
302168

303169
return orig_getattr(import_name)
170+

0 commit comments

Comments
 (0)