Skip to content

Cleanup unused variables and imports #11994

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 1 commit into from
Sep 15, 2018
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: 0 additions & 2 deletions lib/matplotlib/_constrained_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,6 @@ def _align_spines(fig, gs):
height_ratios[rownummin[n]:(rownummax[n] + 1)])

for nn, ax in enumerate(axs[:-1]):
ss0 = ax.get_subplotspec()

# now compare ax to all the axs:
#
# If the subplotspecs have the same colnumXmax, then line
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7772,7 +7772,6 @@ def matshow(self, Z, **kwargs):

"""
Z = np.asanyarray(Z)
nr, nc = Z.shape
kw = {'origin': 'upper',
'interpolation': 'nearest',
'aspect': 'equal', # (already the imshow default)
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import matplotlib.font_manager as font_manager
import matplotlib.text as mtext
import matplotlib.image as mimage
from matplotlib.artist import allow_rasterization

from matplotlib.rcsetup import cycler, validate_axisbelow

Expand Down Expand Up @@ -2540,7 +2539,7 @@ def _update_title_position(self, renderer):
title.set_position((x, ymax))

# Drawing
@allow_rasterization
@martist.allow_rasterization
def draw(self, renderer=None, inframe=False):
"""Draw everything (plot lines, axes, labels)"""
if renderer is None:
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from matplotlib import rcParams
import matplotlib.artist as artist
from matplotlib.artist import allow_rasterization
import matplotlib.cbook as cbook
from matplotlib.cbook import _string_to_bool
import matplotlib.font_manager as font_manager
Expand Down Expand Up @@ -286,7 +285,7 @@ def get_loc(self):
'Return the tick location (data coords) as a scalar'
return self._loc

@allow_rasterization
@artist.allow_rasterization
def draw(self, renderer):
if not self.get_visible():
self.stale = False
Expand Down Expand Up @@ -1174,7 +1173,7 @@ def get_tick_padding(self):
values.append(self.minorTicks[0].get_tick_padding())
return max(values, default=0)

@allow_rasterization
@artist.allow_rasterization
def draw(self, renderer, *args, **kwargs):
'Draw the axis lines, grid lines, tick lines and labels'

Expand Down
57 changes: 20 additions & 37 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -722,45 +722,29 @@ def remove(self, o):


def report_memory(i=0): # argument may go away
"""return the memory consumed by process"""
from subprocess import Popen, PIPE
pid = os.getpid()
if sys.platform == 'sunos5':
"""Return the memory consumed by the process."""
def call(command, os_name):
try:
a2 = Popen(['ps', '-p', '%d' % pid, '-o', 'osz'],
stdout=PIPE).stdout.readlines()
except OSError:
return subprocess.check_output(command)
except subprocess.CalledProcessError:
raise NotImplementedError(
"report_memory works on Sun OS only if "
"the 'ps' program is found")
mem = int(a2[-1].strip())
"report_memory works on %s only if "
"the '%s' program is found" % (os_name, command[0])
)

pid = os.getpid()
if sys.platform == 'sunos5':
lines = call(['ps', '-p', '%d' % pid, '-o', 'osz'], 'Sun OS')
mem = int(lines[-1].strip())
elif sys.platform == 'linux':
try:
a2 = Popen(['ps', '-p', '%d' % pid, '-o', 'rss,sz'],
stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(
"report_memory works on Linux only if "
"the 'ps' program is found")
mem = int(a2[1].split()[1])
lines = call(['ps', '-p', '%d' % pid, '-o', 'rss,sz'], 'Linux')
mem = int(lines[1].split()[1])
elif sys.platform == 'darwin':
try:
a2 = Popen(['ps', '-p', '%d' % pid, '-o', 'rss,vsz'],
stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(
"report_memory works on Mac OS only if "
"the 'ps' program is found")
mem = int(a2[1].split()[0])
lines = call(['ps', '-p', '%d' % pid, '-o', 'rss,vsz'], 'Mac OS')
mem = int(lines[1].split()[0])
elif sys.platform == 'win32':
try:
a2 = Popen(["tasklist", "/nh", "/fi", "pid eq %d" % pid],
stdout=PIPE).stdout.read()
except OSError:
raise NotImplementedError(
"report_memory works on Windows only if "
"the 'tasklist' program is found")
mem = int(a2.strip().split()[-2].replace(',', ''))
lines = call(["tasklist", "/nh", "/fi", "pid eq %d" % pid], 'Windows')
mem = int(lines.strip().split()[-2].replace(',', ''))
else:
raise NotImplementedError(
"We don't have a memory monitor for %s" % sys.platform)
Expand Down Expand Up @@ -810,7 +794,6 @@ def print_cycles(objects, outstream=sys.stdout, show_progress=False):
If True, print the number of objects reached as they are found.
"""
import gc
from types import FrameType

def print_path(path):
for i, step in enumerate(path):
Expand Down Expand Up @@ -851,7 +834,7 @@ def recurse(obj, start, all, current_path):
# Don't go back through the original list of objects, or
# through temporary references to the object, since those
# are just an artifact of the cycle detector itself.
elif referent is objects or isinstance(referent, FrameType):
elif referent is objects or isinstance(referent, types.FrameType):
continue

# We haven't seen this object before, so recurse
Expand Down Expand Up @@ -2006,7 +1989,7 @@ def _warn_external(message, category=None):
etc.).
"""
frame = sys._getframe()
for stacklevel in itertools.count(1):
for stacklevel in itertools.count(1): # lgtm[py/unused-loop-variable]
Copy link
Contributor

Choose a reason for hiding this comment

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

really, lgtm can't see that stacklevel is used below the loop?...

Copy link
Member Author

Choose a reason for hiding this comment

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

Not using the loop variable within the loop is often an error, even if it's used afterwards. I think this is what they want to indicate here.

Copy link
Contributor

Choose a reason for hiding this comment

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

Frankly, I don't like peppering the code with comments to appease bad linters.

Copy link
Member Author

Choose a reason for hiding this comment

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

Well, I think that the alert is a valid concern, and a statement that stacklevel is intentionally not used in the loop is justified here. I did not put comments in other places where the linting was just not good enough.

Copy link
Contributor

Choose a reason for hiding this comment

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

I guess I should just write something like (untested)

    def recur(f, x0):
        return itertools.accumulate(lambda x, _: f(x), itertools.repeat(x0))

    stacklevel = 1 + next(
        i for i, fr in enumerate(recur(lambda fr: fr.f_back, sys._getframe()))
        if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.)",
                        fr.f_globals["name"])

and keep lgtm happy :p
(abusing accumulate to repeatedly just apply a function is actually documented as an example in https://docs.python.org/3/library/itertools.html#itertools.accumulate...)

if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.)",
frame.f_globals["__name__"]):
break
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -1056,7 +1056,7 @@ def __init__(self, ax, mappable, **kw):

self.mappable = mappable
kw['cmap'] = cmap = mappable.cmap
kw['norm'] = norm = mappable.norm
kw['norm'] = mappable.norm

if isinstance(mappable, contour.ContourSet):
CS = mappable
Expand Down
2 changes: 0 additions & 2 deletions lib/matplotlib/dviread.py
Original file line number Diff line number Diff line change
Expand Up @@ -964,8 +964,6 @@ def __iter__(self):

@staticmethod
def _parse(file):
result = []

lines = (line.split(b'%', 1)[0].strip() for line in file)
data = b''.join(lines)
beginning = data.find(b'[')
Expand Down
24 changes: 9 additions & 15 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,9 @@

import matplotlib.artist as martist
from matplotlib.artist import Artist, allow_rasterization

import matplotlib.cbook as cbook

from matplotlib.cbook import Stack

from matplotlib import image as mimage
from matplotlib.image import FigureImage

import matplotlib.colorbar as cbar
import matplotlib.image as mimage

from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
Expand All @@ -57,7 +51,7 @@ def _stale_figure_callback(self, val):
self.figure.stale = val


class AxesStack(Stack):
class AxesStack(cbook.Stack):
"""
Specialization of the `.Stack` to handle all tracking of
`~matplotlib.axes.Axes` in a `.Figure`.
Expand All @@ -74,7 +68,7 @@ class AxesStack(Stack):

"""
def __init__(self):
Stack.__init__(self)
super().__init__()
self._ind = 0

def as_list(self):
Expand Down Expand Up @@ -108,14 +102,14 @@ def _entry_from_axes(self, e):

def remove(self, a):
"""Remove the axes from the stack."""
Stack.remove(self, self._entry_from_axes(a))
super().remove(self._entry_from_axes(a))

def bubble(self, a):
"""
Move the given axes, which must already exist in the
stack, to the top.
"""
return Stack.bubble(self, self._entry_from_axes(a))
return super().bubble(self._entry_from_axes(a))

def add(self, key, a):
"""
Expand All @@ -137,15 +131,15 @@ def add(self, key, a):

a_existing = self.get(key)
if a_existing is not None:
Stack.remove(self, (key, a_existing))
super().remove((key, a_existing))
warnings.warn(
"key {!r} already existed; Axes is being replaced".format(key))
# I don't think the above should ever happen.

if a in self:
return None
self._ind += 1
return Stack.push(self, (key, (self._ind, a)))
return super().push((key, (self._ind, a)))

def current_key_axes(self):
"""
Expand Down Expand Up @@ -331,7 +325,7 @@ def __init__(self,
:meth:`.subplot2grid`.)
Defaults to :rc:`figure.constrained_layout.use`.
"""
Artist.__init__(self)
super().__init__()
# remove the non-figure artist _axes property
# as it makes no sense for a figure to be _in_ an axes
# this is used by the property methods in the artist base class
Expand Down Expand Up @@ -859,7 +853,7 @@ def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None,
figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
self.set_size_inches(figsize, forward=True)

im = FigureImage(self, cmap, norm, xo, yo, origin, **kwargs)
im = mimage.FigureImage(self, cmap, norm, xo, yo, origin, **kwargs)
im.stale_callback = _stale_figure_callback

im.set_array(X)
Expand Down
2 changes: 0 additions & 2 deletions lib/matplotlib/fontconfig_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,6 @@ def generate_fontconfig_pattern(d):
pattern string.
"""
props = []
families = ''
size = ''
for key in 'family style variant weight stretch file size'.split():
val = getattr(d, 'get_' + key)()
if val is not None and val != []:
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

from matplotlib import rcParams
import matplotlib.artist as martist
from matplotlib.artist import allow_rasterization
from matplotlib.backend_bases import FigureCanvasBase
import matplotlib.colors as mcolors
import matplotlib.cm as cm
Expand Down Expand Up @@ -557,7 +556,7 @@ def _check_unsampled_image(self, renderer):
"""
return False

@allow_rasterization
@martist.allow_rasterization
def draw(self, renderer, *args, **kwargs):
# if not visible, declare victory and return
if not self.get_visible():
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,6 @@ def _get_glyph(self, fontname, font_class, sym, fontsize, math=True):
new_fontname, sym, uniindex),
MathTextWarning)
fontname = 'rm'
new_fontname = fontname
font = self._get_font(fontname)
uniindex = 0xA4 # currency char, for lack of anything better
glyphindex = font.get_char_index(uniindex)
Expand Down Expand Up @@ -1168,7 +1167,7 @@ def _get_info(self, fontname, font_class, sym, fontsize, dpi, math=True):
found_symbol = False

if not found_symbol:
glyph = sym = '?'
glyph = '?'
num = ord(glyph)
symbol_name = font.get_name_char(glyph)

Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/mlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -3447,7 +3447,6 @@ def stineman_interp(xi, x, y, yp=None):
yp = np.asarray(yp, float)

xi = np.asarray(xi, float)
yi = np.zeros(xi.shape, float)

# calculate linear slopes
dx = x[1:] - x[:-1]
Expand Down
3 changes: 0 additions & 3 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -3079,9 +3079,6 @@ def connect(self, posA, posB):
dd2 = (dx * dx + dy * dy) ** .5
ddx, ddy = dx / dd2, dy / dd2

else:
dl = 0.

arm = max(armA, armB)
f = self.fraction * dd + arm

Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/projections/geo.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ def __str__(self):
return "{}({})".format(type(self).__name__, self._resolution)

def transform_path_non_affine(self, path):
vertices = path.vertices
ipath = path.interpolated(self._resolution)
return Path(self.transform(ipath.vertices), ipath.codes)
transform_path_non_affine.__doc__ = \
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import matplotlib.transforms as transforms
import matplotlib.text as mtext
import matplotlib.artist as martist
from matplotlib.artist import allow_rasterization
from matplotlib import docstring
import matplotlib.font_manager as font_manager
from matplotlib.cbook import delete_masked_points
Expand Down Expand Up @@ -341,7 +340,7 @@ def _text_y(self, y):
else:
return y

@allow_rasterization
@martist.allow_rasterization
def draw(self, renderer):
self._init()
self.vector.draw(renderer)
Expand Down Expand Up @@ -540,7 +539,7 @@ def get_datalim(self, transData):
bbox.update_from_data_xy(XY, ignore=True)
return bbox

@allow_rasterization
@martist.allow_rasterization
def draw(self, renderer):
self._init()
verts = self._make_verts(self.U, self.V, self.angles)
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/stackplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ def stackplot(axes, x, *args,
stack += first_line

elif baseline == 'weighted_wiggle':
m, n = y.shape
total = np.sum(y, 0)
# multiply by 1/total (or zero) to avoid infinities in the division:
inv_total = np.zeros_like(total)
Expand Down
1 change: 0 additions & 1 deletion lib/matplotlib/textpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,6 @@ def get_glyphs_mathtext(self, prop, s, glyph_map=None,
glyph_ids = []
sizes = []

currx, curry = 0, 0
for font, fontsize, ccode, ox, oy in glyphs:
char_id = self._get_char_id(font, ccode)
if char_id not in glyph_map:
Expand Down
Loading