ronantakizawa/codereview-bench huggingface dataset:
Repository: matplotlib/matplotlib
File: lib/matplotlib/_docstring.py (Python)

Code before:
import inspect

from . import _api


def kwarg_doc(text):
    """
    Decorator for defining the documentation used when artist properties are
    passed through as keyword arguments.

    See e.g. the `**kwargs` section in `.Axes.text`.

    The given text is stored in a privat variable ``_kwarg_doc`` on the method.
    It is used for generating the kwdoc list for artists, which we
    auto-generate through docstring interpolation, e.g. via
    ``%(Line2D:kwdoc)s``.

    The text should contain the supported types as well as the default value
    if applicable, e.g.:

        @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
        def set_usetex(self, usetex):

    """
    def decorator(func):
        func._kwarg_doc = text
        return func
    return decorator


class Substitution:
    """
    A decorator that performs %-substitution on an object's docstring.

    This decorator should be robust even if ``obj.__doc__`` is None (for
    example, if -OO was passed to the interpreter).

    Usage: construct a docstring.Substitution with a sequence or dictionary
    suitable for performing substitution; then decorate a suitable function
    with the constructed object, e.g.::

        sub_author_name = Substitution(author='Jason')

        @sub_author_name
        def some_function(x):
            "%(author)s wrote this function"

Review comment (suggestion):
I'm finding this a little hard to follow and wondering if it'd be clearer if this was streamlined to one use case - so like an example of a method that uses line2D kwargs and then a code example that applies this decorator using a line2d kwarg.

Code after:
import inspect

from . import _api


def kwarg_doc(text):
    """
    Decorator for defining the kwdoc documentation of artist properties.

    This decorator can be applied to artist property setter methods.
    The given text is stored in a privat attribute ``_kwarg_doc`` on
    the method.  It is used to overwrite auto-generated documentation
    in the *kwdoc list* for artists. The kwdoc list is used to document
    ``**kwargs`` when they are properties of an artist. See e.g. the
    ``**kwargs`` section in `.Axes.text`.

    The text should contain the supported types as well as the default value
    if applicable, e.g.:

        @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
        def set_usetex(self, usetex):

    See Also
    --------
    matplotlib.artist.kwdoc

    """
    def decorator(func):
        func._kwarg_doc = text
        return func
    return decorator


class Substitution:
    """
    A decorator that performs %-substitution on an object's docstring.

    This decorator should be robust even if ``obj.__doc__`` is None (for
    example, if -OO was passed to the interpreter).

    Usage: construct a docstring.Substitution with a sequence or dictionary
    suitable for performing substitution; then decorate a suitable function
    with the constructed object, e.g.::

        sub_author_name = Substitution(author='Jason')
Repository: matplotlib/matplotlib
File: lib/matplotlib/_docstring.pyi (Python)

Code before:
from typing import Any, Callable, TypeVar, overload


_T = TypeVar('_T')


def _kwarg_doc(text: str) -> Callable[[_T], _T]: ...


class Substitution:
    @overload
    def __init__(self, *args: str): ...
    @overload
    def __init__(self, **kwargs: str): ...
    def __call__(self, func: _T) -> _T: ...
    def update(self, *args, **kwargs): ...  # type: ignore[no-untyped-def]


class _ArtistKwdocLoader(dict[str, str]):
    def __missing__(self, key: str) -> str: ...


class _ArtistPropertiesSubstitution(Substitution):
    def __init__(self) -> None: ...
    def __call__(self, obj: _T) -> _T: ...


def copy(source: Any) -> Callable[[_T], _T]: ...


dedent_interpd: _ArtistPropertiesSubstitution
interpd: _ArtistPropertiesSubstitution

Review comment (suggestion):
```suggestion
def kwarg_doc(text: str) -> Callable[[_T], _T]: ...
```

Not sure why stubtest didn't flag this, when I think it _did_ flag it as missing previously...

Code after:
from typing import Any, Callable, TypeVar, overload


_T = TypeVar('_T')


def kwarg_doc(text: str) -> Callable[[_T], _T]: ...


class Substitution:
    @overload
    def __init__(self, *args: str): ...
    @overload
    def __init__(self, **kwargs: str): ...
    def __call__(self, func: _T) -> _T: ...
    def update(self, *args, **kwargs): ...  # type: ignore[no-untyped-def]


class _ArtistKwdocLoader(dict[str, str]):
    def __missing__(self, key: str) -> str: ...


class _ArtistPropertiesSubstitution(Substitution):
    def __init__(self) -> None: ...
    def __call__(self, obj: _T) -> _T: ...


def copy(source: Any) -> Callable[[_T], _T]: ...


dedent_interpd: _ArtistPropertiesSubstitution
interpd: _ArtistPropertiesSubstitution
Repository: matplotlib/matplotlib
File: lib/matplotlib/_docstring.py (Python)

Code before:
import inspect

from . import _api


def kwarg_doc(text):
    """
    Decorator for defining the documentation used when artist properties are
    passed through as keyword arguments.

    See e.g. the ``**kwargs`` section in `.Axes.text`.

    The given text is stored in a privat variable ``_kwarg_doc`` on the method.
    It is used for generating the kwdoc list for artists, which we
    auto-generate through docstring interpolation, e.g. via
    ``%(Line2D:kwdoc)s``.

    The text should contain the supported types as well as the default value
    if applicable, e.g.:

        @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
        def set_usetex(self, usetex):

    """
    def decorator(func):
        func._kwarg_doc = text
        return func
    return decorator


class Substitution:
    """
    A decorator that performs %-substitution on an object's docstring.

    This decorator should be robust even if ``obj.__doc__`` is None (for
    example, if -OO was passed to the interpreter).

    Usage: construct a docstring.Substitution with a sequence or dictionary

Review comment (suggestion):
```suggestion
    The given text is stored in a private attribute ``_kwarg_doc`` on the method.
```

Code after:
import inspect

from . import _api


def kwarg_doc(text):
    """
    Decorator for defining the kwdoc documentation of artist properties.

    This decorator can be applied to artist property setter methods.
    The given text is stored in a privat attribute ``_kwarg_doc`` on
    the method.  It is used to overwrite auto-generated documentation
    in the *kwdoc list* for artists. The kwdoc list is used to document
    ``**kwargs`` when they are properties of an artist. See e.g. the
    ``**kwargs`` section in `.Axes.text`.

    The text should contain the supported types as well as the default value
    if applicable, e.g.:

        @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
        def set_usetex(self, usetex):

    See Also
    --------
    matplotlib.artist.kwdoc

    """
    def decorator(func):
        func._kwarg_doc = text
        return func
    return decorator


class Substitution:
    """
    A decorator that performs %-substitution on an object's docstring.

    This decorator should be robust even if ``obj.__doc__`` is None (for
Repository: matplotlib/matplotlib
File: lib/matplotlib/gridspec.py (Python)

Code before:
        if ((left if left is not None else self.left)
                >= (right if right is not None else self.right)):
            raise ValueError('left cannot be >= right')
        if ((bottom if bottom is not None else self.bottom)
                >= (top if top is not None else self.top)):
            raise ValueError('bottom cannot be >= top')

        attributes = {'left': left, 'right': right, 'bottom': bottom, 'top': top,
                          'hspace': hspace, 'wspace': wspace}
        for key, value in attributes.items():
            if value is not None:
                setattr(self, key, value)

    def reset(self):
        """Restore the positioning parameters to the default values"""
        for key in self.get_subplot_params().keys():
            setattr(self, key, mpl.rcParams[f'figure.subplot.{key}'])

    def get_subplot_params(self) -> dict[str, float]:
        """
        Returns
        -------
        subplot_params : dictionary
            A dictionary with the subplot parameters
        """
        return self.__dict__.copy()


Review comment (suggestion):
```suggestion
    def to_dict(self):
        """Return the subplot parameters as a dict."""
        return self.__dict__.copy()
```


Code after:
        """
        Update the dimensions of the passed parameters. *None* means unchanged.
        """
        if ((left if left is not None else self.left)
                >= (right if right is not None else self.right)):
            raise ValueError('left cannot be >= right')
        if ((bottom if bottom is not None else self.bottom)
                >= (top if top is not None else self.top)):
            raise ValueError('bottom cannot be >= top')
        if left is not None:
            self.left = left
        if right is not None:
            self.right = right
        if bottom is not None:
            self.bottom = bottom
        if top is not None:
            self.top = top
        if wspace is not None:
            self.wspace = wspace
        if hspace is not None:
            self.hspace = hspace

    def reset(self):
        """Restore the subplot positioning parameters to the default rcParams values"""
        for key in self.to_dict():
            setattr(self, key, mpl.rcParams[f'figure.subplot.{key}'])

    def to_dict(self):
        """Return a copy of the subplot parameters as a dict."""
        return self.__dict__.copy()
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_gridspec.py (Python)

Code before:
        gs.update(lleft=.1)


def test_width_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3])


def test_height_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])


def test_SubplotParams():
    s = gridspec.SubplotParams(.1, .1, .9, .9)
    assert s.left == 0.1

    with pytest.raises(ValueError):
        s.update(left=s.right + .01)

    with pytest.raises(ValueError):
        s.update(bottom=s.top + .01)

    with pytest.raises(ValueError):
        s = gridspec.SubplotParams(.1, .1, .09, .9)

    s.reset()
    assert s.left == matplotlib.rcParams['figure.subplot.left']

def test_repr():
    ss = gridspec.GridSpec(3, 3)[2, 1:3]
    assert repr(ss) == "GridSpec(3, 3)[2:3, 1:3]"

    ss = gridspec.GridSpec(2, 2,
                           height_ratios=(3, 1),
                           width_ratios=(1, 3))
    assert repr(ss) == \
        "GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(1, 3))"


def test_subplotspec_args():
    fig, axs = plt.subplots(1, 2)
    # should work:

Review comment (suggestion):
```suggestion
    with pytest.raises(ValueError, match='left cannot be >= right'):
```


Code after:
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3])


def test_height_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])


def test_SubplotParams():
    s = gridspec.SubplotParams(.1, .1, .9, .9)
    assert s.left == 0.1

    s.reset()
    assert s.left == matplotlib.rcParams['figure.subplot.left']

    with pytest.raises(ValueError, match='left cannot be >= right'):
        s.update(left=s.right + .01)

    with pytest.raises(ValueError, match='bottom cannot be >= top'):
        s.update(bottom=s.top + .01)

    with pytest.raises(ValueError, match='left cannot be >= right'):
        gridspec.SubplotParams(.1, .1, .09, .9)


def test_repr():
    ss = gridspec.GridSpec(3, 3)[2, 1:3]
    assert repr(ss) == "GridSpec(3, 3)[2:3, 1:3]"

    ss = gridspec.GridSpec(2, 2,
                           height_ratios=(3, 1),
                           width_ratios=(1, 3))
    assert repr(ss) == \
        "GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(1, 3))"


def test_subplotspec_args():
    fig, axs = plt.subplots(1, 2)
    # should work:
    gs = gridspec.GridSpecFromSubplotSpec(2, 1,
                                          subplot_spec=axs[0].get_subplotspec())
    assert gs.get_topmost_subplotspec() == axs[0].get_subplotspec()
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_gridspec.py (Python)

Code before:
import matplotlib
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import pytest


def test_equal():
    gs = gridspec.GridSpec(2, 1)
    assert gs[0, 0] == gs[0, 0]
    assert gs[:, 0] == gs[:, 0]


def test_update():
    gs = gridspec.GridSpec(2, 1)

    gs.update(left=.1)
    assert gs.left == .1

    with pytest.raises(AttributeError):
        gs.update(lleft=.1)


def test_width_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3])


def test_height_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])


def test_SubplotParams():
    s = gridspec.SubplotParams(.1, .1, .9, .9)
    assert s.left == 0.1

    s.reset()

Review comment (suggestion):
```suggestion
```
Let's not check this. This is basically an invalid parameter name, and we don't check functions for invalid parameter names. It's slightly different in that the parameters are not explicit, but instead of being tempted to add tests because of that, let's rather make the parameters explicit (see #29956).

Code after:
import matplotlib
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import pytest


def test_equal():
    gs = gridspec.GridSpec(2, 1)
    assert gs[0, 0] == gs[0, 0]
    assert gs[:, 0] == gs[:, 0]


def test_update():
    gs = gridspec.GridSpec(2, 1)

    gs.update(left=.1)
    assert gs.left == .1


def test_width_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3])


def test_height_ratios():
    """
    Addresses issue #5835.
    See at https://github.com/matplotlib/matplotlib/issues/5835.
    """
    with pytest.raises(ValueError):
        gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])


def test_SubplotParams():
    s = gridspec.SubplotParams(.1, .1, .9, .9)
    assert s.left == 0.1

    s.reset()
    assert s.left == matplotlib.rcParams['figure.subplot.left']

    with pytest.raises(ValueError, match='left cannot be >= right'):
Repository: matplotlib/matplotlib
File: lib/matplotlib/gridspec.py (Python)

Code before:
        if ((left if left is not None else self.left)
                >= (right if right is not None else self.right)):
            raise ValueError('left cannot be >= right')
        if ((bottom if bottom is not None else self.bottom)
                >= (top if top is not None else self.top)):
            raise ValueError('bottom cannot be >= top')
        if left is not None:
            self.left = left
        if right is not None:
            self.right = right
        if bottom is not None:
            self.bottom = bottom
        if top is not None:
            self.top = top
        if wspace is not None:
            self.wspace = wspace
        if hspace is not None:
            self.hspace = hspace

    def reset(self):
        """Restore the positioning parameters to the default values"""
        for key in self.to_dict():
            setattr(self, key, mpl.rcParams[f'figure.subplot.{key}'])

    def to_dict(self):
        """Return the subplot parameters as a dict."""
        return self.__dict__.copy()


Review comment (suggestion):
```suggestion
        """Return a copy of the subplot parameters as a dict."""
```

Code after:
        """
        for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
            setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
        self.update(left, bottom, right, top, wspace, hspace)

    def update(self, left=None, bottom=None, right=None, top=None,
               wspace=None, hspace=None):
        """
        Update the dimensions of the passed parameters. *None* means unchanged.
        """
        if ((left if left is not None else self.left)
                >= (right if right is not None else self.right)):
            raise ValueError('left cannot be >= right')
        if ((bottom if bottom is not None else self.bottom)
                >= (top if top is not None else self.top)):
            raise ValueError('bottom cannot be >= top')
        if left is not None:
            self.left = left
        if right is not None:
            self.right = right
        if bottom is not None:
            self.bottom = bottom
        if top is not None:
            self.top = top
        if wspace is not None:
            self.wspace = wspace
        if hspace is not None:
            self.hspace = hspace

    def reset(self):
        """Restore the subplot positioning parameters to the default rcParams values"""
        for key in self.to_dict():
            setattr(self, key, mpl.rcParams[f'figure.subplot.{key}'])

    def to_dict(self):
        """Return a copy of the subplot parameters as a dict."""
        return self.__dict__.copy()
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_sphinxext.py (Python)

Code before:
"""Tests for tinypages build using sphinx extensions."""

import filecmp
import os
from pathlib import Path
import shutil
import sys

from matplotlib.testing import subprocess_run_for_testing
import pytest


pytest.importorskip('sphinx', minversion='4.1.3')


tinypages = Path(__file__).parent / 'data/tinypages'


def _ignore_build_artifacts(dir, files):
    """
    Ignore function for shutil.copytree to exclude build artifacts.

    This prevents stale build artifacts from the source tinypages directory
    from being copied to test directories, which could cause inconsistent
    test results due to cached or outdated files.
    """
    return {'_build', 'doctrees', 'plot_directive'} & set(files)


def build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None):
    # Build the pages with warnings turned into errors
    extra_args = [] if extra_args is None else extra_args
    cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',
           '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args]
    # On CI, gcov emits warnings (due to agg headers being included with the
    # same name in multiple extension modules -- but we don't care about their
    # coverage anyways); hide them using GCOV_ERROR_FILE.
    proc = subprocess_run_for_testing(
        cmd, capture_output=True, text=True,
        env={**os.environ, "MPLBACKEND": "", "GCOV_ERROR_FILE": os.devnull}
    )
    out = proc.stdout
    err = proc.stderr


Review comment (suggestion):
From the docs, you can use `shutil.ignore_patterns` to generate this function directly.

Code after:
"""Tests for tinypages build using sphinx extensions."""

import filecmp
import os
from pathlib import Path
import shutil
import sys

from matplotlib.testing import subprocess_run_for_testing
import pytest


pytest.importorskip('sphinx', minversion='4.1.3')


tinypages = Path(__file__).parent / 'data/tinypages'


def build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None):
    # Build the pages with warnings turned into errors
    extra_args = [] if extra_args is None else extra_args
    cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',
           '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args]
    # On CI, gcov emits warnings (due to agg headers being included with the
    # same name in multiple extension modules -- but we don't care about their
    # coverage anyways); hide them using GCOV_ERROR_FILE.
    proc = subprocess_run_for_testing(
        cmd, capture_output=True, text=True,
        env={**os.environ, "MPLBACKEND": "", "GCOV_ERROR_FILE": os.devnull}
    )
    out = proc.stdout
    err = proc.stderr

    assert proc.returncode == 0, \
        f"sphinx build failed with stdout:\n{out}\nstderr:\n{err}\n"
    if err:
        pytest.fail(f"sphinx build emitted the following warnings:\n{err}")

    assert html_dir.is_dir()


def test_tinypages(tmp_path):
    shutil.copytree(tinypages, tmp_path, dirs_exist_ok=True,
                    ignore=shutil.ignore_patterns('_build', 'doctrees',
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_patheffects.py (Python)

Code before:
def test_patheffects_overridden_methods_open_close_group():
    class CustomRenderer(RendererBase):
        def __init__(self):
            super().__init__()

        def open_group(self, s, gid=None):
            return "open_group overridden"

        def close_group(self, s):
            return "close_group overridden"

    renderer = PathEffectRenderer([path_effects.Normal()], CustomRenderer())

    assert renderer.open_group('s') == "open_group overridden"
    assert renderer.close_group('s') == "close_group overridden"


@check_figures_equal()
def test_simpleLineShadow_plot(fig_test, fig_ref):
    # Create the plots
    ax_ref = fig_ref.add_subplot()
    ax_test = fig_test.add_subplot()

    # Generate Gaussian distribution data
    x = np.linspace(-5, 5, 500)
    y = np.exp(-x**2)

    # Plot the Gaussian line with the SimpleLineShadow path effect
    line, = ax_test.plot(x, y, linewidth=5)
    line.set_path_effects([path_effects.SimpleLineShadow(
                            offset=(0, 0), shadow_color='blue', rho=0.5)])

    # Plot the Gaussian line simply
    ax_ref.plot(x, y, linewidth=5, color='blue', alpha=0.3)


Review comment (suggestion):
Don't think these comments are necessary.
```suggestion
    ax_ref = fig_ref.add_subplot()
    ax_test = fig_test.add_subplot()

    x = np.linspace(-5, 5, 500)
    y = np.exp(-x**2)
```

Code after:

def test_patheffects_overridden_methods_open_close_group():
    class CustomRenderer(RendererBase):
        def __init__(self):
            super().__init__()

        def open_group(self, s, gid=None):
            return "open_group overridden"

        def close_group(self, s):
            return "close_group overridden"

    renderer = PathEffectRenderer([path_effects.Normal()], CustomRenderer())

    assert renderer.open_group('s') == "open_group overridden"
    assert renderer.close_group('s') == "close_group overridden"


@check_figures_equal()
def test_simple_line_shadow(fig_test, fig_ref):
    ax_ref = fig_ref.add_subplot()
    ax_test = fig_test.add_subplot()

    x = np.linspace(-5, 5, 500)
    y = np.exp(-x**2)

    line, = ax_test.plot(
        x, y, linewidth=5,
        path_effects=[
            path_effects.SimpleLineShadow(offset=(0, 0), shadow_color='blue')])

    ax_ref.plot(x, y, linewidth=5, color='blue', alpha=0.3)