8000 FIX: be more careful about not importing pyplot early by tacaswell · Pull Request #17764 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

FIX: be more careful about not importing pyplot early #17764

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
merged 1 commit into from
Jun 29, 2020
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
30 changes: 24 additions & 6 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1136,16 +1136,34 @@ def use(backend, *, force=True):
matplotlib.get_backend
"""
name = validate_backend(backend)
# we need to use the base-class method here to avoid (prematurely)
# resolving the "auto" backend setting
if dict.__getitem__(rcParams, 'backend') == name:
# Nothing to do if the requested backend is already set
pass
else:
try:
from matplotlib import pyplot as plt
plt.switch_backend(name)
except ImportError:
if force:
raise
# if pyplot is not already imported, do not import it. Doing
# so may trigger a `plt.switch_backend` to the _default_ backend
# before we get a chance to change to the one the user just requested
plt = sys.modules.get('matplotlib.pyplot')
# if pyplot is imported, then try to change backends
if plt is not None:
try:
# we need this import check here to re-raise if the
# user does not have the libraries to support their
# chosen backend installed.
plt.switch_backend(name)
except ImportError:
< 8000 div data-view-component="true">
if force:
raise
# if we have not imported pyplot, then we can set the rcParam
# value which will be respected when the user finally imports
# pyplot
else:
rcParams['backend'] = backend
# if the user has asked for a given backend, do not helpfully
# fallback
rcParams['backend_fallback'] = False


if os.environ.get('MPLBACKEND'):
Expand Down
5 changes: 4 additions & 1 deletion lib/matplotlib/tests/test_rcparams.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,10 @@ def test_backend_fallback_headless(tmpdir):
with pytest.raises(subprocess.CalledProcessError):
subprocess.run(
[sys.executable, "-c",
"import matplotlib; matplotlib.use('tkagg')"],
("import matplotlib;" +
"matplotlib.use('tkagg');" +
"import matplotlib.pyplot")
],
env=env, check=True)


Expand Down
0