Skip to content

Commit 785ad6b

Browse files
author
Zack Cornelius
committed
Only attempt to import np/pd once in basevalidators
Use get_module to import numpy and pandas once at the load of basevalidators Significantly speeds up graph rendering when using large (10K entry) pandas dataframe columns. Graph rendering time changed from 1200-1500ms to 240-350ms by avoiding many (~10K) calls to get_module().
1 parent 168398e commit 785ad6b

File tree

1 file changed

+3
-9
lines changed

1 file changed

+3
-9
lines changed

Diff for: packages/python/plotly/_plotly_utils/basevalidators.py

+3-9
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414

1515
from _plotly_utils.optional_imports import get_module
1616

17+
np = get_module("numpy")
18+
pd = get_module("pandas")
19+
1720

1821
# back-port of fullmatch from Py3.4+
1922
def fullmatch(regex, string, flags=0):
@@ -35,8 +38,6 @@ def to_scalar_or_list(v):
3538
# Python native scalar type ('float' in the example above).
3639
# We explicitly check if is has the 'item' method, which conventionally
3740
# converts these types to native scalars.
38-
np = get_module("numpy")
39-
pd = get_module("pandas")
4041
if np and np.isscalar(v) and hasattr(v, "item"):
4142
return v.item()
4243
if isinstance(v, (list, tuple)):
@@ -73,8 +74,6 @@ def copy_to_readonly_numpy_array(v, kind=None, force_numeric=False):
7374
np.ndarray
7475
Numpy array with the 'WRITEABLE' flag set to False
7576
"""
76-
np = get_module("numpy")
77-
pd = get_module("pandas")
7877
assert np is not None
7978

8079
# ### Process kind ###
@@ -166,8 +165,6 @@ def is_homogeneous_array(v):
166165
"""
167166
Return whether a value is considered to be a homogeneous array
168167
"""
169-
np = get_module("numpy")
170-
pd = get_module("pandas")
171168
if (
172169
np
173170
and isinstance(v, np.ndarray)
@@ -739,7 +736,6 @@ def validate_coerce(self, v):
739736
# Pass None through
740737
pass
741738
elif self.array_ok and is_homogeneous_array(v):
742-
np = get_module("numpy")
743739
try:
744740
v_array = copy_to_readonly_numpy_array(v, force_numeric=True)
745741
except (ValueError, TypeError, OverflowError):
@@ -867,7 +863,6 @@ def validate_coerce(self, v):
867863
# Pass None through
868864
pass
869865
elif self.array_ok and is_homogeneous_array(v):
870-
np = get_module("numpy")
871866
v_array = copy_to_readonly_numpy_array(
872867
v, kind=("i", "u"), force_numeric=True
873868
)
@@ -1030,7 +1025,6 @@ def validate_coerce(self, v):
10301025
self.raise_invalid_elements(invalid_els)
10311026

10321027
if is_homogeneous_array(v):
1033-
np = get_module("numpy")
10341028

10351029
# If not strict, let numpy cast elements to strings
10361030
v = copy_to_readonly_numpy_array(v, kind="U")

0 commit comments

Comments
 (0)