Skip to content

Commit e45d8b0

Browse files
committed
Rework backend loading.
This is preliminary work towards fixing the runtime detection of default backend problem (the first step being to make it easier to check whether a backend *can* be loaded). No publically visible API is changed. Backend loading now defines default versions of `backend_version`, `draw_if_interactive`, and `show` using the same inheritance strategy as builtin backends do. For non-interactive backends (i.e., `FigureManager == FigureManagerBase`), restore the default implementation of `show()` that prints a warning when run from a console (the backend refactor accidentally removed this error message as it provided a silent default `show()`). The `_Backend` class had to be moved to the end of the module as `FigureManagerBase` needs to be defined first. The `ShowBase` class had to be moved even after that as it depends on the `_Backend` class.
1 parent 477c1dc commit e45d8b0

File tree

5 files changed

+159
-168
lines changed

5 files changed

+159
-168
lines changed

lib/matplotlib/backend_bases.py

+128-114
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
from contextlib import contextmanager
4242
from functools import partial
4343
import importlib
44+
import inspect
4445
import io
4546
import os
4647
import sys
@@ -49,6 +50,7 @@
4950
from weakref import WeakKeyDictionary
5051

5152
import numpy as np
53+
import matplotlib
5254
import matplotlib.cbook as cbook
5355
import matplotlib.colors as colors
5456
import matplotlib.transforms as transforms
@@ -136,120 +138,6 @@ def get_registered_canvas_class(format):
136138
return backend_class
137139

138140

139-
class _Backend(object):
140-
# A backend can be defined by using the following pattern:
141-
#
142-
# @_Backend.export
143-
# class FooBackend(_Backend):
144-
# # override the attributes and methods documented below.
145-
146-
# The following attributes and methods must be overridden by subclasses.
147-
148-
# The `FigureCanvas` and `FigureManager` classes must be defined.
149-
FigureCanvas = None
150-
FigureManager = None
151-
152-
# The following methods must be left as None for non-interactive backends.
153-
# For interactive backends, `trigger_manager_draw` should be a function
154-
# taking a manager as argument and triggering a canvas draw, and `mainloop`
155-
# should be a function taking no argument and starting the backend main
156-
# loop.
157-
trigger_manager_draw = None
158-
mainloop = None
159-
160-
# The following methods will be automatically defined and exported, but
161-
# can be overridden.
162-
163-
@classmethod
164-
def new_figure_manager(cls, num, *args, **kwargs):
165-
"""Create a new figure manager instance.
166-
"""
167-
# This import needs to happen here due to circular imports.
168-
from matplotlib.figure import Figure
169-
fig_cls = kwargs.pop('FigureClass', Figure)
170-
fig = fig_cls(*args, **kwargs)
171-
return cls.new_figure_manager_given_figure(num, fig)
172-
173-
@classmethod
174-
def new_figure_manager_given_figure(cls, num, figure):
175-
"""Create a new figure manager instance for the given figure.
176-
"""
177-
canvas = cls.FigureCanvas(figure)
178-
manager = cls.FigureManager(canvas, num)
179-
return manager
180-
181-
@classmethod
182-
def draw_if_interactive(cls):
183-
if cls.trigger_manager_draw is not None and is_interactive():
184-
manager = Gcf.get_active()
185-
if manager:
186-
cls.trigger_manager_draw(manager)
187-
188-
@classmethod
189-
def show(cls, block=None):
190-
"""Show all figures.
191-
192-
`show` blocks by calling `mainloop` if *block* is ``True``, or if it
193-
is ``None`` and we are neither in IPython's ``%pylab`` mode, nor in
194-
`interactive` mode.
195-
"""
196-
if cls.mainloop is None:
197-
return
198-
managers = Gcf.get_all_fig_managers()
199-
if not managers:
200-
return
201-
for manager in managers:
202-
manager.show()
203-
if block is None:
204-
# Hack: Are we in IPython's pylab mode?
205-
from matplotlib import pyplot
206-
try:
207-
# IPython versions >= 0.10 tack the _needmain attribute onto
208-
# pyplot.show, and always set it to False, when in %pylab mode.
209-
ipython_pylab = not pyplot.show._needmain
210-
except AttributeError:
211-
ipython_pylab = False
212-
block = not ipython_pylab and not is_interactive()
213-
# TODO: The above is a hack to get the WebAgg backend working with
214-
# ipython's `%pylab` mode until proper integration is implemented.
215-
if get_backend() == "WebAgg":
216-
block = True
217-
if block:
218-
cls.mainloop()
219-
220-
# This method is the one actually exporting the required methods.
221-
222-
@staticmethod
223-
def export(cls):
224-
for name in ["FigureCanvas",
225-
"FigureManager",
226-
"new_figure_manager",
227-
"new_figure_manager_given_figure",
228-
"draw_if_interactive",
229-
"show"]:
230-
setattr(sys.modules[cls.__module__], name, getattr(cls, name))
231-
232-
# For back-compatibility, generate a shim `Show` class.
233-
234-
class Show(ShowBase):
235-
def mainloop(self):
236-
return cls.mainloop()
237-
238-
setattr(sys.modules[cls.__module__], "Show", Show)
239-
return cls
240-
241-
242-
class ShowBase(_Backend):
243-
"""
244-
Simple base class to generate a show() callable in backends.
245-
246-
Subclass must override mainloop() method.
247-
"""
248-
249-
def __call__(self, block=None):
250-
return self.show(block=block)
251-
252-
253141
class RendererBase(object):
254142
"""An abstract base class to handle drawing/rendering operations.
255143
@@ -3362,3 +3250,129 @@ def set_message(self, s):
33623250
Message text
33633251
"""
33643252
pass
3253+
3254+
3255+
class _Backend(object):
3256+
# A backend can be defined by using the following pattern:
3257+
#
3258+
# @_Backend.export
3259+
# class FooBackend(_Backend):
3260+
# # override the attributes and methods documented below.
3261+
3262+
# May be overridden by the subclass.
3263+
backend_version = "unknown"
3264+
# The `FigureCanvas` class must be overridden.
3265+
FigureCanvas = None
3266+
# For interactive backends, the `FigureManager` class must be overridden.
3267+
FigureManager = FigureManagerBase
3268+
# The following methods must be left as None for non-interactive backends.
3269+
# For interactive backends, `trigger_manager_draw` should be a function
3270+
# taking a manager as argument and triggering a canvas draw, and `mainloop`
3271+
# should be a function taking no argument and starting the backend main
3272+
# loop.
3273+
trigger_manager_draw = None
3274+
mainloop = None
3275+
3276+
# The following methods will be automatically defined and exported, but
3277+
# can be overridden.
3278+
3279+
@classmethod
3280+
def new_figure_manager(cls, num, *args, **kwargs):
3281+
"""Create a new figure manager instance.
3282+
"""
3283+
# This import needs to happen here due to circular imports.
3284+
from matplotlib.figure import Figure
3285+
fig_cls = kwargs.pop('FigureClass', Figure)
3286+
fig = fig_cls(*args, **kwargs)
3287+
return cls.new_figure_manager_given_figure(num, fig)
3288+
3289+
@classmethod
3290+
def new_figure_manager_given_figure(cls, num, figure):
3291+
"""Create a new figure manager instance for the given figure.
3292+
"""
3293+
canvas = cls.FigureCanvas(figure)
3294+
manager = cls.FigureManager(canvas, num)
3295+
return manager
3296+
3297+
@classmethod
3298+
def draw_if_interactive(cls):
3299+
if cls.trigger_manager_draw is not None and is_interactive():
3300+
manager = Gcf.get_active()
3301+
if manager:
3302+
cls.trigger_manager_draw(manager)
3303+
3304+
@classmethod
3305+
def show(cls, block=None):
3306+
"""Show all figures.
3307+
3308+
`show` blocks by calling `mainloop` if *block* is ``True``, or if it
3309+
is ``None`` and we are neither in IPython's ``%pylab`` mode, nor in
3310+
`interactive` mode.
3311+
"""
3312+
if cls.mainloop is None:
3313+
frame = inspect.currentframe()
3314+
while frame:
3315+
if frame.f_code.co_filename in [
3316+
"<stdin>", "<ipython console>"]:
3317+
warnings.warn("""\
3318+
Your currently selected backend does not support show().
3319+
Please select a GUI backend in your matplotlibrc file ('{}')
3320+
or with matplotlib.use()""".format(matplotlib.matplotlib_fname()))
3321+
break
3322+
else:
3323+
frame = frame.f_back
3324+
return
3325+
managers = Gcf.get_all_fig_managers()
3326+
if not managers:
3327+
return
3328+
for manager in managers:
3329+
manager.show()
3330+
if block is None:
3331+
# Hack: Are we in IPython's pylab mode?
3332+
from matplotlib import pyplot
3333+
try:
3334+
# IPython versions >= 0.10 tack the _needmain attribute onto
3335+
# pyplot.show, and always set it to False, when in %pylab mode.
3336+
ipython_pylab = not pyplot.show._needmain
3337+
except AttributeError:
3338+
ipython_pylab = False
3339+
block = not ipython_pylab and not is_interactive()
3340+
# TODO: The above is a hack to get the WebAgg backend working with
3341+
# ipython's `%pylab` mode until proper integration is implemented.
3342+
if get_backend() == "WebAgg":
3343+
block = True
3344+
if block:
3345+
cls.mainloop()
3346+
3347+
# This method is the one actually exporting the required methods.
3348+
3349+
@staticmethod
3350+
def export(cls):
3351+
for name in ["backend_version",
3352+
"FigureCanvas",
3353+
"FigureManager",
3354+
"new_figure_manager",
3355+
"new_figure_manager_given_figure",
3356+
"draw_if_interactive",
3357+
"show"]:
3358+
setattr(sys.modules[cls.__module__], name, getattr(cls, name))
3359+
3360+
# For back-compatibility, generate a shim `Show` class.
3361+
3362+
class Show(ShowBase):
3363+
def mainloop(self):
3364+
return cls.mainloop()
3365+
3366+
setattr(sys.modules[cls.__module__], "Show", Show)
3367+
return cls
3368+
3369+
3370+
class ShowBase(_Backend):
3371+
"""
3372+
Simple base class to generate a show() callable in backends.
3373+
3374+
Subclass must override mainloop() method.
3375+
"""
3376+
3377+
def __call__(self, block=None):
3378+
return self.show(block=block)

lib/matplotlib/backends/__init__.py

+27-45
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33

44
import six
55

6-
import matplotlib
7-
import inspect
8-
import traceback
9-
import warnings
6+
import importlib
107
import logging
8+
import traceback
9+
10+
import matplotlib
11+
from matplotlib.backend_bases import _Backend
12+
1113

1214
_log = logging.getLogger(__name__)
1315

@@ -47,50 +49,30 @@ def pylab_setup(name=None):
4749
'''
4850
# Import the requested backend into a generic module object
4951
if name is None:
50-
# validates, to match all_backends
5152
name = matplotlib.get_backend()
52-
if name.startswith('module://'):
53-
backend_name = name[9:]
54-
else:
55-
backend_name = 'backend_' + name
56-
backend_name = backend_name.lower() # until we banish mixed case
57-
backend_name = 'matplotlib.backends.%s' % backend_name.lower()
58-
59-
# the last argument is specifies whether to use absolute or relative
60-
# imports. 0 means only perform absolute imports.
61-
backend_mod = __import__(backend_name, globals(), locals(),
62-
[backend_name], 0)
63-
64-
# Things we pull in from all backends
65-
new_figure_manager = backend_mod.new_figure_manager
66-
67-
# image backends like pdf, agg or svg do not need to do anything
68-
# for "show" or "draw_if_interactive", so if they are not defined
69-
# by the backend, just do nothing
70-
def do_nothing_show(*args, **kwargs):
71-
frame = inspect.currentframe()
72-
fname = frame.f_back.f_code.co_filename
73-
if fname in ('<stdin>', '<ipython console>'):
74-
warnings.warn("""
75-
Your currently selected backend, '%s' does not support show().
76-
Please select a GUI backend in your matplotlibrc file ('%s')
77-
or with matplotlib.use()""" %
78-
(name, matplotlib.matplotlib_fname()))
79-
80-
def do_nothing(*args, **kwargs):
81-
pass
82-
83-
backend_version = getattr(backend_mod, 'backend_version', 'unknown')
84-
85-
show = getattr(backend_mod, 'show', do_nothing_show)
86-
87-
draw_if_interactive = getattr(backend_mod, 'draw_if_interactive',
88-
do_nothing)
89-
90-
_log.info('backend %s version %s' % (name, backend_version))
53+
backend_name = (name[9:] if name.startswith("module://")
54+
else "matplotlib.backends.backend_{}".format(name.lower()))
55+
56+
backend_mod = importlib.import_module(backend_name)
57+
Backend = type(str("Backend"), (_Backend,), vars(backend_mod))
58+
_log.info('backend %s version %s', name, Backend.backend_version)
9159

9260
# need to keep a global reference to the backend for compatibility
9361
# reasons. See https://github.com/matplotlib/matplotlib/issues/6092
9462
global backend
9563
backend = name
96-
return backend_mod, new_figure_manager, draw_if_interactive, show
64+
65+
# We want to get functions out of a class namespace and call them *without
66+
# the first argument being an instance of the class*. This works directly
67+
# on Py3. On Py2, we need to remove the check that the first argument be
68+
# an instance of the class. The only relevant case is if `.im_self` is
69+
# None, in which case we need to use `.im_func` (if we have a bound method
70+
# (e.g. a classmethod), everything is fine).
71+
def _dont_check_first_arg(func):
72+
return (func.im_func if getattr(func, "im_self", 0) is None
73+
else func)
74+
75+
return (backend_mod,
76+
_dont_check_first_arg(Backend.new_figure_manager),
77+
_dont_check_first_arg(Backend.draw_if_interactive),
78+
_dont_check_first_arg(Backend.show))

lib/matplotlib/backends/backend_pdf.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -2599,11 +2599,9 @@ def print_pdf(self, filename, **kwargs):
25992599
file.close()
26002600

26012601

2602-
class FigureManagerPdf(FigureManagerBase):
2603-
pass
2602+
FigureManagerPdf = FigureManagerBase
26042603

26052604

26062605
@_Backend.export
26072606
class _BackendPdf(_Backend):
26082607
FigureCanvas = FigureCanvasPdf
2609-
FigureManager = FigureManagerPdf

lib/matplotlib/backends/backend_ps.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1728,8 +1728,7 @@ def pstoeps(tmpfile, bbox=None, rotated=False):
17281728
shutil.move(epsfile, tmpfile)
17291729

17301730

1731-
class FigureManagerPS(FigureManagerBase):
1732-
pass
1731+
FigureManagerPS = FigureManagerBase
17331732

17341733

17351734
# The following Python dictionary psDefs contains the entries for the
@@ -1775,4 +1774,3 @@ class FigureManagerPS(FigureManagerBase):
17751774
@_Backend.export
17761775
class _BackendPS(_Backend):
17771776
FigureCanvas = FigureCanvasPS
1778-
FigureManager = FigureManagerPS

0 commit comments

Comments
 (0)