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

Skip to content

Commit 466c4a5

Browse files
committed
Lazy import of private modules
1 parent 3e90025 commit 466c4a5

File tree

11 files changed

+62
-12
lines changed

11 files changed

+62
-12
lines changed

doc/api/api_changes.rst

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ subplotparams will collapse axes to zero width or height. This prevents
4444
``tight_layout`` from being executed. Similarly
4545
`.tight_layout.get_tight_layout_figure` will return None.
4646

47+
To improve import (startup) time, private modules are now imported lazily.
48+
These modules are no longer available at these locations:
49+
50+
- `matplotlib.backends.backend_agg._png`
51+
- `matplotlib.contour._contour`
52+
- `matplotlib.image._png`
53+
- `matplotlib.mathtext._png`
54+
- `matplotlib.testing.compare._png`
55+
- `matplotlib.texmanager._png`
56+
- `matplotlib.tri.triangulation._tri`
57+
- `matplotlib.tri.triangulation._qhull`
58+
- `matplotlib.tri.tricontour._tri`
59+
- `matplotlib.tri.trifinder._tri`
60+
4761
API Changes for 3.0.0
4862
=====================
4963

lib/matplotlib/backends/backend_agg.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
from matplotlib import colors as mcolors
3939

4040
from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
41-
from matplotlib import _png
4241

4342
from matplotlib.backend_bases import _has_pil
4443

@@ -502,6 +501,8 @@ def print_png(self, filename_or_obj, *args, **kwargs):
502501
https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
503502
504503
"""
504+
from matplotlib import _png
505+
505506
FigureCanvasAgg.draw(self)
506507
renderer = self.get_renderer()
507508

lib/matplotlib/contour.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from numpy import ma
99

1010
import matplotlib as mpl
11-
import matplotlib._contour as _contour
1211
import matplotlib.path as mpath
1312
import matplotlib.ticker as ticker
1413
import matplotlib.cm as cm
@@ -1481,6 +1480,8 @@ def _process_args(self, *args, **kwargs):
14811480
self._mins = args[0]._mins
14821481
self._maxs = args[0]._maxs
14831482
else:
1483+
import matplotlib._contour as _contour
1484+
14841485
self._corner_mask = kwargs.pop('corner_mask', None)
14851486
if self._corner_mask is None:
14861487
self._corner_mask = mpl.rcParams['contour.corner_mask']

lib/matplotlib/image.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121

2222
# For clarity, names from _image are given explicitly in this module:
2323
import matplotlib._image as _image
24-
import matplotlib._png as _png
2524

2625
# For user convenience, the names from _image are also imported into
2726
# the image namespace:
@@ -613,6 +612,7 @@ def contains(self, mouseevent):
613612

614613
def write_png(self, fname):
615614
"""Write the image to png file with fname"""
615+
from matplotlib import _png
616616
im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
617617
bytes=True, norm=True)
618618
_png.write_png(im, fname)
@@ -1340,7 +1340,11 @@ def imread(fname, format=None):
13401340
.. _Pillow documentation: http://pillow.readthedocs.io/en/latest/
13411341
"""
13421342

1343-
handlers = {'png': _png.read_png, }
1343+
def read_png(*args, **kwargs):
1344+
from matplotlib import _png
1345+
return _png.read_png(*args, **kwargs)
1346+
1347+
handlers = {'png': read_png, }
13441348
if format is None:
13451349
if isinstance(fname, str):
13461350
parsed = urllib.parse.urlparse(fname)

lib/matplotlib/mathtext.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232
ParserElement.enablePackrat()
3333

34-
from matplotlib import _png, cbook, colors as mcolors, get_data_path, rcParams
34+
from matplotlib import cbook, colors as mcolors, get_data_path, rcParams
3535
from matplotlib.afm import AFM
3636
from matplotlib.cbook import get_realpath_and_stat
3737
from matplotlib.ft2font import FT2Image, KERNING_DEFAULT, LOAD_NO_HINTING
@@ -3446,6 +3446,7 @@ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
34463446
Returns the offset of the baseline from the bottom of the
34473447
image in pixels.
34483448
"""
3449+
from matplotlib import _png
34493450
rgba, depth = self.to_rgba(
34503451
texstr, color=color, dpi=dpi, fontsize=fontsize)
34513452
_png.write_png(rgba, filename)

lib/matplotlib/testing/compare.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import matplotlib
1919
from matplotlib.testing.exceptions import ImageComparisonFailure
20-
from matplotlib import _png, cbook
20+
from matplotlib import cbook
2121

2222
__all__ = ['compare_float', 'compare_images', 'comparable_formats']
2323

@@ -386,6 +386,8 @@ def compare_images(expected, actual, tol, in_decorator=False):
386386
compare_images(img1, img2, 0.001):
387387
388388
"""
389+
from matplotlib import _png
390+
389391
if not os.path.exists(actual):
390392
raise Exception("Output image %s does not exist." % actual)
391393

@@ -456,6 +458,8 @@ def save_diff_image(expected, actual, output):
456458
File path to save difference image to.
457459
'''
458460
# Drop alpha channels, similarly to compare_images.
461+
from matplotlib import _png
462+
459463
expectedImage = _png.read_png(expected)[..., :3]
460464
actualImage = _png.read_png(actual)[..., :3]
461465
actualImage, expectedImage = crop_to_same(

lib/matplotlib/tests/test_basic.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import builtins
2+
import subprocess
3+
import sys
24

35
import matplotlib
6+
from matplotlib.cbook import dedent
47

58

69
def test_simple():
@@ -34,3 +37,24 @@ def test_override_builtins():
3437

3538
def test_verbose():
3639
assert isinstance(matplotlib.verbose, matplotlib.Verbose)
40+
41+
42+
def test_lazy_imports():
43+
source = dedent("""
44+
import sys
45+
46+
import matplotlib.figure
47+
import matplotlib.backend_bases
48+
import matplotlib.pyplot
49+
50+
assert 'matplotlib._png' not in sys.modules
51+
assert 'matplotlib._tri' not in sys.modules
52+
assert 'matplotlib._qhull' not in sys.modules
53+
assert 'matplotlib._contour' not in sys.modules
54+
""")
55+
56+
subprocess.check_call([
57+
sys.executable,
58+
'-c',
59+
source
60+
])

lib/matplotlib/texmanager.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
import numpy as np
4141

4242
import matplotlib as mpl
43-
from matplotlib import _png, cbook, dviread, rcParams
43+
from matplotlib import cbook, dviread, rcParams
4444

4545
_log = logging.getLogger(__name__)
4646

@@ -414,6 +414,7 @@ def get_ps_bbox(self, tex, fontsize):
414414

415415
def get_grey(self, tex, fontsize=None, dpi=None):
416416
"""Return the alpha channel."""
417+
from matplotlib import _png
417418
key = tex, self.get_font_config(), fontsize, dpi
418419
alpha = self.grey_arrayd.get(key)
419420
if alpha is None:

lib/matplotlib/tri/triangulation.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
import numpy as np
22

3-
import matplotlib._tri as _tri
4-
import matplotlib._qhull as _qhull
5-
63

74
class Triangulation(object):
85
"""
@@ -39,6 +36,8 @@ class Triangulation(object):
3936
triangles formed from colinear points, or overlapping triangles.
4037
"""
4138
def __init__(self, x, y, triangles=None, mask=None):
39+
from matplotlib import _qhull
40+
4241
self.x = np.asarray(x, dtype=np.float64)
4342
self.y = np.asarray(y, dtype=np.float64)
4443
if self.x.shape != self.y.shape or self.x.ndim != 1:
@@ -106,6 +105,7 @@ def get_cpp_triangulation(self):
106105
Return the underlying C++ Triangulation object, creating it
107106
if necessary.
108107
"""
108+
from matplotlib import _tri
109109
if self._cpp_triangulation is None:
110110
self._cpp_triangulation = _tri.Triangulation(
111111
self.x, self.y, self.triangles, self.mask, self._edges,

lib/matplotlib/tri/tricontour.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from matplotlib.contour import ContourSet
44
from matplotlib.tri.triangulation import Triangulation
5-
import matplotlib._tri as _tri
65

76

87
class TriContourSet(ContourSet):
@@ -44,6 +43,7 @@ def _process_args(self, *args, **kwargs):
4443
if self.levels is None:
4544
self.levels = args[0].levels
4645
else:
46+
from matplotlib import _tri
4747
tri, z = self._contour_args(args, kwargs)
4848
C = _tri.TriContourGenerator(tri.get_cpp_triangulation(), z)
4949
self._mins = [tri.x.min(), tri.y.min()]

lib/matplotlib/tri/trifinder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import numpy as np
22

33
from matplotlib.tri import Triangulation
4-
import matplotlib._tri as _tri
54

65

76
class TriFinder(object):
@@ -35,6 +34,7 @@ class TrapezoidMapTriFinder(TriFinder):
3534
this should not be relied upon.
3635
"""
3736
def __init__(self, triangulation):
37+
from matplotlib import _tri
3838
TriFinder.__init__(self, triangulation)
3939
self._cpp_trifinder = _tri.TrapezoidMapTriFinder(
4040
triangulation.get_cpp_triangulation())

0 commit comments

Comments
 (0)