Skip to content
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: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ mplotutils now uses the MIT license instead of GPL-3.0 ([#51](https://github.com

* Deprecated `mpu.infer_interval_breaks` as this is no longer necessary with matplotlib v3.2
and cartopy v0.21 ([#32](https://github.com/mathause/mplotutils/pull/32)).
* Deprecated a number of positional arguments, these are now keyword only, e.g. in
`mpu.colorbar` ([#54](https://github.com/mathause/mplotutils/pull/54)).

### Enhancements

Expand Down
29 changes: 29 additions & 0 deletions licenses/SCIKIT_LEARN_LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2007-2021 The scikit-learn developers.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4 changes: 4 additions & 0 deletions mplotutils/_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
import matplotlib.pyplot as plt
import numpy as np

from mplotutils._deprecate import _deprecate_positional_args


@_deprecate_positional_args("0.3")
def colorbar(
mappable,
ax1,
ax2=None,
*,
orientation="vertical",
aspect=None,
size=None,
Expand Down
112 changes: 112 additions & 0 deletions mplotutils/_deprecate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# Adapted from scikit-learn https://github.com/scikit-learn/scikit-learn/pull/13311
# For reference, here is a copy of their copyright notice:

# BSD 3-Clause License

# Copyright (c) 2007-2021 The scikit-learn developers.
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.

# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.

# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import inspect
import warnings
from functools import wraps

POSITIONAL_OR_KEYWORD = inspect.Parameter.POSITIONAL_OR_KEYWORD
KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY
POSITIONAL_ONLY = inspect.Parameter.POSITIONAL_ONLY
EMPTY = inspect.Parameter.empty


def _deprecate_positional_args(version):
"""Decorator for methods that issues warnings for positional arguments
Using the keyword-only argument syntax in pep 3102, arguments after the
``*`` will issue a warning when passed as a positional argument.

Parameters
----------
version : str
version of the library when the positional arguments were deprecated

Examples
--------
Deprecate passing `b` as positional argument:
>>> def func(a, b=1):
... pass
>>> @_deprecate_positional_args("v0.1.0")
... def func(a, *, b=2):
... pass
>>> func(1, 2)

Notes
-----
This function is adapted from scikit-learn under the terms of its license. See
"""

def _decorator(func):

signature = inspect.signature(func)

pos_or_kw_args = []
kwonly_args = []
for name, param in signature.parameters.items():
if param.kind in (POSITIONAL_OR_KEYWORD, POSITIONAL_ONLY):
pos_or_kw_args.append(name)
elif param.kind == KEYWORD_ONLY:
kwonly_args.append(name)
if param.default is EMPTY:
# IMHO `def f(a, *, b):` does not make sense -> disallow it
# if removing this constraint -> need to add these to kwargs as well
raise TypeError("Keyword-only param without default disallowed.")

@wraps(func)
def inner(*args, **kwargs):

name = func.__name__
n_extra_args = len(args) - len(pos_or_kw_args)
if n_extra_args > 0:

extra_args = ", ".join(kwonly_args[:n_extra_args])

warnings.warn(
f"Passing '{extra_args}' as positional argument(s) to {name} "
f"was deprecated in version {version} and will raise an error two "
"releases later. Please pass them as keyword arguments."
"",
FutureWarning,
stacklevel=2,
)

zip_args = zip(kwonly_args[:n_extra_args], args[-n_extra_args:])
kwargs.update({name: arg for name, arg in zip_args})

return func(*args[:-n_extra_args], **kwargs)

return func(*args, **kwargs)

return inner

return _decorator
14 changes: 10 additions & 4 deletions mplotutils/cartopy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
import shapely.geometry
from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER

from .colormaps import _get_label_attr
from mplotutils._deprecate import _deprecate_positional_args

# =============================================================================
from .colormaps import _get_label_attr


def sample_data_map(nlons, nlats):
Expand Down Expand Up @@ -115,7 +115,8 @@ def cyclic_dataarray(obj, coord="lon"):
return obj.pad({coord: (0, 1)}, mode="wrap")


def ylabel_map(s, labelpad=None, size=None, weight=None, y=0.5, ax=None, **kwargs):
@_deprecate_positional_args("0.3")
def ylabel_map(s, *, labelpad=None, size=None, weight=None, y=0.5, ax=None, **kwargs):
"""
add ylabel to cartopy plot

Expand Down Expand Up @@ -180,7 +181,8 @@ def ylabel_map(s, labelpad=None, size=None, weight=None, y=0.5, ax=None, **kwarg
# =============================================================================


def xlabel_map(s, labelpad=None, size=None, weight=None, x=0.5, ax=None, **kwargs):
@_deprecate_positional_args("0.3")
def xlabel_map(s, *, labelpad=None, size=None, weight=None, x=0.5, ax=None, **kwargs):
"""
add xlabel to cartopy plot

Expand Down Expand Up @@ -245,8 +247,10 @@ def xlabel_map(s, labelpad=None, size=None, weight=None, x=0.5, ax=None, **kwarg
# =============================================================================


@_deprecate_positional_args("0.3")
def yticklabels(
y_ticks,
*,
labelpad=None,
size=None,
weight=None,
Expand Down Expand Up @@ -347,8 +351,10 @@ def yticklabels(
)


@_deprecate_positional_args("0.3")
def xticklabels(
x_ticks,
*,
labelpad=None,
size=None,
weight=None,
Expand Down
5 changes: 4 additions & 1 deletion mplotutils/map_layout.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import matplotlib.pyplot as plt
import numpy as np

from mplotutils._deprecate import _deprecate_positional_args

def set_map_layout(axes, width=17.0, nrow=None, ncol=None):

@_deprecate_positional_args("0.3")
def set_map_layout(axes, width=17.0, *, nrow=None, ncol=None):
"""set figure height, given width, taking axes' aspect ratio into account

Needs to be called after all plotting is done.
Expand Down
13 changes: 13 additions & 0 deletions mplotutils/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,19 @@ def test_parse_size_aspect_pad():
# =============================================================================


@pytest.mark.parametrize("orientation", ["vertical", "horizontal"])
def test_colorbar_deprecate_positional(orientation):

with subplots_context(1, 2) as (f, axs):

h = axs[0].pcolormesh([[0, 1]])

with pytest.warns(
FutureWarning, match="Passing 'orientation' as positional argument"
):
mpu.colorbar(h, axs[0], axs[0], orientation)


def test_colorbar_different_figures():

with figure_context() as f1, figure_context() as f2:
Expand Down
140 changes: 140 additions & 0 deletions mplotutils/tests/test_deprecate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import pytest

from mplotutils._deprecate import _deprecate_positional_args


def test_deprecate_positional_args_warns_for_function():
@_deprecate_positional_args("v0.1")
def f1(a, b, *, c="c", d="d"):
return a, b, c, d

result = f1(1, 2)
assert result == (1, 2, "c", "d")

result = f1(1, 2, c=3, d=4)
assert result == (1, 2, 3, 4)

with pytest.warns(FutureWarning, match=r".*v0.1"):
result = f1(1, 2, 3)
assert result == (1, 2, 3, "d")

with pytest.warns(FutureWarning, match=r"Passing 'c' as positional"):
result = f1(1, 2, 3)
assert result == (1, 2, 3, "d")

with pytest.warns(FutureWarning, match=r"Passing 'c, d' as positional"):
result = f1(1, 2, 3, 4)
assert result == (1, 2, 3, 4)

@_deprecate_positional_args("v0.1")
def f2(a="a", *, b="b", c="c", d="d"):
return a, b, c, d

with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
result = f2(1, 2)
assert result == (1, 2, "c", "d")

@_deprecate_positional_args("v0.1")
def f3(a, *, b="b", **kwargs):
return a, b, kwargs

with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
result = f3(1, 2)
assert result == (1, 2, {})

with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
result = f3(1, 2, f="f")
assert result == (1, 2, {"f": "f"})

# @_deprecate_positional_args("v0.1")
# def f4(a, /, *, b="b", **kwargs):
# return a, b, kwargs

# result = f4(1)
# assert result == (1, "b", {})

# result = f4(1, b=2, f="f")
# assert result == (1, 2, {"f": "f"})

# with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
# result = f4(1, 2, f="f")
# assert result == (1, 2, {"f": "f"})

with pytest.raises(TypeError, match=r"Keyword-only param without default"):

@_deprecate_positional_args("v0.1")
def f5(a, *, b, c=3, **kwargs):
pass


def test_deprecate_positional_args_warns_for_class():
class A1:
@_deprecate_positional_args("v0.1")
def method(self, a, b, *, c="c", d="d"):
return a, b, c, d

result = A1().method(1, 2)
assert result == (1, 2, "c", "d")

result = A1().method(1, 2, c=3, d=4)
assert result == (1, 2, 3, 4)

with pytest.warns(FutureWarning, match=r".*v0.1"):
result = A1().method(1, 2, 3)
assert result == (1, 2, 3, "d")

with pytest.warns(FutureWarning, match=r"Passing 'c' as positional"):
result = A1().method(1, 2, 3)
assert result == (1, 2, 3, "d")

with pytest.warns(FutureWarning, match=r"Passing 'c, d' as positional"):
result = A1().method(1, 2, 3, 4)
assert result == (1, 2, 3, 4)

class A2:
@_deprecate_positional_args("v0.1")
def method(self, a=1, b=1, *, c="c", d="d"):
return a, b, c, d

with pytest.warns(FutureWarning, match=r"Passing 'c' as positional"):
result = A2().method(1, 2, 3)
assert result == (1, 2, 3, "d")

with pytest.warns(FutureWarning, match=r"Passing 'c, d' as positional"):
result = A2().method(1, 2, 3, 4)
assert result == (1, 2, 3, 4)

class A3:
@_deprecate_positional_args("v0.1")
def method(self, a, *, b="b", **kwargs):
return a, b, kwargs

with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
result = A3().method(1, 2)
assert result == (1, 2, {})

with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
result = A3().method(1, 2, f="f")
assert result == (1, 2, {"f": "f"})

# class A4:
# @_deprecate_positional_args("v0.1")
# def method(self, a, /, *, b="b", **kwargs):
# return a, b, kwargs

# result = A4().method(1)
# assert result == (1, "b", {})

# result = A4().method(1, b=2, f="f")
# assert result == (1, 2, {"f": "f"})

# with pytest.warns(FutureWarning, match=r"Passing 'b' as positional"):
# result = A4().method(1, 2, f="f")
# assert result == (1, 2, {"f": "f"})

with pytest.raises(TypeError, match=r"Keyword-only param without default"):

class A5:
@_deprecate_positional_args("v0.1")
def __init__(self, a, *, b, c=3, **kwargs):
pass