Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite45d8b0

Browse files
committed
Rework backend loading.
This is preliminary work towards fixing the runtime detection of defaultbackend problem (the first step being to make it easier to check whethera 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 asbuiltin 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 refactoraccidentally 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 hadto be moved even after that as it depends on the `_Backend` class.
1 parent477c1dc commite45d8b0

File tree

5 files changed

+159
-168
lines changed

5 files changed

+159
-168
lines changed

‎lib/matplotlib/backend_bases.py

Lines changed: 128 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
fromcontextlibimportcontextmanager
4242
fromfunctoolsimportpartial
4343
importimportlib
44+
importinspect
4445
importio
4546
importos
4647
importsys
@@ -49,6 +50,7 @@
4950
fromweakrefimportWeakKeyDictionary
5051

5152
importnumpyasnp
53+
importmatplotlib
5254
importmatplotlib.cbookascbook
5355
importmatplotlib.colorsascolors
5456
importmatplotlib.transformsastransforms
@@ -136,120 +138,6 @@ def get_registered_canvas_class(format):
136138
returnbackend_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-
defnew_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-
frommatplotlib.figureimportFigure
169-
fig_cls=kwargs.pop('FigureClass',Figure)
170-
fig=fig_cls(*args,**kwargs)
171-
returncls.new_figure_manager_given_figure(num,fig)
172-
173-
@classmethod
174-
defnew_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-
returnmanager
180-
181-
@classmethod
182-
defdraw_if_interactive(cls):
183-
ifcls.trigger_manager_drawisnotNoneandis_interactive():
184-
manager=Gcf.get_active()
185-
ifmanager:
186-
cls.trigger_manager_draw(manager)
187-
188-
@classmethod
189-
defshow(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-
ifcls.mainloopisNone:
197-
return
198-
managers=Gcf.get_all_fig_managers()
199-
ifnotmanagers:
200-
return
201-
formanagerinmanagers:
202-
manager.show()
203-
ifblockisNone:
204-
# Hack: Are we in IPython's pylab mode?
205-
frommatplotlibimportpyplot
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=notpyplot.show._needmain
210-
exceptAttributeError:
211-
ipython_pylab=False
212-
block=notipython_pylabandnotis_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-
ifget_backend()=="WebAgg":
216-
block=True
217-
ifblock:
218-
cls.mainloop()
219-
220-
# This method is the one actually exporting the required methods.
221-
222-
@staticmethod
223-
defexport(cls):
224-
fornamein ["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-
classShow(ShowBase):
235-
defmainloop(self):
236-
returncls.mainloop()
237-
238-
setattr(sys.modules[cls.__module__],"Show",Show)
239-
returncls
240-
241-
242-
classShowBase(_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-
returnself.show(block=block)
251-
252-
253141
classRendererBase(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+
defnew_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+
frommatplotlib.figureimportFigure
3285+
fig_cls=kwargs.pop('FigureClass',Figure)
3286+
fig=fig_cls(*args,**kwargs)
3287+
returncls.new_figure_manager_given_figure(num,fig)
3288+
3289+
@classmethod
3290+
defnew_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+
returnmanager
3296+
3297+
@classmethod
3298+
defdraw_if_interactive(cls):
3299+
ifcls.trigger_manager_drawisnotNoneandis_interactive():
3300+
manager=Gcf.get_active()
3301+
ifmanager:
3302+
cls.trigger_manager_draw(manager)
3303+
3304+
@classmethod
3305+
defshow(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+
ifcls.mainloopisNone:
3313+
frame=inspect.currentframe()
3314+
whileframe:
3315+
ifframe.f_code.co_filenamein [
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+
ifnotmanagers:
3327+
return
3328+
formanagerinmanagers:
3329+
manager.show()
3330+
ifblockisNone:
3331+
# Hack: Are we in IPython's pylab mode?
3332+
frommatplotlibimportpyplot
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=notpyplot.show._needmain
3337+
exceptAttributeError:
3338+
ipython_pylab=False
3339+
block=notipython_pylabandnotis_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+
ifget_backend()=="WebAgg":
3343+
block=True
3344+
ifblock:
3345+
cls.mainloop()
3346+
3347+
# This method is the one actually exporting the required methods.
3348+
3349+
@staticmethod
3350+
defexport(cls):
3351+
fornamein ["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+
classShow(ShowBase):
3363+
defmainloop(self):
3364+
returncls.mainloop()
3365+
3366+
setattr(sys.modules[cls.__module__],"Show",Show)
3367+
returncls
3368+
3369+
3370+
classShowBase(_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+
returnself.show(block=block)

‎lib/matplotlib/backends/__init__.py

Lines changed: 27 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33

44
importsix
55

6-
importmatplotlib
7-
importinspect
8-
importtraceback
9-
importwarnings
6+
importimportlib
107
importlogging
8+
importtraceback
9+
10+
importmatplotlib
11+
frommatplotlib.backend_basesimport_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
ifnameisNone:
50-
# validates, to match all_backends
5152
name=matplotlib.get_backend()
52-
ifname.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-
defdo_nothing_show(*args,**kwargs):
71-
frame=inspect.currentframe()
72-
fname=frame.f_back.f_code.co_filename
73-
iffnamein ('<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-
defdo_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:]ifname.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
globalbackend
9563
backend=name
96-
returnbackend_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_funcifgetattr(func,"im_self",0)isNone
73+
elsefunc)
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

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

26012601

2602-
classFigureManagerPdf(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

Lines changed: 1 addition & 3 deletions
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-
classFigureManagerPS(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)

[8]ページ先頭

©2009-2025 Movatter.jp