8000 Factor out retrieval of data relative to datapath · matplotlib/matplotlib@afdf317 · GitHub
[go: up one dir, main page]

Skip to content

Commit afdf317

Browse files
committed
Factor out retrieval of data relative to datapath
... into a cbook._get_data_path() helper.
1 parent 8d487d8 commit afdf317

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
@@ -3103,14 +3103,13 @@ def _get_image_filename(self, image):
31033103
if not image:
31043104
return None
31053105

3106-
basedir = os.path.join(rcParams['datapath'], 'images')
3107-
possible_images = (
3106+
basedir = cbook._get_data_path("images")
3107+
for fname in [
31083108
image,
31093109
image + self._icon_extension,
3110-
os.path.join(basedir, image),
3111-
os.path.join(basedir, image) + self._icon_extension)
3112-
3113-
for fname in possible_images:
3110+
str(basedir / image),
3111+
str(basedir / (image + self._icon_extension)),
3112+
]:
31143113
if os.path.isfile(fname):
31153114
return fname
31163115

lib/matplotlib/backends/_backend_tk.py

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

617617
def _Button(self, text, file, command, extension='.gif'):
618-
img_file = os.path.join(
619-
rcParams['datapath'], 'images', file + extension)
618+
img_file = str(cbook._get_data_path(file + extension))
620619
im = tk.PhotoImage(master=self, file=img_file)
621620
b = tk.Button(
622621
master=self, text=text, padx=2, pady=2, image=im, command=command)
@@ -950,8 +949,7 @@ def new_figure_manager_given_figure(cls, num, figure):
950949
# Tkinter doesn't allow colour icons on linux systems, but tk>=8.5
951950
# has a iconphoto command which we call directly. Source:
952951
# http://mail.python.org/pipermail/tkinter-discuss/2006-November/000954.html
953-
icon_fname = os.path.join(
954-
rcParams['datapath'], 'images', 'matplotlib.ppm')
952+
icon_fname = str(cbook._get_data_path('images/matplotlib.ppm'))
955953
icon_img = tk.PhotoImage(file=icon_fname, master=window)
956954
try:
957955
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
@@ -494,16 +494,15 @@ def draw_rubberband(self, event, x0, y0, x1, y1):
494494

495495
def _init_toolbar(self):
496496
self.set_style(Gtk.ToolbarStyle.ICONS)
497-
basedir = os.path.join(rcParams['datapath'], 'images')
498497

499498
self._gtk_ids = {}
500499
for text, tooltip_text, image_file, callback in self.toolitems:
501500
if text is None:
502501
self.insert(Gtk.SeparatorToolItem(), -1)
503502
continue
504-
fname = os.path.join(basedir, image_file + '.png')
505503
image = Gtk.Image()
506-
image.set_from_file(fname)
504+
image.set_from_file(
505+
str(cbook._get_data_path('images', image_file + '.png')))
507506
self._gtk_ids[text] = tbutton = Gtk.ToolButton()
508507
tbutton.set_label(text)
509508
tbutton.set_icon_widget(image)
@@ -956,8 +955,7 @@ def trigger(self, *args, **kwargs):
956955
icon_filename = 'matplotlib.png'
957956
else:
958957
icon_filename = 'matplotlib.svg'
959-
window_icon = os.path.join(
960-
matplotlib.rcParams['datapath'], 'images', icon_filename)
958+
window_icon = str(cbook._get_data_path('images', icon_filename))
961959

962960

963961
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 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
#
@@ -137,8 +131,8 @@ def __init__(self, canvas):
137131
NavigationToolbar2.__init__(self, canvas)
138132

139133
def _init_toolbar(self):
140-
basedir = os.path.join(rcParams['datapath'], "images")
141-
_macosx.NavigationToolbar2.__init__(self, basedir)
134+
_macosx.NavigationToolbar2.__init__(
135+
self, str(cbook._get_data_path('images')))
142136

143137
def draw_rubberband(self, event, x0, y0, x1, y1):
144138
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
@@ -636,10 +634,11 @@ def fontName(self, fontprop):
636634
filename = fontprop
637635
elif rcParams['pdf.use14corefonts']:
638636
filename = findfont(
639-
fontprop, fontext='afm', directory=self._core14fontdir)
637+
fontprop, fontext='afm', directory=RendererPdf._afm_font_dir)
640638
if filename is None:
641639
filename = findfont(
642-
"Helvetica", fontext='afm', directory=self._core14fontdir)
640+
"Helvetica",
641+
fontext='afm', directory=RendererPdf._afm_font_dir)
643642
else:
644643
filename = findfont(fontprop)
645644

@@ -1579,7 +1578,7 @@ class RendererPdf(_backend_pdf_ps.RendererPDFPSBase):
15791578
def afm_font_cache(self, _cache=cbook.maxdict(50)):
15801579
return _cache
15811580

1582-
_afm_font_dir = pathlib.Path(rcParams["datapath"], "fonts", "pdfcorefonts")
1581+
_afm_font_dir = cbook._get_data_path("fonts/pdfcorefonts")
15831582
_use_afm_rc_name = "pdf.use14corefonts"
15841583

15851584
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
@@ -552,8 +552,7 @@ def __init__(self, canvas, num):
552552
self.window.closing.connect(self._widgetclosed)
553553

554554
self.window.setWindowTitle("Figure %d" % num)
555-
image = os.path.join(matplotlib.rcParams['datapath'],
556-
'images', 'matplotlib.svg')
555+
image = str(cbook._get_data_path('images/matplotlib.svg'))
557556
self.window.setWindowIcon(QtGui.QIcon(image))
558557

559558
# Give the keyboard focus to the figure instead of the
@@ -693,7 +692,7 @@ def _icon(self, name):
693692
return QtGui.QIcon(pm)
694693

695694
def _init_toolbar(self):
696-
self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')
695+
self.basedir = str(cbook._get_data_path('images'))
697696

698697
for text, tooltip_text, image_file, callback in self.toolitems:
699698
if text is None:
@@ -809,8 +808,7 @@ def remove_rubberband(self):
809808
self.canvas.drawRectangle(None)
810809

811810
def configure_subplots(self):
812-
image = os.path.join(matplotlib.rcParams['datapath'],
813-
'images', 'matplotlib.png')
811+
image = str(cbook._get_data_path('images/matplotlib.png'))
814812
dia = SubplotToolQt(self.canvas.figure, self.canvas.parent())
815813
dia.setWindowIcon(QtGui.QIcon(image))
816814
dia.exec_()

lib/matplotlib/backends/backend_webagg.py

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

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

7070
class SingleFigurePage(tornado.web.RequestHandler):
7171
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
@@ -1231,27 +1231,21 @@ def _load_bitmap(filename):
12311231
matplotlib library is installed. The filename parameter should not
12321232
contain any path information as this is determined automatically.
12331233
1234-
Returns a wx.Bitmap object
1234+
Returns a wx.Bitmap object.
12351235
"""
1236-
1237-
basedir = os.path.join(rcParams['datapath'], 'images')
1238-
1239-
bmpFilename = os.path.normpath(os.path.join(basedir, filename))
1240-
if not os.path.exists(bmpFilename):
1241-
raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename)
1242-
1243-
bmp = wx.Bitmap(bmpFilename)
1244-
return bmp
1236+
path = cbook._get_data_path('images', filename)
1237+
if not path.exists():
1238+
raise IOError(f"Could not find bitmap file '{path}'; dying")
1239+
return wx.Bitmap(str(path))
12451240

12461241

12471242
def _set_frame_icon(frame):
1248-
# set frame icon
12491243
bundle = wx.IconBundle()
12501244
for image in ('matplotlib.png', 'matplotlib_large.png'):
1251-
image = os.path.join(matplotlib.rcParams['datapath'], 'images', image)
1252-
if not os.path.exists(image):
1245+
try:
1246+
icon = wx.Icon(_load_bitmap(image))
1247+
except IOError:
12531248
continue
1254-
icon = wx.Icon(_load_bitmap(image))
12551249
if not icon.IsOk():
12561250
return
12571251
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
@@ -493,6 +493,15 @@ def get_sample_data(fname, asfileobj=True):
493493
return path
494494

495495

496+
def _get_data_path(*args):
497+
"""
498+
Return the `Path` to a resource file provided by Matplotlib.
499+
500+
``*args`` specify a path relative to the base data path.
501+
"""
502+
return Path(matplotlib.get_data_path(), *args)
503+
504+
496505
def flatten(seq, scalarp=is_scalar_or_string):
497506
"""
498507
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
@@ -984,10 +984,8 @@ def __init__(self, size=None, weight='normal'):
984984
self.__default_weight = weight
985985
self.default_size = size
986986

987-
paths = [os.path.join(rcParams['datapath'], 'fonts', 'ttf'),
988-
os.path.join(rcParams['datapath'], 'fonts', 'afm'),
989-
os.path.join(rcParams['datapath'], 'fonts', 'pdfcorefonts')]
990-
987+
paths = [cbook._get_data_path('fonts', subdir)
988+
for subdir in ['ttf', 'afm', 'pdfcorefonts']]
991989
# Create list of font paths
992990
for pathname in ['TTFPATH', 'AFMPATH']:
993991
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 D7AE 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
@@ -1081,7 +1081,7 @@ class StandardPsFonts(Fonts):
10811081
Unlike the other font classes, BakomaFont and UnicodeFont, this
10821082
one requires the Ps backend.
10831083
"""
1084-
basepath = os.path.join(get_data_path(), 'fonts', 'afm')
1084+
basepath = str(cbook._get_data_path('fonts/afm'))
10851085

10861086
fontmap = { 'cal' : 'pzcmi8a', # Zapf Chancery
10871087
'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
@@ -429,9 +429,8 @@ def test_rcparams_reset_after_fail():
429429
def test_if_rctemplate_is_up_to_date():
430430
# This tests if the matplotlibrc.template file contains all valid rcParams.
431431
deprecated = {*mpl._all_deprecated, *mpl._deprecated_remain_as_none}
432-
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
433-
with open(path_to_rc, "r") as f:
434-
rclines = f.readlines()
432+
with cbook._get_data_path('matplotlibrc').open() as file:
433+
rclines = file.readlines()
435434
missing = {}
436435
for k, v in mpl.defaultParams.items():
437436
if k[0] == "_":
@@ -456,9 +455,8 @@ def test_if_rctemplate_is_up_to_date():
456455
def test_if_rctemplate_would_be_valid(tmpdir):
457456
# This tests if the matplotlibrc.template file would result in a valid
458457
# rc file if all lines are uncommented.
459-
path_to_rc = os.path.join(mpl.get_data_path(), 'matplotlibrc')
460-
with open(path_to_rc, "r") as f:
461-
rclines = f.readlines()
458+
with cbook._get_data_path('matplotlibrc').open() as file:
459+
rclines = file.readlines()
462460
newlines = []
463461
for line in rclines:
464462
if line[0] == "#":

lib/matplotlib/tests/test_text.py

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

2121
@image_comparison(baseline_images=['font_styles'])
2222
def test_font_styles():
23-
from matplotlib import _get_data_path
24-
data_path = _get_data_path()
2523

2624
def find_matplotlib_font(**kw):
2725
prop = FontProperties(**kw)
28-
path = findfont(prop, directory=data_path)
26+
path = findfont(prop, directory=matplotlib.get_data_path())
2927
return FontProperties(fname=path)
3028

3129
from matplotlib.font_manager import FontProperties, findfont

0 commit comments

Comments
 (0)
0