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

Skip to content

Commit 92bccd2

Browse files
committed
Handle unicode/bytes directly in the C extension
1 parent d75b068 commit 92bccd2

2 files changed

Lines changed: 21 additions & 3 deletions

File tree

lib/matplotlib/backends/backend_agg.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ def print_png(self, filename_or_obj, *args, **kwargs):
556556

557557
version_str = 'matplotlib version ' + __version__ + \
558558
', http://matplotlib.org/'
559-
metadata = {six.b('Software'): six.b(version_str)}
559+
metadata = {'Software': version_str}
560560
user_metadata = kwargs.pop("metadata", None)
561561
if user_metadata is not None:
562562
metadata.update(user_metadata)

src/_png.cpp

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,26 @@ static PyObject *Py_write_png(PyObject *self, PyObject *args, PyObject *kwds)
292292
while (PyDict_Next(metadata, &pos, &meta_key, &meta_val)) {
293293
text[meta_pos].compression = PNG_TEXT_COMPRESSION_NONE;
294294
#if PY3K
295-
text[meta_pos].key = PyBytes_AsString(meta_key);
296-
text[meta_pos].text = PyBytes_AsString(meta_val);
295+
if (PyUnicode_Check(meta_key)) {
296+
PyObject *temp_key = PyUnicode_AsEncodedString(meta_key, "ASCII", "strict");
297+
if (temp_key != NULL) {
298+
text[meta_pos].key = PyBytes_AsString(temp_key);
299+
}
300+
} else if (PyBytes_Check(meta_key)) {
301+
text[meta_pos].key = PyBytes_AsString(meta_key);
302+
} else {
303+
text[meta_pos].key = NULL; // Silently drops entry
304+
}
305+
if (PyUnicode_Check(meta_val)) {
306+
PyObject *temp_val = PyUnicode_AsEncodedString(meta_val, "ASCII", "strict");
307+
if (temp_val != NULL) {
308+
text[meta_pos].text = PyBytes_AsString(temp_val);
309+
}
310+
} else if (PyBytes_Check(meta_val)) {
311+
text[meta_pos].text = PyBytes_AsString(meta_val);
312+
} else {
313+
text[meta_pos].text = (char *)"Invalid value in metadata";
314+
}
297315
#else
298316
text[meta_pos].key = PyString_AsString(meta_key);
299317
text[meta_pos].text = PyString_AsString(meta_val);

0 commit comments

Comments
 (0)