Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9814fe8

Browse files
authored
Merge pull request #14104 from anntzer/data_path
Factor out retrieval of data relative to datapath
2 parents 7c8b80f + 65d77bf commit 9814fe8

15 files changed

+59
-80
lines changed

lib/matplotlib/backend_bases.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3142,14 +3142,13 @@ def _get_image_filename(self, image):
31423142
if not image:
31433143
return None
31443144

3145-
basedir = os.path.join(rcParams['datapath'], 'images')
3146-
possible_images = (
3145+
basedir = cbook._get_data_path("images")
3146+
for fname in [
31473147
image,
31483148
image + self._icon_extension,
3149-
os.path.join(basedir, image),
3150-
os.path.join(basedir, image) + self._icon_extension)
3151-
3152-
for fname in possible_images:
3149+
str(basedir / image),
3150+
str(basedir / (image + self._icon_extension)),
3151+
]:
31533152
if os.path.isfile(fname):
31543153
return fname
31553154

lib/matplotlib/backends/_backend_tk.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -545,8 +545,7 @@ def set_cursor(self, cursor):
545545
window.update_idletasks()
546546

547547
def _Button(self, text, file, command, extension='.gif'):
548-
img_file = os.path.join(
549-
rcParams['datapath'], 'images', file + extension)
548+
img_file = str(cbook._get_data_path('images', file + extension))
550549
im = tk.PhotoImage(master=self, file=img_file)
551550
b = tk.Button(
552551
master=self, text=text, padx=2, pady=2, image=im, command=command)
@@ -882,8 +881,7 @@ def new_figure_manager_given_figure(cls, num, figure):
882881
# Tkinter doesn't allow colour icons on linux systems, but tk>=8.5
883882
# has a iconphoto command which we call directly. Source:
884883
# http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html
885-
icon_fname = os.path.join(
886-
rcParams['datapath'], 'images', 'matplotlib.ppm')
884+
icon_fname = str(cbook._get_data_path('images/matplotlib.ppm'))
887885
icon_img = tk.PhotoImage(file=icon_fname, master=window)
888886
try:
889887
window.iconphoto(False, icon_img)

lib/matplotlib/backends/backend_gtk3.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -490,16 +490,15 @@ def draw_rubberband(self, event, x0, y0, x1, y1):
490490

491491
def _init_toolbar(self):
492492
self.set_style(Gtk.ToolbarStyle.ICONS)
493-
basedir = os.path.join(rcParams['datapath'], 'images')
494493

495494
self._gtk_ids = {}
496495
for text, tooltip_text, image_file, callback in self.toolitems:
497496
if text is None:
498497
self.insert(Gtk.SeparatorToolItem(), -1)
499498
continue
500-
fname = os.path.join(basedir, image_file + '.png')
501499
image = Gtk.Image()
502-
image.set_from_file(fname)
500+
image.set_from_file(
501+
str(cbook._get_data_path('images', image_file + '.png')))
503502
self._gtk_ids[text] = tbutton = Gtk.ToolButton()
504503
tbutton.set_label(text)
505504
tbutton.set_icon_widget(image)
@@ -948,8 +947,7 @@ def trigger(self, *args, **kwargs):
948947
icon_filename = 'matplotlib.png'
949948
else:
950949
icon_filename = 'matplotlib.svg'
951-
window_icon = os.path.join(
952-
matplotlib.rcParams['datapath'], 'images', icon_filename)
950+
window_icon = str(cbook._get_data_path('images', icon_filename))
953951

954952

955953
def error_msg_gtk(msg, parent=None):

lib/matplotlib/backends/backend_macosx.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
1-
import os
2-
1+
import matplotlib
2+
from matplotlib import cbook, rcParams
33
from matplotlib._pylab_helpers import Gcf
4+
from matplotlib.backends import _macosx
5+
from matplotlib.backends.backend_agg import FigureCanvasAgg
46
from matplotlib.backend_bases import (
57
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
68
TimerBase)
7-
89
from matplotlib.figure import Figure
9-
from matplotlib import cbook, rcParams
10-
1110
from matplotlib.widgets import SubplotTool
1211

13-
import matplotlib
14-
from matplotlib.backends import _macosx
15-
16-
from .backend_agg import FigureCanvasAgg
17-
1812

1913
########################################################################
2014
#
@@ -139,8 +133,8 @@ def __init__(self, canvas):
139133
NavigationToolbar2.__init__(self, canvas)
140134

141135
def _init_toolbar(self):
142-
basedir = os.path.join(rcParams['datapath'], "images")
143-
_macosx.NavigationToolbar2.__init__(self, basedir)
136+
_macosx.NavigationToolbar2.__init__(
137+
self, str(cbook._get_data_path('images')))
144138

145139
def draw_rubberband(self, event, x0, y0, x1, y1):
146140
self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1))

lib/matplotlib/backends/backend_pdf.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -440,8 +440,6 @@ def __init__(self, filename, metadata=None):
440440
fh = filename
441441
self.passed_in_file_object = True
442442

443-
self._core14fontdir = os.path.join(
444-
rcParams['datapath'], 'fonts', 'pdfcorefonts')
445443
self.fh = fh
446444
self.currentstream = None # stream object to write to, if any
447445
fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha
@@ -635,10 +633,11 @@ def fontName(self, fontprop):
635633
filename = fontprop
636634
elif rcParams['pdf.use14corefonts']:
637635
filename = findfont(
638-
fontprop, fontext='afm', directory=self._core14fontdir)
636+
fontprop, fontext='afm', directory=RendererPdf._afm_font_dir)
639637
if filename is None:
640638
filename = findfont(
641-
"Helvetica", fontext='afm', directory=self._core14fontdir)
639+
"Helvetica",
640+
fontext='afm', directory=RendererPdf._afm_font_dir)
642641
else:
643642
filename = findfont(fontprop)
644643

@@ -1571,7 +1570,7 @@ class RendererPdf(_backend_pdf_ps.RendererPDFPSBase):
15711570
def afm_font_cache(self, _cache=cbook.maxdict(50)):
15721571
return _cache
15731572

1574-
_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "pdfcorefonts")
1573+
_afm_font_dir = cbook._get_data_path("fonts/pdfcorefonts")
15751574
_use_afm_rc_name = "pdf.use14corefonts"
15761575

15771576
def __init__(self, file, image_dpi, height, width):

lib/matplotlib/backends/backend_ps.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
192192
def afmfontd(self, _cache=cbook.maxdict(50)):
193193
return _cache
194194

195-
_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "afm")
195+
_afm_font_dir = cbook._get_data_path("fonts/afm")
196196
_use_afm_rc_name = "ps.useafm"
197197

198198
def __init__(self, width, height, pswriter, imagedpi=72):

lib/matplotlib/backends/backend_qt5.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -535,8 +535,7 @@ def __init__(self, canvas, num):
535535
self.window.closing.connect(self._widgetclosed)
536536

537537
self.window.setWindowTitle("Figure %d" % num)
538-
image = os.path.join(matplotlib.rcParams['datapath'],
539-
'images', 'matplotlib.svg')
538+
image = str(cbook._get_data_path('images/matplotlib.svg'))
540539
self.window.setWindowIcon(QtGui.QIcon(image))
541540

542541
# Give the keyboard focus to the figure instead of the
@@ -676,7 +675,7 @@ def _icon(self, name):
676675
return QtGui.QIcon(pm)
677676

678677
def _init_toolbar(self):
679-
self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
678+
self.basedir = str(cbook._get_data_path('images'))
680679

681680
for text, tooltip_text, image_file, callback in self.toolitems:
682681
if text is None:
@@ -792,8 +791,7 @@ def remove_rubberband(self):
792791
self.canvas.drawRectangle(None)
793792

794793
def configure_subplots(self):
795-
image = os.path.join(matplotlib.rcParams['datapath'],
796-
'images', 'matplotlib.png')
794+
image = str(cbook._get_data_path('images/matplotlib.png'))
797795
dia = SubplotToolQt(self.canvas.figure, self.canvas.parent())
798796
dia.setWindowIcon(QtGui.QIcon(image))
799797
dia.exec_()

lib/matplotlib/backends/backend_webagg.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
import tornado.ioloop
3333
import tornado.websocket
3434

35-
from matplotlib import rcParams
35+
from matplotlib import cbook, rcParams
3636
from matplotlib.backend_bases import _Backend
3737
from matplotlib._pylab_helpers import Gcf
3838
from . import backend_webagg_core as core
@@ -65,8 +65,8 @@ class WebAggApplication(tornado.web.Application):
6565
class FavIcon(tornado.web.RequestHandler):
6666
def get(self):
6767
self.set_header('Content-Type', 'image/png')
68-
image_path = Path(rcParams["datapath"], "images", "matplotlib.png")
69-
self.write(image_path.read_bytes())
68+
self.write(
69+
cbook._get_data_path('images/matplotlib.png').read_bytes())
7070

7171
class SingleFigurePage(tornado.web.RequestHandler):
7272
def __init__(self, application, request, *, url_prefix='', **kwargs):

lib/matplotlib/backends/backend_wx.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,27 +1226,21 @@ def _load_bitmap(filename):
12261226
matplotlib library is installed. The filename parameter should not
12271227
contain any path information as this is determined automatically.
12281228
1229-
Returns a wx.Bitmap object
1229+
Returns a wx.Bitmap object.
12301230
"""
1231-
1232-
basedir = os.path.join(rcParams['datapath'], 'images')
1233-
1234-
bmpFilename = os.path.normpath(os.path.join(basedir, filename))
1235-
if not os.path.exists(bmpFilename):
1236-
raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename)
1237-
1238-
bmp = wx.Bitmap(bmpFilename)
1239-
return bmp
1231+
path = cbook._get_data_path('images', filename)
1232+
if not path.exists():
1233+
raise IOError(f"Could not find bitmap file '{path}'; dying")
1234+
return wx.Bitmap(str(path))
12401235

12411236

12421237
def _set_frame_icon(frame):
1243-
# set frame icon
12441238
bundle = wx.IconBundle()
12451239
for image in ('matplotlib.png', 'matplotlib_large.png'):
1246-
image = os.path.join(matplotlib.rcParams['datapath'], 'images', image)
1247-
if not os.path.exists(image):
1240+
try:
1241+
icon = wx.Icon(_load_bitmap(image))
1242+
except IOError:
12481243
continue
1249-
icon = wx.Icon(_load_bitmap(image))
12501244
if not icon.IsOk():
12511245
return
12521246
bundle.AddIcon(icon)

lib/matplotlib/backends/qt_editor/figureoptions.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,14 @@
55

66
"""Module that provides a GUI-based editor for matplotlib's figure options."""
77

8-
import os.path
98
import re
109

1110
import matplotlib
12-
from matplotlib import cm, colors as mcolors, markers, image as mimage
11+
from matplotlib import cbook, cm, colors as mcolors, markers, image as mimage
1312
from matplotlib.backends.qt_compat import QtGui
1413
from matplotlib.backends.qt_editor import _formlayout
1514

1615

17-
def get_icon(name):
18-
basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
19-
return QtGui.QIcon(os.path.join(basedir, name))
20-
21-
2216
LINESTYLES = {'-': 'Solid',
2317
'--': 'Dashed',
2418
'-.': 'DashDot',
@@ -257,8 +251,10 @@ def apply_callback(data):
257251
if not (axes.get_xlim() == orig_xlim and axes.get_ylim() == orig_ylim):
258252
figure.canvas.toolbar.push_current()
259253

260-
data = _formlayout.fedit(datalist, title="Figure options", parent=parent,
261-
icon=get_icon('qt4_editor_options.svg'),
262-
apply=apply_callback)
254+
data = _formlayout.fedit(
255+
datalist, title="Figure options", parent=parent,
256+
icon=QtGui.QIcon(
257+
str(cbook._get_data_path('images', 'qt4_editor_options.svg'))),
258+
apply=apply_callback)
263259
if data is not None:
264260
apply_callback(data)

lib/matplotlib/cbook/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,15 @@ def get_sample_data(fname, asfileobj=True):
436436
return str(path)
437437

438438

439+
def _get_data_path(*args):
440+
"""
441+
Return the `Path` to a resource file provided by Matplotlib.
442+
443+
``*args`` specify a path relative to the base data path.
444+
"""
445+
return Path(matplotlib.get_data_path(), *args)
446+
447+
439448
def flatten(seq, scalarp=is_scalar_or_string):
440449
"""
441450
Return a generator of flattened nested containers

lib/matplotlib/font_manager.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -946,10 +946,8 @@ def __init__(self, size=None, weight='normal'):
946946
self.__default_weight = weight
947947
self.default_size = size
948948

949-
paths = [os.path.join(rcParams['datapath'], 'fonts', 'ttf'),
950-
os.path.join(rcParams['datapath'], 'fonts', 'afm'),
951-
os.path.join(rcParams['datapath'], 'fonts', 'pdfcorefonts')]
952-
949+
paths = [cbook._get_data_path('fonts', subdir)
950+
for subdir in ['ttf', 'afm', 'pdfcorefonts']]
953951
# Create list of font paths
954952
for pathname in ['TTFPATH', 'AFMPATH']:
955953
if pathname in os.environ:

lib/matplotlib/mathtext.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
ParserElement.enablePackrat()
3434

35-
from matplotlib import cbook, colors as mcolors, get_data_path, rcParams
35+
from matplotlib import cbook, colors as mcolors, rcParams
3636
from matplotlib.afm import AFM
3737
from matplotlib.cbook import get_realpath_and_stat
3838
from matplotlib.ft2font import FT2Image, KERNING_DEFAULT, LOAD_NO_HINTING
@@ -1078,7 +1078,7 @@ class StandardPsFonts(Fonts):
10781078
Unlike the other font classes, BakomaFont and UnicodeFont, this
10791079
one requires the Ps backend.
10801080
"""
1081-
basepath = os.path.join(get_data_path(), 'fonts', 'afm')
1081+
basepath = str(cbook._get_data_path('fonts/afm'))
10821082

10831083
fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery
10841084
'rm' : 'pncr8a', # New Century Schoolbook

lib/matplotlib/tests/test_rcparams.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -433,9 +433,8 @@ def test_rcparams_reset_after_fail():
433433
def test_if_rctemplate_is_up_to_date():
434434
# This tests if the matplotlibrc.template file contains all valid rcParams.
435435
deprecated = {*mpl._all_deprecated, *mpl._deprecated_remain_as_none}
436-
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
437-
with open(path_to_rc, "r") as f:
438-
rclines = f.readlines()
436+
with cbook._get_data_path('matplotlibrc').open() as file:
437+
rclines = file.readlines()
439438
missing = {}
440439
for k, v in mpl.defaultParams.items():
441440
if k[0] == "_":
@@ -457,9 +456,8 @@ def test_if_rctemplate_is_up_to_date():
457456
def test_if_rctemplate_would_be_valid(tmpdir):
458457
# This tests if the matplotlibrc.template file would result in a valid
459458
# rc file if all lines are uncommented.
460-
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
461-
with open(path_to_rc, "r") as f:
462-
rclines = f.readlines()
459+
with cbook._get_data_path('matplotlibrc').open() as file:
460+
rclines = file.readlines()
463461
newlines = []
464462
for line in rclines:
465463
if line[0] == "#":

lib/matplotlib/tests/test_text.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,10 @@
2121

2222
@image_comparison(['font_styles'])
2323
def test_font_styles():
24-
from matplotlib import _get_data_path
25-
data_path = _get_data_path()
2624

2725
def find_matplotlib_font(**kw):
2826
prop = FontProperties(**kw)
29-
path = findfont(prop, directory=data_path)
27+
path = findfont(prop, directory=matplotlib.get_data_path())
3028
return FontProperties(fname=path)
3129

3230
from matplotlib.font_manager import FontProperties, findfont

0 commit comments

Comments
 (0)