8000 Additional cleanups by anntzer · Pull Request #7547 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Additional cleanups #7547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 5, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
set/dict literals/comprehensions.
  • Loading branch information
anntzer committed Dec 4, 2016
commit 69622dd32de172be82c10a03cfd43d49d940cf8a
2 changes: 1 addition & 1 deletion boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ def format_value(value):
# A gensym-like facility in case some function takes an
# argument named washold, ax, or ret
washold, ret, ax = 'washold', 'ret', 'ax'
bad = set(args) | set((varargs, varkw))
bad = set(args) | {varargs, varkw}
while washold in bad or ret in bad or ax in bad:
washold = 'washold' + str(random.randrange(10 ** 12))
ret = 'ret' + str(random.randrange(10 ** 12))
Expand Down
10 changes: 4 additions & 6 deletions doc/sphinxext/gen_gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,10 @@ def gen_gallery(app, doctree):
# images we want to skip for the gallery because they are an unusual
# size that doesn't layout well in a table, or because they may be
# redundant with other images or uninteresting
skips = set([
'mathtext_examples',
'matshow_02',
'matshow_03',
'matplotlib_icon',
])
skips = {'mathtext_examples',
'matshow_02',
'matshow_03',
'matplotlib_icon'}

thumbnails = {}
rows = []
Expand Down
4 changes: 2 additions & 2 deletions examples/pylab_examples/arrow_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
rates_to_bases = {'r1': 'AT', 'r2': 'TA', 'r3': 'GA', 'r4': 'AG', 'r5': 'CA',
'r6': 'AC', 'r7': 'GT', 'r8': 'TG', 'r9': 'CT', 'r10': 'TC',
'r11': 'GC', 'r12': 'CG'}
numbered_bases_to_rates = dict([(v, k) for k, v in rates_to_bases.items()])
lettered_bases_to_rates = dict([(v, 'r' + v) for k, v in rates_to_bases.items()])
numbered_bases_to_rates = {v: k for k, v in rates_to_bases.items()}
lettered_bases_to_rates = {v: 'r' + v for k, v in rates_to_bases.items()}


def add_dicts(d1, d2):
Expand Down
5 changes: 2 additions & 3 deletions examples/tests/backend_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,14 +321,13 @@ def report_missing(dir, flist):
globstr = os.path.join(dir, '*.py')
fnames = glob.glob(globstr)

pyfiles = set([os.path.split(fullpath)[-1] for fullpath in set(fnames)])
pyfiles = {os.path.split(fullpath)[-1] for fullpath in set(fnames)}

exclude = set(excluded.get(dir, []))
flist = set(flist)
missing = list(pyfiles - flist - exclude)
missing.sort()
if missing:
print('%s files not tested: %s' % (dir, ', '.join(missing)))
print('%s files not tested: %s' % (dir, ', '.join(sorted(missing))))


def report_all_missing(directories):
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ class Verbose(object):
instance to handle the output. Default is sys.stdout
"""
levels = ('silent', 'helpful', 'debug', 'debug-annoying')
vald = dict([(level, i) for i, level in enumerate(levels)])
vald = {level: i for i, level in enumerate(levels)}

# parse the verbosity from the command line; flags look like
# --verbose-silent or --verbose-helpful
Expand Down Expand Up @@ -860,10 +860,10 @@ def matplotlib_fname():
_deprecated_ignore_map = {
}

_obsolete_set = set(['tk.pythoninspect', 'legend.isaxes'])
_obsolete_set = {'tk.pythoninspect', 'legend.isaxes'}

# The following may use a value of None to suppress the warning.
_deprecated_set = set(['axes.hold']) # do NOT include in _all_deprecated
_deprecated_set = {'axes.hold'} # do NOT include in _all_deprecated

_all_deprecated = set(chain(_deprecated_ignore_map,
_deprecated_map,
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def _getdefaults(self, ignore, *kwargs):
"""
prop_keys = self._prop_keys
if ignore is None:
ignore = set([])
ignore = set()
prop_keys = prop_keys - ignore

if any(all(kw.get(k, None) is None for kw in kwargs)
Expand Down Expand Up @@ -309,8 +309,8 @@ def _makefill(self, x, y, kw, kwargs):
# *user* explicitly specifies a marker which should be an error.
# We also want to prevent advancing the cycler if there are no
# defaults needed after ignoring the given properties.
ignores = set(['marker', 'markersize', 'markeredgecolor',
'markerfacecolor', 'markeredgewidth'])
ignores = {'marker', 'markersize', 'markeredgecolor',
'markerfacecolor', 'markeredgewidth'}
# Also ignore anything provided by *kwargs*.
for k, v in six.iteritems(kwargs):
if v is not None:
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,8 @@ def _apply_params(self, **kw):
self.label1.set_transform(trans)
trans = self._get_text2_transform()[0]
self.label2.set_transform(trans)
tick_kw = dict([kv for kv in six.iteritems(kw)
if kv[0] in ['color', 'zorder']])
tick_kw = {k: v for k, v in six.iteritems(kw)
if k in ['color', 'zorder']}
if tick_kw:
self.tick1line.set(**tick_kw)
self.tick2line.set(**tick_kw)
Expand All @@ -334,7 +334,7 @@ def _apply_params(self, **kw):
label_list = [k for k in six.iteritems(kw)
if k[0] in ['labelsize', 'labelcolor', 'labelrotation']]
if label_list:
label_kw = dict([(k[5:], v) for (k, v) in label_list])
label_kw = {k[5:]: v for k, v in label_list}
self.label1.set(**label_kw)
self.label2.set(**label_kw)
for k, v in six.iteritems(label_kw):
Expand Down
19 changes: 8 additions & 11 deletions lib/matplotlib/backends/backend_gtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,25 +905,26 @@ class DialogLineprops(object):
)

linestyles = [ls for ls in lines.Line2D.lineStyles if ls.strip()]
linestyled = dict([ (s,i) for i,s in enumerate(linestyles)])
linestyled = {s: i for i, s in enumerate(linestyles)}


markers = [m for m in markers.MarkerStyle.markers if cbook.is_string_like(m)]

markerd = dict([(s,i) for i,s in enumerate(markers)])
markers = [m for m in markers.MarkerStyle.markers
if cbook.is_string_like(m)]
markerd = {s: i for i, s in enumerate(markers)}

def __init__(self, lines):
import gtk.glade

datadir = matplotlib.get_data_path()
gladefile = os.path.join(datadir, 'lineprops.glade')
if not os.path.exists(gladefile):
raise IOError('Could not find gladefile lineprops.glade in %s'%datadir)
raise IOError(
'Could not find gladefile lineprops.glade in %s' % datadir)

self._inited = False
self._updateson = True # suppress updates when setting widgets manually
self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops')
self.wtree.signal_autoconnect(dict([(s, getattr(self, s)) for s in self.signals]))
self.wtree.signal_autoconnect(
{s: getattr(self, s) for s in self.signals})

self.dlg = self.wtree.get_widget('dialog_lineprops')

Expand All @@ -947,7 +948,6 @@ def __init__(self, lines):
self._lastcnt = 0
self._inited = True


def show(self):
'populate the combo box'
self._updateson = False
Expand All @@ -971,7 +971,6 @@ def get_active_line(self):
line = self.lines[ind]
return line


def get_active_linestyle(self):
'get the active lineinestyle'
ind = self.cbox_linestyles.get_active()
Expand Down Expand Up @@ -1005,8 +1004,6 @@ def _update(self):

line.figure.canvas.draw()



def on_combobox_lineprops_changed(self, item):
'update the widgets from the active line'
if not self._inited: return
Expand Down
9 changes: 4 additions & 5 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,8 +318,7 @@ def pdfRepr(self):
grestore=b'Q', textpos=b'Td', selectfont=b'Tf', textmatrix=b'Tm',
show=b'Tj', showkern=b'TJ', setlinewidth=b'w', clip=b'W', shading=b'sh')

Op = Bunch(**dict([(name, Operator(value))
for name, value in six.iteritems(_pdfops)]))
Op = Bunch(**{name: Operator(value) for name, value in six.iteritems(_pdfops)})


def _paint_path(fill, stroke):
Expand Down Expand Up @@ -556,9 +555,9 @@ def close(self):
self.endStream()
# Write out the various deferred objects
self.writeFonts()
self.writeObject(self.alphaStateObject,
dict([(val[0], val[1])
for val in six.itervalues(self.alphaStates)]))
self.writeObject(
self.alphaStateObject,
{val[0]: val[1] for val in six.itervalues(self.alphaStates)})
self.writeHatches()
self.writeGouraudTriangles()
xobjects = dict(x[1:] for x in six.itervalues(self._images))
Copy link
Member

Choose a reason for hiding this comment

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

One more dict comprehension?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/qt_editor/formlayout.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore


BLACKLIST = set(["title", "label"])
BLACKLIST = {"title", "label"}


class ColorButton(QtWidgets.QPushButton):
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/cbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,7 @@ def __repr__(self):

def unique(x):
"""Return a list of unique elements of *x*"""
return list(six.iterkeys(dict([(val, 1) for val in x])))
return list(set(x))


def iterable(obj):
Expand Down Expand Up @@ -1407,15 +1407,15 @@ def finddir(o, match, case=False):

def reverse_dict(d):
Copy link
Member

Choose a reason for hiding this comment

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

Could probably be used in a couple places you've updated...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'd rather deprecate this function... I think everyone can understand what {v: k for k, v in d.items()} does and this way you don't have to go and check whether the function does something funny with duplicates.

Copy link
Member

Choose a reason for hiding this comment

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

No argument there.

"""reverse the dictionary -- may lose data if values are not unique!"""
return dict([(v, k) for k, v in six.iteritems(d)])
return {v: k for k, v in six.iteritems(d)}


def restrict_dict(d, keys):
"""
Return a dictionary that contains those keys that appear in both
d and keys, with values from d.
"""
return dict([(k, v) for (k, v) in six.iteritems(d) if k in keys])
return {k: v for k, v in six.iteritems(d) if k in keys}


def report_memory(i=0): # argument may go away
Expand Down Expand Up @@ -2077,7 +2077,7 @@ def unmasked_index_ranges(mask, compressed=True):
# The ls_mapper maps short codes for line style to their full name used
# by backends
# The reverse mapper is for mapping full names to short ones
ls_mapper_r = dict([(ls[1], ls[0]) for ls in _linestyles])
ls_mapper_r = reverse_dict(ls_mapper)
Copy link
Member

Choose a reason for hiding this comment

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

Can _linestyles be dropped and ls_mapper written as a literal now?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes



def align_iterators(func, *iterables):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def get(self, key):
return item[1]

def _entry_from_axes(self, e):
ind, k = dict([(a, (ind, k)) for (k, (ind, a)) in self._elements])[e]
ind, k = {a: (ind, k) for k, (ind, a) in self._elements}[e]
return (k, (ind, e))

def remove(self, a):
Expand Down
16 changes: 8 additions & 8 deletions lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,14 @@
'extra bold' : 800,
'black' : 900}

font_family_aliases = set([
'serif',
'sans-serif',
'sans serif',
'cursive',
'fantasy',
'monospace',
'sans'])
font_family_aliases = {
'serif',
'sans-serif',
'sans serif',
'cursive',
'fantasy',
'monospace',
'sans'}

# OS Font paths
MSFolders = \
Expand Down
8 changes: 2 additions & 6 deletions lib/matplotlib/gridspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,6 @@ def update(self, **kwargs):
ax.update_params()
ax.set_position(ax.figbox)



def get_subplot_params(self, fig=None):
"""
return a dictionary of subplot layout parameters. The default
Expand All @@ -265,13 +263,12 @@ def get_subplot_params(self, fig=None):
from matplotlib.figure import SubplotParams
import copy
if fig is None:
kw = dict([(k, rcParams["figure.subplot."+k]) \
for k in self._AllowedKeys])
kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys}
subplotpars = SubplotParams(**kw)
else:
subplotpars = copy.copy(fig.subplotpars)

update_kw = dict([(k, getattr(self, k)) for k in self._AllowedKeys])
update_kw = {k: getattr(self, k) for k in self._AllowedKeys}
subplotpars.update(**update_kw)

return subplotpars
Expand Down Expand Up @@ -428,7 +425,6 @@ def get_position(self, fig, return_all=False):
figBottoms, figTops, figLefts, figRights = \
gridspec.get_grid_positions(fig)


rowNum, colNum = divmod(self.num1, ncols)
figBottom = figBottoms[rowNum]
figTop = figTops[rowNum]
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ class _ImageBase(martist.Artist, cm.ScalarMappable):
# backward compatibility just in case.
_interpd = _interpd_
# reverse interp dict
_interpdr = dict([(v, k) for k, v in six.iteritems(_interpd_)])
_interpdr = {v: k for k, v in six.iteritems(_interpd_)}
iterpnames = interpolations_names
# <end unused keys>

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -2410,7 +2410,7 @@ def __init__(self):
p.ambi_delim <<= oneOf(list(self._ambi_delim))
p.left_delim <<= oneOf(list(self._left_delim))
p.right_delim <<= oneOf(list(self._right_delim))
p.right_delim_safe <<= oneOf(list(self._right_delim - set(['}'])) + [r'\}'])
p.right_delim_safe <<= oneOf(list(self._right_delim - {'}'}) + [r'\}'])

p.genfrac <<= Group(
Suppress(Literal(r"\genfrac"))
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/mlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -2495,8 +2495,8 @@ def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1',
def makekey(row):
return tuple([row[name] for name in key])

r1d = dict([(makekey(row), i) for i, row in enumerate(r1)])
r2d = dict([(makekey(row), i) for i, row in enumerate(r2)])
r1d = {makekey(row): i for i, row in enumerate(r1)}
r2d = {makekey(row): i for i, row in enumerate(r2)}

r1keys = set(r1d.keys())
r2keys = set(r2d.keys())
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -1867,7 +1867,7 @@ def __new__(self, stylename, **kw):

try:
_args_pair = [cs.split("=") for cs in _list[1:]]
_args = dict([(k, float(v)) for k, v in _args_pair])
_args = {k: float(v) for k, v in _args_pair}
except ValueError:
raise ValueError("Incorrect style argument : %s" % stylename)
_args.update(kw)
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1797,9 +1797,9 @@ def get_plot_commands():

import inspect

exclude = set(['colormaps', 'colors', 'connect', 'disconnect',
'get_plot_commands', 'get_current_fig_manager',
'ginput', 'plotting', 'waitforbuttonpress'])
exclude = {'colormaps', 'colors', 'connect', 'disconnect',
'get_plot_commands', 'get_current_fig_manager', 'ginput',
'plotting', 'waitforbuttonpress'}
exclude |= set(colormaps())
this_module = inspect.getmodule(get_plot_commands)

Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/rcsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def func(s):
return s.lower()
else:
return s
self.valid = dict([(func(k), k) for k in valid])
self.valid = {func(k): k for k in valid}

def __call__(self, s):
if self.ignorecase:
Expand Down Expand Up @@ -683,9 +683,7 @@ def validate_hatch(s):
"""
if not isinstance(s, six.string_types):
raise ValueError("Hatch pattern must be a string")
unique_chars = set(s)
unknown = (unique_chars -
set(['\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O']))
unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
if unknown:
raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
return s
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/style/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@


# A list of rcParams that should not be applied from styles
STYLE_BLACKLIST = set([
STYLE_BLACKLIST = {
'interactive', 'backend', 'backend.qt4', 'webagg.port',
'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',
'toolbar', 'timezone', 'datapath', 'figure.max_open_warning',
'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'])
'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'}


def _remove_blacklisted_style_params(d, warn=True):
Expand Down
Loading
0