8000 Minor tweaks to pdf Name. (#23287) · matplotlib/matplotlib@9bca34e · GitHub
[go: up one dir, main page]

Skip to content

Commit 9bca34e

Browse files
authored
Minor tweaks to pdf Name. (#23287)
- Fix `__str__` for Python3. `__str__` is never actually used (but can be nice to have for debugging purposes); still, `str(Name("foo"))` currently returns `/b'foo'` where the surrounding `b''` is almost certainly a fallout from the Py2/Py3 str transition; the intent was to return the same thing as `pdfRepr`, but ascii-decoded. Fix that. - Micro-optimize hex escapes. In the presence of characters to be escaped, `str.translate` is quite faster than `regex.sub`: `$ python -mtimeit -s 'from matplotlib.backends.backend_pdf import Name' 'Name("foo\xff\x01")'` shows a >2x speedup, for example. (There is no difference when no characters are actually subbed. I guess the overhead likely comes from the function calls?) This is unlikely to matter in reality, but is also shorter and just as legible (perhaps even a bit better), so...
1 parent 7858eb4 commit 9bca34e

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

lib/matplotlib/backends/backend_pdf.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -366,21 +366,22 @@ def write(self, contents, file):
366366
class Name:
367367
"""PDF name object."""
368368
__slots__ = ('name',)
369-
_regex = re.compile(r'[^!-~]')
369+
_hexify = {c: '#%02x' % c
370+
for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}}
370371

371372
def __init__(self, name):
372373
if isinstance(name, Name):
373374
self.name = name.name
374375
else:
375376
if isinstance(name, bytes):
376377
name = name.decode('ascii')
377-
self.name = self._regex.sub(Name.hexify, name).encode('ascii')
378+
self.name = name.translate(self._hexify).encode('ascii')
378379

379380
def __repr__(self):
380381
return "<Name %s>" % self.name
381382

382383
def __str__(self):
383-
return '/' + str(self.name)
384+
return '/' + self.name.decode('ascii')
384385

385386
def __eq__(self, other):
386387
return isinstance(other, Name) and self.name == other.name
@@ -391,10 +392,6 @@ def __lt__(self, other):
391392
def __hash__(self):
392393
return hash(self.name)
393394

394-
@staticmethod
395-
def hexify(match):
396-
return '#%02x' % ord(match.group())
397-
398395
def pdfRepr(self):
399396
return b'/' + self.name
400397

0 commit comments

Comments
 (0)
0