Skip to content

Backport PR #11896 on branch v3.0.x #11953

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 29 additions & 11 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@

# cbook must import matplotlib only within function
# definitions, so it is safe to import from it here.
from . import cbook
from . import cbook, rcsetup
from matplotlib.cbook import (
MatplotlibDeprecationWarning, dedent, get_label, sanitize_sequence)
from matplotlib.cbook import mplDeprecation # deprecated
Expand Down Expand Up @@ -853,6 +853,10 @@ def __setitem__(self, key, val):
cbook.warn_deprecated(
"3.0", "{} is deprecated; in the future, examples will be "
"found relative to the 'datapath' directory.".format(key))
elif key == 'backend':
if val is rcsetup._auto_backend_sentinel:
if 'backend' in self:
return
try:
cval = self.validate[key](val)
except ValueError as ve:
Expand Down Expand Up @@ -881,6 +885,12 @@ def __getitem__(self, key):
"3.0", "{} is deprecated; in the future, examples will be "
"found relative to the 'datapath' directory.".format(key))

elif key == "backend":
val = dict.__getitem__(self, key)
if val is rcsetup._auto_backend_sentinel:
from matplotlib import pyplot as plt
plt.switch_backend(rcsetup._auto_backend_sentinel)

return dict.__getitem__(self, key)

def __repr__(self):
Expand Down Expand Up @@ -1095,10 +1105,10 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
_fullpath = os.path.join(_basedir, rcParams['examples.directory'])
rcParams['examples.directory'] = _fullpath

rcParamsOrig = rcParams.copy()

with warnings.catch_warnings():
warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
rcParamsOrig = RcParams(rcParams.copy())
rcParamsDefault = RcParams([(key, default) for key, (default, converter) in
defaultParams.items()
if key not in _all_deprecated])
Expand Down Expand Up @@ -1222,7 +1232,7 @@ def rc_file_defaults():
with warnings.catch_warnings():
warnings.simplefilter("ignore", mplDeprecation)
from .style.core import STYLE_BLACKLIST
rcParams.update({k: v for k, v in rcParamsOrig.items()
rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
if k not in STYLE_BLACKLIST})


Expand All @@ -1238,7 +1248,8 @@ def rc_file(fname):
with warnings.catch_warnings():
warnings.simplefilter("ignore", mplDeprecation)
from .style.core import STYLE_BLACKLIST
rcParams.update({k: v for k, v in rc_params_from_file(fname).items()
rc_from_file = rc_params_from_file(fname)
rcParams.update({k: rc_from_file[k] for k in rc_from_file
if k not in STYLE_BLACKLIST})


Expand Down Expand Up @@ -1289,16 +1300,23 @@ def __init__(self, rc=None, fname=None):
if rc:
rcParams.update(rc)
except Exception:
# If anything goes wrong, revert to the original rcs.
dict.update(rcParams, self._orig)
self.__fallback()
raise

def __fallback(self):
# If anything goes wrong, revert to the original rcs.
updated_backend = self._orig['backend']
dict.update(rcParams, self._orig)
# except for the backend. If the context block triggered resloving
# the auto backend resolution keep that value around
if self._orig['backend'] is rcsetup._auto_backend_sentinel:
rcParams['backend'] = updated_backend

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, exc_tb):
# No need to revalidate the original values.
dict.update(rcParams, self._orig)
self.__fallback()


def use(arg, warn=True, force=False):
Expand All @@ -1324,14 +1342,14 @@ def use(arg, warn=True, force=False):

force : bool, optional
If True, attempt to switch the backend. This defaults to
false and using `.pyplot.switch_backend` is preferred.
False.


"""
name = validate_backend(arg)

# if setting back to the same thing, do nothing
if (rcParams['backend'] == name):
if (dict.__getitem__(rcParams, 'backend') == name):
pass

# Check if we have already imported pyplot and triggered
Expand Down Expand Up @@ -1361,7 +1379,7 @@ def use(arg, warn=True, force=False):


if os.environ.get('MPLBACKEND'):
use(os.environ['MPLBACKEND'])
rcParams['backend'] = os.environ.get('MPLBACKEND')


def get_backend():
Expand Down
9 changes: 3 additions & 6 deletions lib/matplotlib/backends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@

_log = logging.getLogger(__name__)

backend = matplotlib.get_backend()
# FIXME: Remove.
_backend_loading_tb = "".join(
line for line in traceback.format_stack()
# Filter out line noise from importlib line.
if not line.startswith(' File "<frozen importlib._bootstrap'))

# NOTE: plt.switch_backend() (called at import time) will add a "backend"
# attribute here for backcompat.


def _get_running_interactive_framework():
Expand Down
43 changes: 12 additions & 31 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.figure import Figure, figaspect
from matplotlib.gridspec import GridSpec
from matplotlib import rcParams, rcParamsDefault, get_backend
from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
from matplotlib import rc_context
from matplotlib.rcsetup import interactive_bk as _interactive_bk
from matplotlib.artist import getp, get, Artist
Expand Down Expand Up @@ -67,7 +67,7 @@
Locator, IndexLocator, FixedLocator, NullLocator,\
LinearLocator, LogLocator, AutoLocator, MultipleLocator,\
MaxNLocator
from matplotlib.backends import pylab_setup
from matplotlib.backends import pylab_setup, _get_running_interactive_framework

_log = logging.getLogger(__name__)

Expand All @@ -78,35 +78,15 @@
# FIXME: Deprecate.
def _backend_selection():
"""
If rcParams['backend_fallback'] is true, check to see if the
current backend is compatible with the current running event loop,
and if not switches to a compatible one.
"""
backend = rcParams['backend']
if not rcParams['backend_fallback'] or backend not in _interactive_bk:
return
is_agg_backend = rcParams['backend'].endswith('Agg')
if 'wx' in sys.modules and backend not in ('WX', 'WXAgg'):
import wx
if wx.App.IsMainLoopRunning():
rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
elif 'PyQt4.QtCore' in sys.modules and not backend == 'Qt4Agg':
import PyQt4.QtGui
if not PyQt4.QtGui.qApp.startingUp():
# The mainloop is running.
rcParams['backend'] = 'qt4Agg'
elif 'PyQt5.QtCore' in sys.modules and not backend == 'Qt5Agg':
import PyQt5.QtWidgets
if not PyQt5.QtWidgets.qApp.startingUp():
# The mainloop is running.
rcParams['backend'] = 'qt5Agg'
elif 'gtk' in sys.modules and 'gi' in sys.modules:
from gi.repository import GLib
if GLib.MainLoop().is_running():
rcParams['backend'] = 'GTK3Agg'
elif 'Tkinter' in sys.modules and not backend == 'TkAgg':
# import Tkinter
pass # what if anything do we need to do for tkinter?
If rcParams['backend_fallback'] is true, we will check (at backend
load-time) to see if the current backend is compatible with the current
running event loop, and if not switches to a compatible one.
"""
if rcParams["backend_fallback"]:
if (dict.__getitem__(rcParams, "backend") in _interactive_bk
and _get_running_interactive_framework()):
dict.__setitem__(
rcParams, "backend", rcsetup._auto_backend_sentinel)


_backend_selection()
Expand Down Expand Up @@ -237,6 +217,7 @@ def switch_backend(newbackend):
except ImportError:
continue
else:
rcParamsOrig['backend'] = candidate
return

backend_name = (
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def setup():
"Could not set locale to English/United States. "
"Some date-related tests may fail.")

mpl.use('Agg', warn=False) # use Agg backend for these tests
mpl.use('Agg', force=True, warn=False) # use Agg backend for these tests

with warnings.catch_warnings():
warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
Expand Down
4 changes: 3 additions & 1 deletion lib/matplotlib/testing/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


def pytest_configure(config):
matplotlib.use('agg')
matplotlib.use('agg', force=True)
matplotlib._called_from_pytest = True
matplotlib._init_tests()

Expand Down Expand Up @@ -53,6 +53,8 @@ def mpl_test_settings(request):
if backend is not None:
plt.switch_backend(prev_backend)

assert matplotlib.get_backend() == 'agg'


@pytest.fixture
def mpl_image_comparison_parameters(request, extension):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def test_determinism(filename, usetex):
[sys.executable, '-R', '-c',
'import matplotlib; '
'matplotlib._called_from_pytest = True; '
'matplotlib.use("svg"); '
'matplotlib.use("svg", force=True); '
'from matplotlib.tests.test_backend_svg '
'import _test_determinism_save;'
'_test_determinism_save(%r, %r)' % (filename, usetex)],
Expand Down