Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 51db9bc

Browse files
committed
Use optional_imports instead of _*_imported.
1 parent a617845 commit 51db9bc

25 files changed

+122
-222
lines changed

plotly/figure_factory/_annotated_heatmap.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
from __future__ import absolute_import
22

3-
from plotly import exceptions
3+
from plotly import exceptions, optional_imports
44
from plotly.figure_factory import utils
55
from plotly.graph_objs import graph_objs
6-
from plotly.tools import _numpy_imported
76

8-
if _numpy_imported:
9-
import numpy as np
7+
# Optional imports, may be None for users that only use our core functionality.
8+
np = optional_imports.get_module('numpy')
109

1110

1211
def validate_annotated_heatmap(z, x, y, annotation_text):
@@ -206,7 +205,7 @@ def get_z_mid(self):
206205
207206
:rtype (float) z_avg: average val from z matrix
208207
"""
209-
if _numpy_imported and isinstance(self.z, np.ndarray):
208+
if np and isinstance(self.z, np.ndarray):
210209
z_min = np.amin(self.z)
211210
z_max = np.amax(self.z)
212211
else:

plotly/figure_factory/_dendrogram.py

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,14 @@
44

55
from collections import OrderedDict
66

7-
from plotly import exceptions
7+
from plotly import exceptions, optional_imports
88
from plotly.graph_objs import graph_objs
9-
from plotly.tools import (_numpy_imported, _scipy_imported,
10-
_scipy__cluster__hierarchy_imported,
11-
_scipy__spatial_imported)
129

13-
if _numpy_imported:
14-
import numpy as np
15-
16-
if _scipy_imported:
17-
import scipy as scp
18-
19-
if _scipy__cluster__hierarchy_imported:
20-
import scipy.cluster.hierarchy as sch
21-
22-
if _scipy__spatial_imported:
23-
import scipy.spatial as scs
10+
# Optional imports, may be None for users that only use our core functionality.
11+
np = optional_imports.get_module('numpy')
12+
scp = optional_imports.get_module('scipy')
13+
sch = optional_imports.get_module('scipy.cluster.hierarchy')
14+
scs = optional_imports.get_module('scipy.spatial')
2415

2516

2617
def create_dendrogram(X, orientation="bottom", labels=None,
@@ -82,10 +73,7 @@ def create_dendrogram(X, orientation="bottom", labels=None,
8273
url = py.plot(fig, filename='pandas-dendrogram')
8374
```
8475
"""
85-
dependencies = (_scipy_imported and _scipy__spatial_imported and
86-
_scipy__cluster__hierarchy_imported)
87-
88-
if dependencies is False:
76+
if not scp or not scs or not sch:
8977
raise ImportError("FigureFactory.create_dendrogram requires scipy, \
9078
scipy.spatial and scipy.hierarchy")
9179

plotly/figure_factory/_distplot.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
from __future__ import absolute_import
22

3-
from plotly import exceptions
3+
from plotly import exceptions, optional_imports
44
from plotly.figure_factory import utils
55
from plotly.graph_objs import graph_objs
6-
from plotly.tools import _numpy_imported, _pandas_imported, _scipy_imported
76

8-
if _numpy_imported:
9-
import numpy as np
10-
11-
if _pandas_imported:
12-
import pandas as pd
13-
14-
if _scipy_imported:
15-
import scipy
16-
import scipy.stats
7+
# Optional imports, may be None for users that only use our core functionality.
8+
np = optional_imports.get_module('numpy')
9+
pd = optional_imports.get_module('pandas')
10+
scipy = optional_imports.get_module('scipy')
11+
scipy_stats = optional_imports.get_module('scipy.stats')
1712

1813

1914
DEFAULT_HISTNORM = 'probability density'
@@ -29,9 +24,9 @@ def validate_distplot(hist_data, curve_type):
2924
'normal').
3025
"""
3126
hist_data_types = (list,)
32-
if _numpy_imported:
27+
if np:
3328
hist_data_types += (np.ndarray,)
34-
if _pandas_imported:
29+
if pd:
3530
hist_data_types += (pd.core.series.Series,)
3631

3732
if not isinstance(hist_data[0], hist_data_types):
@@ -47,7 +42,7 @@ def validate_distplot(hist_data, curve_type):
4742
raise exceptions.PlotlyError("curve_type must be defined as "
4843
"'kde' or 'normal'")
4944

50-
if _scipy_imported is False:
45+
if not scipy:
5146
raise ImportError("FigureFactory.create_distplot requires scipy")
5247

5348

@@ -312,7 +307,7 @@ def make_kde(self):
312307
self.curve_x[index] = [self.start[index] +
313308
x * (self.end[index] - self.start[index])
314309
/ 500 for x in range(500)]
315-
self.curve_y[index] = (scipy.stats.gaussian_kde
310+
self.curve_y[index] = (scipy_stats.gaussian_kde
316311
(self.hist_data[index])
317312
(self.curve_x[index]))
318313

@@ -345,12 +340,12 @@ def make_normal(self):
345340
sd = [None] * self.trace_number
346341

347342
for index in range(self.trace_number):
348-
mean[index], sd[index] = (scipy.stats.norm.fit
343+
mean[index], sd[index] = (scipy_stats.norm.fit
349344
(self.hist_data[index]))
350345
self.curve_x[index] = [self.start[index] +
351346
x * (self.end[index] - self.start[index])
352347
/ 500 for x in range(500)]
353-
self.curve_y[index] = scipy.stats.norm.pdf(
348+
self.curve_y[index] = scipy_stats.norm.pdf(
354349
self.curve_x[index], loc=mean[index], scale=sd[index])
355350

356351
if self.histnorm == ALTERNATIVE_HISTNORM:

plotly/figure_factory/_gantt.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,10 @@
22

33
from numbers import Number
44

5-
from plotly import exceptions
5+
from plotly import exceptions, optional_imports
66
from plotly.figure_factory import utils
7-
from plotly.tools import _pandas_imported
87

9-
if _pandas_imported:
10-
import pandas as pd
8+
pd = optional_imports.get_module('pandas')
119

1210
REQUIRED_GANTT_KEYS = ['Task', 'Start', 'Finish']
1311

@@ -16,7 +14,7 @@ def validate_gantt(df):
1614
"""
1715
Validates the inputted dataframe or list
1816
"""
19-
if _pandas_imported and isinstance(df, pd.core.frame.DataFrame):
17+
if pd and isinstance(df, pd.core.frame.DataFrame):
2018
# validate that df has all the required keys
2119
for key in REQUIRED_GANTT_KEYS:
2220
if key not in df:

plotly/figure_factory/_scatterplot.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
from __future__ import absolute_import
22

3-
from plotly import exceptions
3+
from plotly import exceptions, optional_imports
44
from plotly.figure_factory import utils
55
from plotly.graph_objs import graph_objs
6-
from plotly.tools import _pandas_imported, make_subplots
6+
from plotly.tools import make_subplots
77

8-
if _pandas_imported:
9-
import pandas as pd
8+
pd = optional_imports.get_module('pandas')
109

1110
DIAG_CHOICES = ['scatter', 'histogram', 'box']
1211
VALID_COLORMAP_TYPES = ['cat', 'seq']
@@ -88,7 +87,7 @@ def validate_scatterplotmatrix(df, index, diag, colormap_type, **kwargs):
8887
:raises: (PlotlyError) If kwargs contains 'size', 'color' or
8988
'colorscale'
9089
"""
91-
if _pandas_imported is False:
90+
if not pd:
9291
raise ImportError("FigureFactory.scatterplotmatrix requires "
9392
"a pandas DataFrame.")
9493

plotly/figure_factory/_streamline.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,11 @@
22

33
import math
44

5-
from plotly import exceptions
5+
from plotly import exceptions, optional_imports
66
from plotly.figure_factory import utils
77
from plotly.graph_objs import graph_objs
8-
from plotly.tools import _numpy_imported
98

10-
if _numpy_imported:
11-
import numpy as np
9+
np = optional_imports.get_module('numpy')
1210

1311

1412
def validate_streamline(x, y):
@@ -24,7 +22,7 @@ def validate_streamline(x, y):
2422
:raises: (PlotlyError) If x is not evenly spaced.
2523
:raises: (PlotlyError) If y is not evenly spaced.
2624
"""
27-
if _numpy_imported is False:
25+
if np is False:
2826
raise ImportError("FigureFactory.create_streamline requires numpy")
2927
for index in range(len(x) - 1):
3028
if ((x[index + 1] - x[index]) - (x[1] - x[0])) > .0001:

plotly/figure_factory/_table.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
from __future__ import absolute_import
22

3-
from plotly import exceptions
3+
from plotly import exceptions, optional_imports
44
from plotly.graph_objs import graph_objs
5-
from plotly.tools import _pandas_imported
65

7-
if _pandas_imported:
8-
import pandas as pd
6+
pd = optional_imports.get_module('pandas')
97

108

119
def validate_table(table_text, font_colors):
@@ -138,7 +136,7 @@ class _Table(object):
138136
"""
139137
def __init__(self, table_text, colorscale, font_colors, index,
140138
index_title, annotation_offset, **kwargs):
141-
if _pandas_imported and isinstance(table_text, pd.DataFrame):
139+
if pd and isinstance(table_text, pd.DataFrame):
142140
headers = table_text.columns.tolist()
143141
table_text_index = table_text.index.tolist()
144142
table_text = table_text.values.tolist()

plotly/figure_factory/_trisurf.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
from __future__ import absolute_import
22

3-
from plotly import colors, exceptions
3+
from plotly import colors, exceptions, optional_imports
44
from plotly.graph_objs import graph_objs
5-
from plotly.tools import _numpy_imported
65

7-
if _numpy_imported:
8-
import numpy as np
6+
np = optional_imports.get_module('numpy')
97

108

119
def map_face2color(face, colormap, scale, vmin, vmax):
@@ -81,7 +79,7 @@ def trisurf(x, y, z, simplices, show_colorbar, edges_color, scale,
8179
Refer to FigureFactory.create_trisurf() for docstring
8280
"""
8381
# numpy import check
84-
if _numpy_imported is False:
82+
if not np:
8583
raise ImportError("FigureFactory._trisurf() requires "
8684
"numpy imported.")
8785
points3D = np.vstack((x, y, z)).T

plotly/figure_factory/_violin.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,14 @@
22

33
from numbers import Number
44

5-
from plotly import exceptions
5+
from plotly import exceptions, optional_imports
66
from plotly.figure_factory import utils
77
from plotly.graph_objs import graph_objs
8-
from plotly.tools import (_numpy_imported, _pandas_imported, _scipy_imported,
9-
make_subplots)
8+
from plotly.tools import make_subplots
109

11-
if _pandas_imported:
12-
import pandas as pd
13-
14-
if _numpy_imported:
15-
import numpy as np
16-
17-
if _scipy_imported:
18-
from scipy import stats
10+
pd = optional_imports.get_module('pandas')
11+
np = optional_imports.get_module('numpy')
12+
scipy_stats = optional_imports.get_module('scipy.stats')
1913

2014

2115
def calc_stats(data):
@@ -178,7 +172,7 @@ def violinplot(vals, fillcolor='#1f77b4', rugplot=True):
178172
d2 = calc_stats(vals)['d2']
179173

180174
# kernel density estimation of pdf
181-
pdf = stats.gaussian_kde(vals)
175+
pdf = scipy_stats.gaussian_kde(vals)
182176
# grid over the data interval
183177
xx = np.linspace(vals_min, vals_max, 100)
184178
# evaluate the pdf at the grid xx
@@ -554,7 +548,7 @@ def create_violin(data, data_header=None, group_header=None, colors=None,
554548
raise exceptions.PlotlyError("If data is a list, it must "
555549
"contain only numbers.")
556550

557-
if _pandas_imported and isinstance(data, pd.core.frame.DataFrame):
551+
if pd and isinstance(data, pd.core.frame.DataFrame):
558552
if data_header is None:
559553
raise exceptions.PlotlyError("data_header must be the "
560554
"column name with the "

plotly/offline/offline.py

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,12 @@
1515
from requests.compat import json as _json
1616

1717
import plotly
18-
from plotly import tools, utils
18+
from plotly import optional_imports, tools, utils
1919
from plotly.exceptions import PlotlyError
2020

21-
try:
22-
import IPython
23-
from IPython.display import HTML, display
24-
_ipython_imported = True
25-
except ImportError:
26-
_ipython_imported = False
27-
28-
try:
29-
import matplotlib
30-
_matplotlib_imported = True
31-
except ImportError:
32-
_matplotlib_imported = False
21+
ipython = optional_imports.get_module('IPython')
22+
ipython_display = optional_imports.get_module('IPython.display')
23+
matplotlib = optional_imports.get_module('matplotlib')
3324

3425
__PLOTLY_OFFLINE_INITIALIZED = False
3526

@@ -112,7 +103,7 @@ def init_notebook_mode(connected=False):
112103
your notebook, resulting in much larger notebook sizes compared to the case
113104
where `connected=True`.
114105
"""
115-
if not _ipython_imported:
106+
if not ipython:
116107
raise ImportError('`iplot` can only run inside an IPython Notebook.')
117108

118109
global __PLOTLY_OFFLINE_INITIALIZED
@@ -149,7 +140,7 @@ def init_notebook_mode(connected=False):
149140
'</script>'
150141
'').format(script=get_plotlyjs())
151142

152-
display(HTML(script_inject))
143+
ipython_display.display(ipython_display.HTML(script_inject))
153144
__PLOTLY_OFFLINE_INITIALIZED = True
154145

155146

@@ -333,7 +324,7 @@ def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
333324
'plotly.offline.init_notebook_mode() '
334325
'# run at the start of every ipython notebook',
335326
]))
336-
if not tools._ipython_imported:
327+
if not ipython:
337328
raise ImportError('`iplot` can only run inside an IPython Notebook.')
338329

339330
config = {}
@@ -344,7 +335,7 @@ def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
344335
figure_or_data, config, validate, '100%', 525, True
345336
)
346337

347-
display(HTML(plot_html))
338+
ipython_display.display(ipython_display.HTML(plot_html))
348339

349340
if image:
350341
if image not in __IMAGE_FORMATS:
@@ -360,7 +351,7 @@ def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
360351
# allow time for the plot to draw
361352
time.sleep(1)
362353
# inject code to download an image of the plot
363-
display(HTML(script))
354+
ipython_display.display(ipython_display.HTML(script))
364355

365356

366357
def plot(figure_or_data, show_link=True, link_text='Export to plot.ly',
@@ -690,7 +681,7 @@ def enable_mpl_offline(resize=False, strip_style=False,
690681
"""
691682
init_notebook_mode()
692683

693-
ip = IPython.core.getipython.get_ipython()
684+
ip = ipython.core.getipython.get_ipython()
694685
formatter = ip.display_formatter.formatters['text/html']
695686
formatter.for_type(matplotlib.figure.Figure,
696687
lambda fig: iplot_mpl(fig, resize, strip_style, verbose,

plotly/tests/test_core/test_tools/test_figure_factory.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1649,8 +1649,6 @@ def test_2D_density_all_args(self):
16491649

16501650
# def test_scipy_import_error(self):
16511651

1652-
# # make sure Import Error is raised when _scipy_imported = False
1653-
16541652
# hist_data = [[1.1, 1.1, 2.5, 3.0, 3.5,
16551653
# 3.5, 4.1, 4.4, 4.5, 4.5,
16561654
# 5.0, 5.0, 5.2, 5.5, 5.5,

0 commit comments

Comments
 (0)