Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -2130,6 +2130,8 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,

if format is None:
# get format from filename, or from backend's default filetype
if isinstance(filename, getattr(os, "PathLike", ())):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Am I correct, that this will only fix the format detection for Python 3.6+? Since this will probably go into 2.2.x. it should also hande pre-python3.6 Path objects, i.e. check for Path instance and use filename = str(filename)?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also PEP-519 states

Libraries wishing to support path objects and a version of Python prior to Python 3.6 and the existence of os.fspath() can use the idiom of path.__fspath__() if hasattr(path, "__fspath__") else path.

But that's more a matter of taste.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original PR explicitly only supported 3.6+ (see whatsnew note in https://github.com/matplotlib/matplotlib/pull/10231/files). I have no intent to reimplement the pathlike API on <3.6.

So I'll leave things as they are.

filename = os.fspath(filename)
if isinstance(filename, six.string_types):
format = os.path.splitext(filename)[1][1:]
if format is None or format == '':
Expand Down
10 changes: 7 additions & 3 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import absolute_import, division, print_function

import os
import sys
import warnings

Expand Down Expand Up @@ -379,6 +378,11 @@ def test_figure_repr():

@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python 3.6+")
@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
def test_fspath(fmt):
def test_fspath(fmt, tmpdir):
from pathlib import Path
plt.savefig(Path(os.devnull), format=fmt)
out = Path(tmpdir, "test.{}".format(fmt))
plt.savefig(out)
with out.open("rb") as file:
# All the supported formats include the format name (case-insensitive)
# in the first 100 bytes.
assert fmt.encode("ascii") in file.read(100).lower()