@@ -905,11 +905,15 @@ def rc_file_defaults():
905
905
or matplotlib.backends is imported for the first time.
906
906
"""
907
907
908
- def use (arg , warn = True ):
908
+ def use (arg , warn = True , force = False ):
909
909
"""
910
910
Set the matplotlib backend to one of the known backends.
911
911
912
- The argument is case-insensitive.
912
+ The argument is case-insensitive. *warn* specifies whether a
913
+ warning should be issued if a backend has already been set up.
914
+ *force* is an **experimental** flag that tells matplotlib to
915
+ attempt to initialize a new backend by reloading the backend
916
+ module.
913
917
914
918
.. note::
915
919
@@ -918,25 +922,41 @@ def use(arg, warn=True):
918
922
before importing matplotlib.backends. If warn is True, a warning
919
923
is issued if you try and call this after pylab or pyplot have been
920
924
loaded. In certain black magic use cases, e.g.
921
- :func:`pyplot.switch_backends `, we are doing the reloading necessary to
925
+ :func:`pyplot.switch_backend `, we are doing the reloading necessary to
922
926
make the backend switch work (in some cases, e.g. pure image
923
- backends) so one can set warn=False to supporess the warnings.
927
+ backends) so one can set warn=False to suppress the warnings.
924
928
925
929
To find out which backend is currently set, see
926
930
:func:`matplotlib.get_backend`.
927
931
928
932
"""
933
+ # Check if we've already set up a backend
929
934
if 'matplotlib.backends' in sys .modules :
930
- if warn : warnings .warn (_use_error_msg )
931
- return
935
+ if warn :
936
+ warnings .warn (_use_error_msg )
937
+
938
+ # Unless we've been told to force it, just return
939
+ if not force :
940
+ return
941
+ need_reload = True
942
+ else :
943
+ need_reload = False
944
+
945
+ # Set-up the proper backend name
932
946
if arg .startswith ('module://' ):
933
947
name = arg
934
948
else :
935
949
# Lowercase only non-module backend names (modules are case-sensitive)
936
950
arg = arg .lower ()
937
951
name = validate_backend (arg )
952
+
938
953
rcParams ['backend' ] = name
939
954
955
+ # If needed we reload here because a lot of setup code is triggered on
956
+ # module import. See backends/__init__.py for more detail.
957
+ if need_reload :
958
+ reload (sys .modules ['matplotlib.backends' ])
959
+
940
960
def get_backend ():
941
961
"Returns the current backend."
942
962
return rcParams ['backend' ]
0 commit comments