Skip to content

Commit

Permalink
feat: adding type annotations to some constructor parameters
Browse files Browse the repository at this point in the history
1.  Add `from __future__ import annotations` as the first line of
    generated files so that modern Python type annotation syntax can
    be used in older versions of Python.

1.  Add `from typing import Any` and `from numpy.types import NDArray`
    to all generated files rather than trying to figure out which
    of these imports are needed on a file-by-file basis.

1.  Rename `get_typing_type` in `codegen/datatypes.py` to
    `get_python_type` to make purpose clearer.

1.  Add additional optional parameter to `get_python_type` so that
    `compound` and `compound_array` types in the schema are converted
    to `None` rather than causing an exception.

1.  Modify `codegen/datatypes.py` to add type annotations to constructor
    parameters.

1.  Modify `codegen/figure.py` to add `bool` type to one figure
    constructor parameter.

FIXME: figure out what type should actually be returned for `compound`
and `compound_array`.

FIXME: figure out what types to use for other standard parameters of
figures generated by `codegen/figure.py`.
  • Loading branch information
gvwilson committed Feb 5, 2025
1 parent 3cb9303 commit f949f65
Show file tree
Hide file tree
Showing 1,064 changed files with 22,600 additions and 19,407 deletions.
24 changes: 15 additions & 9 deletions codegen/datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
]


def get_typing_type(plotly_type, array_ok=False):
def get_python_type(plotly_type, array_ok=False, compound_as_none=False):
"""
Get Python type corresponding to a valType string from the plotly schema
Expand All @@ -28,7 +28,7 @@ def get_typing_type(plotly_type, array_ok=False):
Python type string
"""
if plotly_type == "data_array":
pytype = "numpy.ndarray"
pytype = "NDArray"
elif plotly_type == "info_array":
pytype = "list"
elif plotly_type == "colorlist":
Expand All @@ -43,11 +43,13 @@ def get_typing_type(plotly_type, array_ok=False):
pytype = "int"
elif plotly_type == "boolean":
pytype = "bool"
elif (plotly_type in ("compound", "compound_array")) and compound_as_none:
pytype = None
else:
raise ValueError("Unknown plotly type: %s" % plotly_type)

if array_ok:
return f"{pytype}|numpy.ndarray"
return f"{pytype}|NDArray"
else:
return pytype

Expand Down Expand Up @@ -96,11 +98,14 @@ def build_datatype_py(node):

# Imports
# -------
buffer.write("from __future__ import annotations\n")
buffer.write("from typing import Any\n")
buffer.write("from numpy.typing import NDArray\n")
buffer.write(
f"from plotly.basedatatypes "
"from plotly.basedatatypes "
f"import {node.name_base_datatype} as _{node.name_base_datatype}\n"
)
buffer.write(f"import copy as _copy\n")
buffer.write("import copy as _copy\n")

if node.name_property in deprecated_mapbox_traces:
buffer.write(f"from warnings import warn\n")
Expand All @@ -127,7 +132,7 @@ class {datatype_class}(_{node.name_base_datatype}):\n"""
import re
_subplotid_prop_re = re.compile(
'^(' + '|'.join(_subplotid_prop_names) + r')(\\d+)$')
'^(' + '|'.join(_subplotid_prop_names) + r')(\d+)$')
"""
)

Expand Down Expand Up @@ -197,7 +202,7 @@ def _subplot_re_match(self, prop):
elif subtype_node.is_mapped:
prop_type = ""
else:
prop_type = get_typing_type(subtype_node.datatype, subtype_node.is_array_ok)
prop_type = get_python_type(subtype_node.datatype, array_ok=subtype_node.is_array_ok)

# #### Get property description ####
raw_description = subtype_node.description
Expand Down Expand Up @@ -474,10 +479,11 @@ def add_constructor_params(
{extra}=None"""
)

for i, subtype_node in enumerate(subtype_nodes):
for subtype_node in subtype_nodes:
py_type = get_python_type(subtype_node.datatype, compound_as_none=True)
buffer.write(
f""",
{subtype_node.name_property}=None"""
{subtype_node.name_property}: {py_type}|None = None"""
)

for extra in append_extras:
Expand Down
7 changes: 4 additions & 3 deletions codegen/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ def build_figure_py(
trace_nodes = trace_node.child_compound_datatypes

# Write imports
# -------------
# ### Import base class ###
buffer.write("from __future__ import annotations\n")
buffer.write("from typing import Any\n")
buffer.write("from numpy.typing import NDArray\n")
buffer.write(f"from plotly.{base_package} import {base_classname}\n")

# Write class definition
Expand All @@ -82,7 +83,7 @@ class {fig_classname}({base_classname}):\n"""
buffer.write(
f"""
def __init__(self, data=None, layout=None,
frames=None, skip_invalid=False, **kwargs):
frames=None, skip_invalid: bool = False, **kwargs):
\"\"\"
Create a new :class:{fig_classname} instance
Expand Down
179 changes: 91 additions & 88 deletions plotly/graph_objs/_bar.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@


from __future__ import annotations
from typing import Any
from numpy.typing import NDArray
from plotly.basedatatypes import BaseTraceType as _BaseTraceType
import copy as _copy

Expand Down Expand Up @@ -48,7 +51,7 @@ def base(self):
Returns
-------
Any|numpy.ndarray
Any|NDArray
"""
return self['base']

Expand Down Expand Up @@ -136,7 +139,7 @@ def customdata(self):
Returns
-------
numpy.ndarray
NDArray
"""
return self['customdata']

Expand Down Expand Up @@ -265,7 +268,7 @@ def hoverinfo(self):
Returns
-------
Any|numpy.ndarray
Any|NDArray
"""
return self['hoverinfo']

Expand Down Expand Up @@ -353,7 +356,7 @@ def hovertemplate(self):
Returns
-------
str|numpy.ndarray
str|NDArray
"""
return self['hovertemplate']

Expand Down Expand Up @@ -400,7 +403,7 @@ def hovertext(self):
Returns
-------
str|numpy.ndarray
str|NDArray
"""
return self['hovertext']

Expand Down Expand Up @@ -443,7 +446,7 @@ def ids(self):
Returns
-------
numpy.ndarray
NDArray
"""
return self['ids']

Expand Down Expand Up @@ -674,7 +677,7 @@ def meta(self):
Returns
-------
Any|numpy.ndarray
Any|NDArray
"""
return self['meta']

Expand Down Expand Up @@ -739,7 +742,7 @@ def offset(self):
Returns
-------
int|float|numpy.ndarray
int|float|NDArray
"""
return self['offset']

Expand Down Expand Up @@ -961,7 +964,7 @@ def text(self):
Returns
-------
str|numpy.ndarray
str|NDArray
"""
return self['text']

Expand Down Expand Up @@ -1038,7 +1041,7 @@ def textposition(self):
Returns
-------
Any|numpy.ndarray
Any|NDArray
"""
return self['textposition']

Expand Down Expand Up @@ -1114,7 +1117,7 @@ def texttemplate(self):
Returns
-------
str|numpy.ndarray
str|NDArray
"""
return self['texttemplate']

Expand Down Expand Up @@ -1255,7 +1258,7 @@ def width(self):
Returns
-------
int|float|numpy.ndarray
int|float|NDArray
"""
return self['width']

Expand Down Expand Up @@ -1295,7 +1298,7 @@ def x(self):
Returns
-------
numpy.ndarray
NDArray
"""
return self['x']

Expand Down Expand Up @@ -1503,7 +1506,7 @@ def y(self):
Returns
-------
numpy.ndarray
NDArray
"""
return self['y']

Expand Down Expand Up @@ -2107,80 +2110,80 @@ def _prop_descriptions(self):
"""
def __init__(self,
arg=None,
alignmentgroup=None,
base=None,
basesrc=None,
cliponaxis=None,
constraintext=None,
customdata=None,
customdatasrc=None,
dx=None,
dy=None,
error_x=None,
error_y=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextanchor=None,
insidetextfont=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
offset=None,
offsetgroup=None,
offsetsrc=None,
opacity=None,
orientation=None,
outsidetextfont=None,
selected=None,
selectedpoints=None,
showlegend=None,
stream=None,
text=None,
textangle=None,
textfont=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
unselected=None,
visible=None,
width=None,
widthsrc=None,
x=None,
x0=None,
xaxis=None,
xcalendar=None,
xhoverformat=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
ycalendar=None,
yhoverformat=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
zorder=None,
alignmentgroup: str|None = None,
base: Any|None = None,
basesrc: str|None = None,
cliponaxis: bool|None = None,
constraintext: Any|None = None,
customdata: NDArray|None = None,
customdatasrc: str|None = None,
dx: int|float|None = None,
dy: int|float|None = None,
error_x: None|None = None,
error_y: None|None = None,
hoverinfo: Any|None = None,
hoverinfosrc: str|None = None,
hoverlabel: None|None = None,
hovertemplate: str|None = None,
hovertemplatesrc: str|None = None,
hovertext: str|None = None,
hovertextsrc: str|None = None,
ids: NDArray|None = None,
idssrc: str|None = None,
insidetextanchor: Any|None = None,
insidetextfont: None|None = None,
legend: str|None = None,
legendgroup: str|None = None,
legendgrouptitle: None|None = None,
legendrank: int|float|None = None,
legendwidth: int|float|None = None,
marker: None|None = None,
meta: Any|None = None,
metasrc: str|None = None,
name: str|None = None,
offset: int|float|None = None,
offsetgroup: str|None = None,
offsetsrc: str|None = None,
opacity: int|float|None = None,
orientation: Any|None = None,
outsidetextfont: None|None = None,
selected: None|None = None,
selectedpoints: Any|None = None,
showlegend: bool|None = None,
stream: None|None = None,
text: str|None = None,
textangle: int|float|None = None,
textfont: None|None = None,
textposition: Any|None = None,
textpositionsrc: str|None = None,
textsrc: str|None = None,
texttemplate: str|None = None,
texttemplatesrc: str|None = None,
uid: str|None = None,
uirevision: Any|None = None,
unselected: None|None = None,
visible: Any|None = None,
width: int|float|None = None,
widthsrc: str|None = None,
x: NDArray|None = None,
x0: Any|None = None,
xaxis: str|None = None,
xcalendar: Any|None = None,
xhoverformat: str|None = None,
xperiod: Any|None = None,
xperiod0: Any|None = None,
xperiodalignment: Any|None = None,
xsrc: str|None = None,
y: NDArray|None = None,
y0: Any|None = None,
yaxis: str|None = None,
ycalendar: Any|None = None,
yhoverformat: str|None = None,
yperiod: Any|None = None,
yperiod0: Any|None = None,
yperiodalignment: Any|None = None,
ysrc: str|None = None,
zorder: int|None = None,
**kwargs
):
"""
Expand Down
Loading

0 comments on commit f949f65

Please sign in to comment.