Skip to content

Commit 637b649

Browse files
authored
Merge pull request #10432 from QuLogic/py3-types
Use some new Python3 types
2 parents 9767cfe + 6ba1763 commit 637b649

File tree

9 files changed

+59
-53
lines changed

9 files changed

+59
-53
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
matplotlib.cbook.Bunch deprecated
2+
`````````````````````````````````
3+
The ``matplotlib.cbook.Bunch`` class has been deprecated. Instead, use
4+
`types.SimpleNamespace` from the standard library which provides the same
5+
functionality.

lib/matplotlib/axes/_base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import warnings
1111
import math
1212
from operator import attrgetter
13+
import types
1314

1415
import numpy as np
1516

@@ -3954,7 +3955,7 @@ def start_pan(self, x, y, button):
39543955
Intended to be overridden by new projection types.
39553956
39563957
"""
3957-
self._pan_start = cbook.Bunch(
3958+
self._pan_start = types.SimpleNamespace(
39583959
lim=self.viewLim.frozen(),
39593960
trans=self.transData.frozen(),
39603961
trans_inverse=self.transData.inverted().frozen(),

lib/matplotlib/backends/backend_pdf.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import struct
1818
import sys
1919
import time
20+
import types
2021
import warnings
2122
import zlib
2223

@@ -28,7 +29,7 @@
2829
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
2930
RendererBase)
3031
from matplotlib.backends.backend_mixed import MixedModeRenderer
31-
from matplotlib.cbook import (Bunch, get_realpath_and_stat,
32+
from matplotlib.cbook import (get_realpath_and_stat,
3233
is_writable_file_like, maxdict)
3334
from matplotlib.figure import Figure
3435
from matplotlib.font_manager import findfont, is_opentype_cff_font, get_font
@@ -320,7 +321,8 @@ def pdfRepr(self):
320321
grestore=b'Q', textpos=b'Td', selectfont=b'Tf', textmatrix=b'Tm',
321322
show=b'Tj', showkern=b'TJ', setlinewidth=b'w', clip=b'W', shading=b'sh')
322323

323-
Op = Bunch(**{name: Operator(value) for name, value in _pdfops.items()})
324+
Op = types.SimpleNamespace(**{name: Operator(value)
325+
for name, value in _pdfops.items()})
324326

325327

326328
def _paint_path(fill, stroke):
@@ -685,7 +687,7 @@ def dviFontName(self, dvifont):
685687
pdfname = Name('F%d' % self.nextFont)
686688
self.nextFont += 1
687689
_log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname)
688-
self.dviFontInfo[dvifont.texname] = Bunch(
690+
self.dviFontInfo[dvifont.texname] = types.SimpleNamespace(
689691
dvifont=dvifont,
690692
pdfname=pdfname,
691693
fontfile=psfont.filename,

lib/matplotlib/cbook/__init__.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,8 @@ def strip_math(s):
488488
return s
489489

490490

491-
class Bunch(object):
491+
@deprecated('3.0', alternative='types.SimpleNamespace')
492+
class Bunch(types.SimpleNamespace):
492493
"""
493494
Often we want to just collect a bunch of stuff together, naming each
494495
item of the bunch; a dictionary's OK for that, but a small do- nothing
@@ -497,16 +498,8 @@ class is even handier, and prettier to use. Whenever you want to
497498
498499
>>> point = Bunch(datum=2, squared=4, coord=12)
499500
>>> point.datum
500-
501-
By: Alex Martelli
502-
From: https://code.activestate.com/recipes/121294/
503501
"""
504-
def __init__(self, **kwds):
505-
self.__dict__.update(kwds)
506-
507-
def __repr__(self):
508-
return 'Bunch(%s)' % ', '.join(
509-
'%s=%s' % kv for kv in six.iteritems(vars(self)))
502+
pass
510503

511504

512505
@deprecated('2.1')

lib/matplotlib/dviread.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,17 @@
1818
1919
"""
2020
from collections import namedtuple
21+
import enum
2122
from functools import lru_cache, partial, wraps
2223
import logging
23-
import numpy as np
2424
import os
2525
import re
2626
import struct
2727
import sys
2828
import textwrap
2929

30+
import numpy as np
31+
3032
from matplotlib import cbook, rcParams
3133
from matplotlib.compat import subprocess
3234

@@ -48,7 +50,7 @@
4850
# just stops reading)
4951
# finale: the finale (unimplemented in our current implementation)
5052

51-
_dvistate = cbook.Bunch(pre=0, outer=1, inpage=2, post_post=3, finale=4)
53+
_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
5254

5355
# The marks on a page consist of text and boxes. A page also has dimensions.
5456
Page = namedtuple('Page', 'text boxes height width descent')
@@ -301,7 +303,7 @@ def _read(self):
301303
self._dtable[byte](self, byte)
302304
if byte == 140: # end of page
303305
return True
304-
if self.state == _dvistate.post_post: # end of file
306+
if self.state is _dvistate.post_post: # end of file
305307
self.close()
306308
return False
307309

@@ -622,7 +624,7 @@ def _read(self):
622624
while True:
623625
byte = self.file.read(1)[0]
624626
# If we are in a packet, execute the dvi instructions
625-
if self.state == _dvistate.inpage:
627+
if self.state is _dvistate.inpage:
626628
byte_at = self.file.tell()-1
627629
if byte_at == packet_ends:
628630
self._finalize_packet(packet_char, packet_width)
@@ -678,7 +680,7 @@ def _finalize_packet(self, packet_char, packet_width):
678680
self.state = _dvistate.outer
679681

680682
def _pre(self, i, x, cs, ds):
681-
if self.state != _dvistate.pre:
683+
if self.state is not _dvistate.pre:
682684
raise ValueError("pre command in middle of vf file")
683685
if i != 202:
684686
raise ValueError("Unknown vf format %d" % i)

lib/matplotlib/mathtext.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import os
2424
from math import ceil
25+
import types
2526
import unicodedata
2627
from warnings import warn
2728
from functools import lru_cache
@@ -37,7 +38,7 @@
3738

3839
from matplotlib import _png, colors as mcolors, get_data_path, rcParams
3940
from matplotlib.afm import AFM
40-
from matplotlib.cbook import Bunch, get_realpath_and_stat
41+
from matplotlib.cbook import get_realpath_and_stat
4142
from matplotlib.ft2font import FT2Image, KERNING_DEFAULT, LOAD_NO_HINTING
4243
from matplotlib.font_manager import findfont, FontProperties, get_font
4344
from matplotlib._mathtext_data import (latex_to_bakoma, latex_to_standard,
@@ -312,8 +313,8 @@ def render_rect_filled(self, x1, y1, x2, y2):
312313

313314
def get_results(self, box, used_characters):
314315
ship(0, 0, box)
315-
svg_elements = Bunch(svg_glyphs = self.svg_glyphs,
316-
svg_rects = self.svg_rects)
316+
svg_elements = types.SimpleNamespace(svg_glyphs=self.svg_glyphs,
317+
svg_rects=self.svg_rects)
317318
return (self.width,
318319
self.height + self.depth,
319320
self.depth,
@@ -587,7 +588,7 @@ def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True):
587588

588589
xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
589590
offset = self._get_offset(font, glyph, fontsize, dpi)
590-
metrics = Bunch(
591+
metrics = types.SimpleNamespace(
591592
advance = glyph.linearHoriAdvance/65536.0,
592593
height = glyph.height/64.0,
593594
width = glyph.width/64.0,
@@ -600,7 +601,7 @@ def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True):
600601
slanted = slanted
601602
)
602603

603-
result = self.glyphd[key] = Bunch(
604+
result = self.glyphd[key] = types.SimpleNamespace(
604605
font = font,
605606
fontsize = fontsize,
606607
postscript_name = font.postscript_name,
@@ -1167,7 +1168,7 @@ def _get_info (self, fontname, font_class, sym, fontsize, dpi, math=True):
11671168

11681169
xmin, ymin, xmax, ymax = [val * scale
11691170
for val in font.get_bbox_char(glyph)]
1170-
metrics = Bunch(
1171+
metrics = types.SimpleNamespace(
11711172
advance = font.get_width_char(glyph) * scale,
11721173
width = font.get_width_char(glyph) * scale,
11731174
height = font.get_height_char(glyph) * scale,
@@ -1180,7 +1181,7 @@ def _get_info (self, fontname, font_class, sym, fontsize, dpi, math=True):
11801181
slanted = slanted
11811182
)
11821183

1183-
self.glyphd[key] = Bunch(
1184+
self.glyphd[key] = types.SimpleNamespace(
11841185
font = font,
11851186
fontsize = fontsize,
11861187
postscript_name = font.get_fontname(),
@@ -2290,7 +2291,7 @@ class Parser(object):
22902291
_right_delim = set(r") ] \} > \rfloor \rangle \rceil".split())
22912292

22922293
def __init__(self):
2293-
p = Bunch()
2294+
p = types.SimpleNamespace()
22942295
# All forward declarations are here
22952296
p.accent = Forward()
22962297
p.ambi_delim = Forward()

lib/matplotlib/projections/polar.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import six
55

66
from collections import OrderedDict
7+
import types
78

89
import numpy as np
910

@@ -1362,7 +1363,7 @@ def start_pan(self, x, y, button):
13621363
elif button == 3:
13631364
mode = 'zoom'
13641365

1365-
self._pan_start = cbook.Bunch(
1366+
self._pan_start = types.SimpleNamespace(
13661367
rmax=self.get_rmax(),
13671368
trans=self.transData.frozen(),
13681369
trans_inverse=self.transData.inverted().frozen(),

lib/matplotlib/sankey.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66

77
import six
88
import logging
9+
from types import SimpleNamespace
910
from six.moves import zip
1011
import numpy as np
1112

12-
from matplotlib.cbook import iterable, Bunch
13+
from matplotlib.cbook import iterable
1314
from matplotlib.path import Path
1415
from matplotlib.patches import PathPatch
1516
from matplotlib.transforms import Affine2D
@@ -780,8 +781,9 @@ def _get_angle(a, r):
780781
# where either could determine the margins (e.g., arrow shoulders).
781782

782783
# Add this diagram as a subdiagram.
783-
self.diagrams.append(Bunch(patch=patch, flows=flows, angles=angles,
784-
tips=tips, text=text, texts=texts))
784+
self.diagrams.append(
785+
SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips,
786+
text=text, texts=texts))
785787

786788
# Allow a daisy-chained call structure (see docstring for the class).
787789
return self

lib/matplotlib/type1font.py

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import six
2929

3030
import binascii
31+
import enum
3132
import io
3233
import itertools
3334
import re
@@ -40,6 +41,11 @@ def ord(x):
4041
return x
4142

4243

44+
# token types
45+
_TokenType = enum.Enum('_TokenType',
46+
'whitespace name string delimiter number')
47+
48+
4349
class Type1Font(object):
4450
"""
4551
A class representing a Type-1 font, for use by backends.
@@ -143,25 +149,18 @@ def _split(self, data):
143149
_comment_re = re.compile(br'%[^\r\n\v]*')
144150
_instring_re = re.compile(br'[()\\]')
145151

146-
# token types, compared via object identity (poor man's enum)
147-
_whitespace = object()
148-
_name = object()
149-
_string = object()
150-
_delimiter = object()
151-
_number = object()
152-
153152
@classmethod
154153
def _tokens(cls, text):
155154
"""
156155
A PostScript tokenizer. Yield (token, value) pairs such as
157-
(cls._whitespace, ' ') or (cls._name, '/Foobar').
156+
(_TokenType.whitespace, ' ') or (_TokenType.name, '/Foobar').
158157
"""
159158
pos = 0
160159
while pos < len(text):
161160
match = (cls._comment_re.match(text[pos:]) or
162161
cls._whitespace_re.match(text[pos:]))
163162
if match:
164-
yield (cls._whitespace, match.group())
163+
yield (_TokenType.whitespace, match.group())
165164
pos += match.end()
166165
elif text[pos] == b'(':
167166
start = pos
@@ -178,25 +177,25 @@ def _tokens(cls, text):
178177
depth -= 1
179178
else: # a backslash - skip the next character
180179
pos += 1
181-
yield (cls._string, text[start:pos])
180+
yield (_TokenType.string, text[start:pos])
182181
elif text[pos:pos + 2] in (b'<<', b'>>'):
183-
yield (cls._delimiter, text[pos:pos + 2])
182+
yield (_TokenType.delimiter, text[pos:pos + 2])
184183
pos += 2
185184
elif text[pos] == b'<':
186185
start = pos
187186
pos += text[pos:].index(b'>')
188-
yield (cls._string, text[start:pos])
187+
yield (_TokenType.string, text[start:pos])
189188
else:
190189
match = cls._token_re.match(text[pos:])
191190
if match:
192191
try:
193192
float(match.group())
194-
yield (cls._number, match.group())
193+
yield (_TokenType.number, match.group())
195194
except ValueError:
196-
yield (cls._name, match.group())
195+
yield (_TokenType.name, match.group())
197196
pos += match.end()
198197
else:
199-
yield (cls._delimiter, text[pos:pos + 1])
198+
yield (_TokenType.delimiter, text[pos:pos + 1])
200199
pos += 1
201200

202201
def _parse(self):
@@ -210,23 +209,23 @@ def _parse(self):
210209
'UnderlinePosition': -100, 'UnderlineThickness': 50}
211210
filtered = ((token, value)
212211
for token, value in self._tokens(self.parts[0])
213-
if token is not self._whitespace)
212+
if token is not _TokenType.whitespace)
214213
# The spec calls this an ASCII format; in Python 2.x we could
215214
# just treat the strings and names as opaque bytes but let's
216215
# turn them into proper Unicode, and be lenient in case of high bytes.
217216
convert = lambda x: x.decode('ascii', 'replace')
218217
for token, value in filtered:
219-
if token is self._name and value.startswith(b'/'):
218+
if token is _TokenType.name and value.startswith(b'/'):
220219
key = convert(value[1:])
221220
token, value = next(filtered)
222-
if token is self._name:
221+
if token is _TokenType.name:
223222
if value in (b'true', b'false'):
224223
value = value == b'true'
225224
else:
226225
value = convert(value.lstrip(b'/'))
227-
elif token is self._string:
226+
elif token is _TokenType.string:
228227
value = convert(value.lstrip(b'(').rstrip(b')'))
229-
elif token is self._number:
228+
elif token is _TokenType.number:
230229
if b'.' in value:
231230
value = float(value)
232231
else:
@@ -284,7 +283,7 @@ def replacer(tokens):
284283
token, value = next(tokens) # name, e.g., /FontMatrix
285284
yield bytes(value)
286285
token, value = next(tokens) # possible whitespace
287-
while token is cls._whitespace:
286+
while token is _TokenType.whitespace:
288287
yield bytes(value)
289288
token, value = next(tokens)
290289
if value != b'[': # name/number/etc.
@@ -309,7 +308,7 @@ def suppress(tokens):
309308
b'/UniqueID': suppress}
310309

311310
for token, value in tokens:
312-
if token is cls._name and value in table:
311+
if token is _TokenType.name and value in table:
313312
for value in table[value](itertools.chain([(token, value)],
314313
tokens)):
315314
yield value

0 commit comments

Comments
 (0)