Skip to content

Commit 1176823

Browse files
committed
Enable ruff
1 parent c91289e commit 1176823

File tree

5 files changed

+60
-33
lines changed

5 files changed

+60
-33
lines changed

.github/workflows/main.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,12 @@ jobs:
4646

4747
- name: Test flake8
4848
run: flake8 matplotlib_inline --ignore=E501,W504,W503
49+
50+
- name: Install ruff
51+
run: mamba install ruff
52+
53+
- name: Check code with ruff
54+
run: ruff check matplotlib_inline
55+
56+
- name: Check formatting with ruff
57+
run: ruff format matplotlib_inline --check

matplotlib_inline/backend_inline.py

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,11 @@ def new_figure_manager_given_figure(num, figure):
4343
# https://github.com/ipython/ipython/issues/1612
4444
# https://github.com/matplotlib/matplotlib/issues/835
4545

46-
if not hasattr(figure, 'show'):
46+
if not hasattr(figure, "show"):
4747
# Queue up `figure` for display
4848
figure.show = lambda *a: display(
49-
figure, metadata=_fetch_figure_metadata(figure))
49+
figure, metadata=_fetch_figure_metadata(figure)
50+
)
5051

5152
# If matplotlib was manually set to non-interactive mode, this function
5253
# should be a no-op (otherwise we'll generate duplicate plots, since a user
@@ -89,14 +90,14 @@ def show(close=None, block=None):
8990
for figure_manager in Gcf.get_all_fig_managers():
9091
display(
9192
figure_manager.canvas.figure,
92-
metadata=_fetch_figure_metadata(figure_manager.canvas.figure)
93+
metadata=_fetch_figure_metadata(figure_manager.canvas.figure),
9394
)
9495
finally:
9596
show._to_draw = []
9697
# only call close('all') if any to close
9798
# close triggers gc.collect, which can be slow
9899
if close and Gcf.get_all_fig_managers():
99-
matplotlib.pyplot.close('all')
100+
matplotlib.pyplot.close("all")
100101

101102

102103
# This flag will be reset by draw_if_interactive when called
@@ -176,8 +177,8 @@ def configure_inline_support(shell, backend):
176177
if cfg not in shell.configurables:
177178
shell.configurables.append(cfg)
178179

179-
if backend in ('inline', 'module://matplotlib_inline.backend_inline'):
180-
shell.events.register('post_execute', flush_figures)
180+
if backend in ("inline", "module://matplotlib_inline.backend_inline"):
181+
shell.events.register("post_execute", flush_figures)
181182

182183
# Save rcParams that will be overwrittern
183184
shell._saved_rcParams = {}
@@ -188,10 +189,10 @@ def configure_inline_support(shell, backend):
188189
new_backend_name = "inline"
189190
else:
190191
try:
191-
shell.events.unregister('post_execute', flush_figures)
192+
shell.events.unregister("post_execute", flush_figures)
192193
except ValueError:
193194
pass
194-
if hasattr(shell, '_saved_rcParams'):
195+
if hasattr(shell, "_saved_rcParams"):
195196
matplotlib.rcParams.update(shell._saved_rcParams)
196197
del shell._saved_rcParams
197198
new_backend_name = "other"
@@ -211,13 +212,15 @@ def _enable_matplotlib_integration():
211212
ip = get_ipython()
212213

213214
import matplotlib
215+
214216
if matplotlib.__version_info__ >= (3, 10):
215217
backend = matplotlib.get_backend(auto_select=False)
216218
else:
217219
backend = matplotlib.rcParams._get("backend")
218220

219-
if ip and backend in ('inline', 'module://matplotlib_inline.backend_inline'):
221+
if ip and backend in ("inline", "module://matplotlib_inline.backend_inline"):
220222
from IPython.core.pylabtools import activate_matplotlib
223+
221224
try:
222225
activate_matplotlib(backend)
223226
configure_inline_support(ip, backend)
@@ -226,8 +229,9 @@ def _enable_matplotlib_integration():
226229
def configure_once(*args):
227230
activate_matplotlib(backend)
228231
configure_inline_support(ip, backend)
229-
ip.events.unregister('post_run_cell', configure_once)
230-
ip.events.register('post_run_cell', configure_once)
232+
ip.events.unregister("post_run_cell", configure_once)
233+
234+
ip.events.register("post_run_cell", configure_once)
231235

232236

233237
_enable_matplotlib_integration()
@@ -238,13 +242,17 @@ def _fetch_figure_metadata(fig):
238242
# determine if a background is needed for legibility
239243
if _is_transparent(fig.get_facecolor()):
240244
# the background is transparent
241-
ticksLight = _is_light([label.get_color()
242-
for axes in fig.axes
243-
for axis in (axes.xaxis, axes.yaxis)
244-
for label in axis.get_ticklabels()])
245+
ticksLight = _is_light(
246+
[
247+
label.get_color()
248+
for axes in fig.axes
249+
for axis in (axes.xaxis, axes.yaxis)
250+
for label in axis.get_ticklabels()
251+
]
252+
)
245253
if ticksLight.size and (ticksLight == ticksLight[0]).all():
246254
# there are one or more tick labels, all with the same lightness
247-
return {'needs_background': 'dark' if ticksLight[0] else 'light'}
255+
return {"needs_background": "dark" if ticksLight[0] else "light"}
248256

249257
return None
250258

@@ -254,13 +262,13 @@ def _is_light(color):
254262
opposed to dark). Based on ITU BT.601 luminance formula (see
255263
https://stackoverflow.com/a/596241)."""
256264
rgbaArr = colors.to_rgba_array(color)
257-
return rgbaArr[:, :3].dot((.299, .587, .114)) > .5
265+
return rgbaArr[:, :3].dot((0.299, 0.587, 0.114)) > 0.5
258266

259267

260268
def _is_transparent(color):
261269
"""Determine transparency from alpha."""
262270
rgba = colors.to_rgba(color)
263-
return rgba[3] < .5
271+
return rgba[3] < 0.5
264272

265273

266274
def set_matplotlib_formats(*formats, **kwargs):

matplotlib_inline/config.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@
77
# Distributed under the terms of the BSD 3-Clause License.
88

99
from traitlets.config.configurable import SingletonConfigurable
10-
from traitlets import (
11-
Dict, Instance, Set, Bool, TraitError, Unicode
12-
)
10+
from traitlets import Dict, Instance, Set, Bool, TraitError, Unicode
1311

1412

1513
# Configurable for inline backend options
@@ -18,6 +16,7 @@ def pil_available():
1816
out = False
1917
try:
2018
from PIL import Image # noqa
19+
2120
out = True
2221
except ImportError:
2322
pass
@@ -44,37 +43,44 @@ class InlineBackend(InlineBackendConfig):
4443
the box, but third-party tools may use it to manage rc data. To change
4544
personal defaults for matplotlib, use matplotlib's configuration
4645
tools, or customize this class in your `ipython_config.py` file for
47-
IPython/Jupyter-specific usage.""").tag(config=True)
46+
IPython/Jupyter-specific usage.""",
47+
).tag(config=True)
4848

4949
figure_formats = Set(
50-
{'png'},
50+
{"png"},
5151
help="""A set of figure formats to enable: 'png',
52-
'retina', 'jpeg', 'svg', 'pdf'.""").tag(config=True)
52+
'retina', 'jpeg', 'svg', 'pdf'.""",
53+
).tag(config=True)
5354

5455
def _update_figure_formatters(self):
5556
if self.shell is not None:
5657
from IPython.core.pylabtools import select_figure_formats
57-
select_figure_formats(self.shell, self.figure_formats, **self.print_figure_kwargs)
58+
59+
select_figure_formats(
60+
self.shell, self.figure_formats, **self.print_figure_kwargs
61+
)
5862

5963
def _figure_formats_changed(self, name, old, new):
60-
if 'jpg' in new or 'jpeg' in new:
64+
if "jpg" in new or "jpeg" in new:
6165
if not pil_available():
6266
raise TraitError("Requires PIL/Pillow for JPG figures")
6367
self._update_figure_formatters()
6468

65-
figure_format = Unicode(help="""The figure format to enable (deprecated
66-
use `figure_formats` instead)""").tag(config=True)
69+
figure_format = Unicode(
70+
help="""The figure format to enable (deprecated
71+
use `figure_formats` instead)"""
72+
).tag(config=True)
6773

6874
def _figure_format_changed(self, name, old, new):
6975
if new:
7076
self.figure_formats = {new}
7177

7278
print_figure_kwargs = Dict(
73-
{'bbox_inches': 'tight'},
79+
{"bbox_inches": "tight"},
7480
help="""Extra kwargs to be passed to fig.canvas.print_figure.
7581
7682
Logical examples include: bbox_inches, quality (for jpeg figures), etc.
77-
"""
83+
""",
7884
).tag(config=True)
7985
_print_figure_kwargs_changed = _update_figure_formatters
8086

@@ -94,7 +100,9 @@ def _figure_format_changed(self, name, old, new):
94100
iterative editing of figures, and behaves most consistently with
95101
other matplotlib backends, but figure barriers between cells must
96102
be explicit.
97-
""").tag(config=True)
103+
""",
104+
).tag(config=True)
98105

99-
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
100-
allow_none=True)
106+
shell = Instance(
107+
"IPython.core.interactiveshell.InteractiveShellABC", allow_none=True
108+
)

tests/notebooks/mpl_inline.ipynb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
"\n",
5757
"# Remove text to avoid tiny differences in rendered output.\n",
5858
"from matplotlib.testing.decorators import remove_ticks_and_titles\n",
59+
"\n",
5960
"remove_ticks_and_titles(fig)"
6061
]
6162
},

tests/test_import.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
def test_import():
22
from matplotlib_inline.backend_inline import show
3+
34
show()

0 commit comments

Comments
 (0)