Skip to content

Commit 8709eb4

Browse files
committed
import just once, and at the top
1 parent d97b774 commit 8709eb4

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

plotly/utils.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,25 @@
1313
import re
1414
import datetime
1515

16+
try:
17+
import numpy
18+
_numpy_imported = True
19+
except ImportError:
20+
_numpy_imported = False
21+
22+
try:
23+
import pandas
24+
_pandas_imported = True
25+
except ImportError:
26+
_pandas_imported = False
27+
28+
try:
29+
from sage.all import RR, ZZ
30+
_sage_imported = True
31+
except ImportError:
32+
_sage_imported = False
33+
34+
1635
### incase people are using threading, we lock file reads
1736
lock = threading.Lock()
1837

@@ -76,11 +95,10 @@ def ensure_dir_exists(directory):
7695
class NotEncodable(Exception):
7796
pass
7897

98+
7999
class _plotlyJSONEncoder(json.JSONEncoder):
80100
def numpyJSONEncoder(self, obj):
81-
try:
82-
import numpy
83-
except:
101+
if not _numpy_imported:
84102
raise NotEncodable
85103

86104
if type(obj).__module__.split('.')[0] == numpy.__name__:
@@ -101,13 +119,8 @@ def datetimeJSONEncoder(self, obj):
101119
%Y-%m-%d
102120
depending on what non-zero resolution was provided
103121
"""
104-
try:
105-
import pandas
106-
pandas_importable = True
107-
except:
108-
pandas_importable = False
109122

110-
if pandas_importable and obj is pandas.NaT:
123+
if _pandas_imported and obj is pandas.NaT:
111124
return None
112125

113126
if isinstance(obj, (datetime.datetime, datetime.date)):
@@ -127,9 +140,7 @@ def datetimeJSONEncoder(self, obj):
127140
raise NotEncodable
128141

129142
def pandasJSONEncoder(self, obj):
130-
try:
131-
import pandas
132-
except:
143+
if not _pandas_imported:
133144
raise NotEncodable
134145

135146
if isinstance(obj, pandas.Series):
@@ -150,9 +161,7 @@ def pandasJSONEncoder(self, obj):
150161
raise NotEncodable
151162

152163
def sageJSONEncoder(self, obj):
153-
try:
154-
from sage.all import RR, ZZ
155-
except:
164+
if not _sage_imported:
156165
raise NotEncodable
157166

158167
if obj in RR:

0 commit comments

Comments
 (0)