Skip to content

Change manual kwargs popping to kwonly arguments. #10545

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
Apr 24, 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
3 changes: 1 addition & 2 deletions examples/api/radar_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,8 @@ def __init__(self, *args, **kwargs):
# rotate plot such that the first axis is at the top
self.set_theta_zero_location('N')

def fill(self, *args, **kwargs):
def fill(self, *args, closed=True, **kwargs):
"""Override fill so that line is closed by default"""
closed = kwargs.pop('closed', True)
return super().fill(closed=closed, *args, **kwargs)

def plot(self, *args, **kwargs):
Expand Down
3 changes: 1 addition & 2 deletions examples/images_contours_and_fields/contour_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@
plt.setp(zc, linewidth=4)

ax.clabel(CS, levels[1::2], # label every second level
inline=1, fmt='%1.1f',
cmap='flag', fontsize=14)
inline=1, fmt='%1.1f', fontsize=14)

# make a colorbar for the contour lines
CB = fig.colorbar(CS, shrink=0.8, extend='both')
Expand Down
5 changes: 2 additions & 3 deletions examples/scales/custom_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class MercatorLatitudeScale(mscale.ScaleBase):
# scale.
name = 'mercator'

def __init__(self, axis, **kwargs):
def __init__(self, axis, *, thresh=np.deg2rad(85), **kwargs):
"""
Any keyword arguments passed to ``set_xscale`` and
``set_yscale`` will be passed along to the scale's
Expand All @@ -53,8 +53,7 @@ def __init__(self, axis, **kwargs):
thresh: The degree above which to crop the data.
"""
mscale.ScaleBase.__init__(self)
thresh = kwargs.pop("thresh", np.radians(85))
if thresh >= np.pi / 2.0:
if thresh >= np.pi / 2:
raise ValueError("thresh must be less than pi/2")
self.thresh = thresh

Expand Down
5 changes: 2 additions & 3 deletions examples/subplots_axes_and_figures/custom_figure_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@


class MyFigure(Figure):
def __init__(self, *args, **kwargs):
def __init__(self, *args, figtitle='hi mom', **kwargs):
"""
custom kwarg figtitle is a figure title
"""
figtitle = kwargs.pop('figtitle', 'hi mom')
Figure.__init__(self, *args, **kwargs)
super().__init__(*args, **kwargs)
self.text(0.5, 0.95, figtitle, ha='center')


Expand Down
21 changes: 7 additions & 14 deletions examples/text_labels_and_annotations/usetex_baseline_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,15 @@ class Axes(maxes.Axes):
usetex=False in the same figure. It does not work in the ps backend.
"""

def __init__(self, *kl, **kw):
self.usetex = kw.pop("usetex", "False")
self.preview = kw.pop("preview", "False")

maxes.Axes.__init__(self, *kl, **kw)
def __init__(self, *args, usetex=False, preview=False, **kwargs):
self.usetex = usetex
self.preview = preview
super().__init__(*args, **kwargs)

def draw(self, renderer):
usetex = plt.rcParams["text.usetex"]
preview = plt.rcParams["text.latex.preview"]
plt.rcParams["text.usetex"] = self.usetex
plt.rcParams["text.latex.preview"] = self.preview

maxes.Axes.draw(self, renderer)

plt.rcParams["text.usetex"] = usetex
plt.rcParams["text.latex.preview"] = preview
with plt.rc_context({"text.usetex": self.usetex,
"text.latex.preview": self.preview}):
super().draw(renderer)


subplot = maxes.subplot_class_factory(Axes)
Expand Down
6 changes: 3 additions & 3 deletions examples/user_interfaces/toolmanager_sgskip.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ class GroupHideTool(ToolToggleBase):
description = 'Show by gid'
default_toggled = True

def __init__(self, *args, **kwargs):
self.gid = kwargs.pop('gid')
ToolToggleBase.__init__(self, *args, **kwargs)
def __init__(self, *args, gid, **kwargs):
self.gid = gid
super().__init__(*args, **kwargs)

def enable(self, *args):
self.set_lines_visibility(True)
Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1703,7 +1703,7 @@ def param(func):
pass

@functools.wraps(func)
def inner(ax, *args, **kwargs):
def inner(ax, *args, data=None, **kwargs):
# this is needed because we want to change these values if
# arg_names_at_runtime==True, but python does not allow assigning
# to a variable in a outer scope. So use some new local ones and
Expand All @@ -1714,8 +1714,6 @@ def inner(ax, *args, **kwargs):

label = None

data = kwargs.pop('data', None)

if data is None: # data validation
args = tuple(sanitize_sequence(a) for a in args)
else:
Expand Down
24 changes: 9 additions & 15 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5243,20 +5243,14 @@ def imshow(self, X, cmap=None, norm=None, aspect=None,
return im

@staticmethod
def _pcolorargs(funcname, *args, **kw):
# This takes one kwarg, allmatch.
# If allmatch is True, then the incoming X, Y, C must
# have matching dimensions, taking into account that
# X and Y can be 1-D rather than 2-D. This perfect
# match is required for Gouroud shading. For flat
# shading, X and Y specify boundaries, so we need
# one more boundary than color in each direction.
# For convenience, and consistent with Matlab, we
# discard the last row and/or column of C if necessary
# to meet this condition. This is done if allmatch
# is False.

allmatch = kw.pop("allmatch", False)
def _pcolorargs(funcname, *args, allmatch=False):
# If allmatch is True, then the incoming X, Y, C must have matching
# dimensions, taking into account that X and Y can be 1-D rather than
# 2-D. This perfect match is required for Gouroud shading. For flat
# shading, X and Y specify boundaries, so we need one more boundary
# than color in each direction. For convenience, and consistent with
# Matlab, we discard the last row and/or column of C if necessary to
# meet this condition. This is done if allmatch is False.

if len(args) == 1:
C = np.asanyarray(args[0])
Expand Down Expand Up @@ -5303,7 +5297,7 @@ def _pcolorargs(funcname, *args, **kw):
'Incompatible X, Y inputs to %s; see help(%s)' % (
funcname, funcname))
if allmatch:
if not (Nx == numCols and Ny == numRows):
if (Nx, Ny) != (numCols, numRows):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
Expand Down
13 changes: 5 additions & 8 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2683,7 +2683,8 @@ def grid(self, b=None, which='major', axis='both', **kwargs):
if axis == 'y' or axis == 'both':
self.yaxis.grid(b, which=which, **kwargs)

def ticklabel_format(self, **kwargs):
def ticklabel_format(self, *, axis='both', style='', scilimits=None,
useOffset=None, useLocale=None, useMathText=None):
"""
Change the `~matplotlib.ticker.ScalarFormatter` used by
default for linear axes.
Expand All @@ -2693,6 +2694,7 @@ def ticklabel_format(self, **kwargs):
============== =========================================
Keyword Description
============== =========================================
*axis* [ 'x' | 'y' | 'both' ]
*style* [ 'sci' (or 'scientific') | 'plain' ]
plain turns off scientific notation
*scilimits* (m, n), pair of integers; if *style*
Expand All @@ -2705,7 +2707,6 @@ def ticklabel_format(self, **kwargs):
if False, no offset will be used; if a
numeric offset is specified, it will be
used.
*axis* [ 'x' | 'y' | 'both' ]
*useLocale* If True, format the number according to
the current locale. This affects things
such as the character used for the
Expand All @@ -2724,12 +2725,8 @@ def ticklabel_format(self, **kwargs):
:exc:`AttributeError` will be raised.

"""
style = kwargs.pop('style', '').lower()
scilimits = kwargs.pop('scilimits', None)
useOffset = kwargs.pop('useOffset', None)
useLocale = kwargs.pop('useLocale', None)
useMathText = kwargs.pop('useMathText', None)
axis = kwargs.pop('axis', 'both').lower()
style = style.lower()
axis = axis.lower()
if scilimits is not None:
try:
m, n = scilimits
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1616,7 +1616,7 @@ def set_pickradius(self, pickradius):
"""
self.pickradius = pickradius

def set_ticklabels(self, ticklabels, *args, **kwargs):
def set_ticklabels(self, ticklabels, *args, minor=False, **kwargs):
"""
Set the text values of the tick labels. Return a list of Text
instances. Use *kwarg* *minor=True* to select minor ticks.
Expand Down Expand Up @@ -1645,7 +1645,6 @@ def set_ticklabels(self, ticklabels, *args, **kwargs):
# replace the ticklabels list with the processed one
ticklabels = get_labels

minor = kwargs.pop('minor', False)
if minor:
self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
ticks = self.get_minor_ticks()
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def print_to_buffer(self):

if _has_pil:
# add JPEG support
def print_jpg(self, filename_or_obj, *args, **kwargs):
def print_jpg(self, filename_or_obj, *args, dryrun=False, **kwargs):
"""
Other Parameters
----------------
Expand All @@ -536,7 +536,7 @@ def print_jpg(self, filename_or_obj, *args, **kwargs):
should be stored as a progressive JPEG file.
"""
buf, size = self.print_to_buffer()
if kwargs.pop("dryrun", False):
if dryrun:
return
# The image is "pasted" onto a white background image to safely
# handle any transparency
Expand All @@ -557,9 +557,9 @@ def print_jpg(self, filename_or_obj, *args, **kwargs):
print_jpeg = print_jpg

# add TIFF support
def print_tif(self, filename_or_obj, *args, **kwargs):
def print_tif(self, filename_or_obj, *args, dryrun=False, **kwargs):
buf, size = self.print_to_buffer()
if kwargs.pop("dryrun", False):
if dryrun:
return
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
dpi = (self.figure.dpi, self.figure.dpi)
Expand Down
15 changes: 8 additions & 7 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2560,21 +2560,22 @@ def draw(self):
def get_default_filetype(self):
return 'pdf'

def print_pdf(self, filename, **kwargs):
image_dpi = kwargs.get('dpi', 72) # dpi to use for images
def print_pdf(self, filename, *,
dpi=72, # dpi to use for images
Copy link
Member

Choose a reason for hiding this comment

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

Maybe deprecate dpi and replace by image_dpi? During the deprecation dpi could be catched via kwargs.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

nah, let's try to keep all the print_foo's with as much the same signature as possible

Copy link
Member

Choose a reason for hiding this comment

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

ok.

bbox_inches_restore=None, metadata=None,
**kwargs):
self.figure.set_dpi(72) # there are 72 pdf points to an inch
width, height = self.figure.get_size_inches()
if isinstance(filename, PdfPages):
file = filename._file
else:
file = PdfFile(filename, metadata=kwargs.pop("metadata", None))
file = PdfFile(filename, metadata=metadata)
try:
file.newPage(width, height)
_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
renderer = MixedModeRenderer(
self.figure, width, height, image_dpi,
RendererPdf(file, image_dpi, height, width),
bbox_inches_restore=_bbox_inches_restore)
self.figure, width, height, dpi,
RendererPdf(file, dpi, height, width),
bbox_inches_restore=bbox_inches_restore)
self.figure.draw(renderer)
renderer.finalize()
if not isinstance(filename, PdfPages):
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -802,8 +802,9 @@ class FigureCanvasPgf(FigureCanvasBase):
def get_default_filetype(self):
return 'pdf'

def _print_pgf_to_fh(self, fh, *args, **kwargs):
if kwargs.get("dryrun", False):
def _print_pgf_to_fh(self, fh, *args,
Copy link
Member

Choose a reason for hiding this comment

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

*args is unused -> * only

Copy link
Contributor Author

Choose a reason for hiding this comment

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

see above re: keeping the same signature for all print_foo's. In any case this would mean fixing the call sites as well, so it'll be separate work.

Copy link
Member

Choose a reason for hiding this comment

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

ok.

dryrun=False, bbox_inches_restore=None, **kwargs):
if dryrun:
renderer = RendererPgf(self.figure, None, dummy=True)
self.figure.draw(renderer)
return
Expand Down Expand Up @@ -849,10 +850,9 @@ def _print_pgf_to_fh(self, fh, *args, **kwargs):
r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"
% (w, h))
writeln(fh, r"\pgfusepath{use as bounding box, clip}")
_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
renderer = MixedModeRenderer(self.figure, w, h, dpi,
RendererPgf(self.figure, fh),
bbox_inches_restore=_bbox_inches_restore)
bbox_inches_restore=bbox_inches_restore)
self.figure.draw(renderer)

# end the pgfpicture environment
Expand Down
25 changes: 11 additions & 14 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,9 +959,11 @@ def _print_ps(self, outfile, format, *args, **kwargs):
orientation, isLandscape, papertype,
**kwargs)

def _print_figure(self, outfile, format, dpi=72, facecolor='w', edgecolor='w',
orientation='portrait', isLandscape=False, papertype=None,
metadata=None, **kwargs):
def _print_figure(
self, outfile, format, dpi=72, facecolor='w', edgecolor='w',
orientation='portrait', isLandscape=False, papertype=None,
metadata=None, *,
dryrun=False, bbox_inches_restore=None, **kwargs):
"""
Render the figure to hardcopy. Set the figure patch face and
edge colors. This is useful because some of the GUIs have a
Expand Down Expand Up @@ -1031,8 +1033,6 @@ def _print_figure(self, outfile, format, dpi=72, facecolor='w', edgecolor='w',
self.figure.set_facecolor(facecolor)
self.figure.set_edgecolor(edgecolor)


dryrun = kwargs.get("dryrun", False)
if dryrun:
class NullWriter(object):
def write(self, *kl, **kwargs):
Expand All @@ -1042,14 +1042,12 @@ def write(self, *kl, **kwargs):
else:
self._pswriter = io.StringIO()


# mixed mode rendering
_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
ps_renderer = self._renderer_class(width, height, self._pswriter,
imagedpi=dpi)
renderer = MixedModeRenderer(self.figure,
width, height, dpi, ps_renderer,
bbox_inches_restore=_bbox_inches_restore)
bbox_inches_restore=bbox_inches_restore)

self.figure.draw(renderer)

Expand Down Expand Up @@ -1199,9 +1197,10 @@ def do_nothing():
with io.open(outfile, 'w', encoding='latin-1') as fh:
print_figure_impl(fh)

def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor,
orientation, isLandscape, papertype, metadata=None,
**kwargs):
def _print_figure_tex(
self, outfile, format, dpi, facecolor, edgecolor,
orientation, isLandscape, papertype, metadata=None, *,
dryrun=False, bbox_inches_restore=None, **kwargs):
"""
If text.usetex is True in rc, a temporary pair of tex/eps files
are created to allow tex to manage the text layout via the PSFrags
Expand Down Expand Up @@ -1236,7 +1235,6 @@ def _print_figure_tex(self, outfile, format, dpi, facecolor, edgecolor,
self.figure.set_facecolor(facecolor)
self.figure.set_edgecolor(edgecolor)

dryrun = kwargs.get("dryrun", False)
if dryrun:
class NullWriter(object):
def write(self, *kl, **kwargs):
Expand All @@ -1247,12 +1245,11 @@ def write(self, *kl, **kwargs):
self._pswriter = io.StringIO()

# mixed mode rendering
_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
ps_renderer = self._renderer_class(width, height,
self._pswriter, imagedpi=dpi)
renderer = MixedModeRenderer(self.figure,
width, height, dpi, ps_renderer,
bbox_inches_restore=_bbox_inches_restore)
bbox_inches_restore=bbox_inches_restore)

self.figure.draw(renderer)

Expand Down
11 changes: 5 additions & 6 deletions lib/matplotlib/backends/backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -1215,17 +1215,16 @@ def print_svgz(self, filename, *args, **kwargs):
gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter:
return self.print_svg(gzipwriter)

def _print_svg(self, filename, fh, **kwargs):
image_dpi = kwargs.pop("dpi", 72)
def _print_svg(
self, filename, fh, *, dpi=72, bbox_inches_restore=None, **kwargs):
self.figure.set_dpi(72.0)
width, height = self.figure.get_size_inches()
w, h = width * 72, height * 72

_bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
renderer = MixedModeRenderer(
self.figure, width, height, image_dpi,
RendererSVG(w, h, fh, filename, image_dpi),
bbox_inches_restore=_bbox_inches_restore)
self.figure, width, height, dpi,
RendererSVG(w, h, fh, filename, dpi),
bbox_inches_restore=bbox_inches_restore)

self.figure.draw(renderer)
renderer.finalize()
Expand Down
Loading