The following issues were found

pandas/io/pickle.py
10 issues
Module 'pickle' has no 'HIGHEST_PROTOCOL' member
Error

Line: 24 Column: 21

                  obj: Any,
    filepath_or_buffer: FilePathOrBuffer,
    compression: CompressionOptions = "infer",
    protocol: int = pickle.HIGHEST_PROTOCOL,
    storage_options: StorageOptions = None,
):
    """
    Pickle (serialize) object to file.


            

Reported by Pylint.

Module 'pickle' has no 'HIGHEST_PROTOCOL' member
Error

Line: 92 Column: 20

                  >>> os.remove("./dummy.pkl")
    """
    if protocol < 0:
        protocol = pickle.HIGHEST_PROTOCOL

    with get_handle(
        filepath_or_buffer,
        "wb",
        compression=compression,

            

Reported by Pylint.

Module 'pickle' has no 'dumps' member
Error

Line: 109 Column: 17

                          handles.handle.write(
                # error: Argument 1 to "write" of "TextIOBase" has incompatible type
                # "bytes"; expected "str"
                pickle.dumps(obj, protocol=protocol)  # type: ignore[arg-type]
            )
        else:
            # letting pickle write directly to the buffer is more memory-efficient
            pickle.dump(
                # error: Argument 2 to "dump" has incompatible type "Union[IO[Any],

            

Reported by Pylint.

Module 'pickle' has no 'dump' member
Error

Line: 113 Column: 13

                          )
        else:
            # letting pickle write directly to the buffer is more memory-efficient
            pickle.dump(
                # error: Argument 2 to "dump" has incompatible type "Union[IO[Any],
                # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]"; expected
                # "IO[bytes]"
                obj,
                handles.handle,  # type: ignore[arg-type]

            

Reported by Pylint.

Module 'pickle' has no 'load' member
Error

Line: 217 Column: 28

                                  # error: Argument 1 to "load" has incompatible type "Union[IO[Any],
                    # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]";
                    # expected "IO[bytes]"
                    return pickle.load(handles.handle)  # type: ignore[arg-type]
            except excs_to_catch:
                # e.g.
                #  "No module named 'pandas.core.sparse.series'"
                #  "Can't get attribute '__nat_unpickle' on <module 'pandas._libs.tslib"
                return pc.load(handles.handle, encoding=None)

            

Reported by Pylint.

Module import itself
Error

Line: 2 Column: 1

              """ pickle compat """
import pickle
from typing import Any
import warnings

from pandas._typing import (
    CompressionOptions,
    FilePathOrBuffer,
    StorageOptions,

            

Reported by Pylint.

Access to a protected member _shared_docs of a client class
Error

Line: 19 Column: 22

              from pandas.io.common import get_handle


@doc(storage_options=generic._shared_docs["storage_options"])
def to_pickle(
    obj: Any,
    filepath_or_buffer: FilePathOrBuffer,
    compression: CompressionOptions = "infer",
    protocol: int = pickle.HIGHEST_PROTOCOL,

            

Reported by Pylint.

Access to a protected member _shared_docs of a client class
Error

Line: 123 Column: 22

                          )


@doc(storage_options=generic._shared_docs["storage_options"])
def read_pickle(
    filepath_or_buffer: FilePathOrBuffer,
    compression: CompressionOptions = "infer",
    storage_options: StorageOptions = None,
):

            

Reported by Pylint.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 217
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                                  # error: Argument 1 to "load" has incompatible type "Union[IO[Any],
                    # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]";
                    # expected "IO[bytes]"
                    return pickle.load(handles.handle)  # type: ignore[arg-type]
            except excs_to_catch:
                # e.g.
                #  "No module named 'pandas.core.sparse.series'"
                #  "Can't get attribute '__nat_unpickle' on <module 'pandas._libs.tslib"
                return pc.load(handles.handle, encoding=None)

            

Reported by Bandit.

Consider possible security implications associated with pickle module.
Security blacklist

Line: 2
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle

              """ pickle compat """
import pickle
from typing import Any
import warnings

from pandas._typing import (
    CompressionOptions,
    FilePathOrBuffer,
    StorageOptions,

            

Reported by Bandit.

pandas/tests/arrays/boolean/test_ops.py
10 issues
bad operand type for unary ~: PeriodArray
Error

Line: 9 Column: 41

                  def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

        expected = pd.Series(expected, index=["a", "b", "c"], name="name")
        result = ~pd.Series(a, index=["a", "b", "c"], name="name")
        tm.assert_series_equal(result, expected)


            

Reported by Pylint.

bad operand type for unary ~: ArrowStringArray
Error

Line: 9 Column: 41

                  def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

        expected = pd.Series(expected, index=["a", "b", "c"], name="name")
        result = ~pd.Series(a, index=["a", "b", "c"], name="name")
        tm.assert_series_equal(result, expected)


            

Reported by Pylint.

bad operand type for unary ~: IntervalArray
Error

Line: 9 Column: 41

                  def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

        expected = pd.Series(expected, index=["a", "b", "c"], name="name")
        result = ~pd.Series(a, index=["a", "b", "c"], name="name")
        tm.assert_series_equal(result, expected)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pandas as pd
import pandas._testing as tm


class TestUnaryOps:
    def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 5 Column: 1

              import pandas._testing as tm


class TestUnaryOps:
    def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)


            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              import pandas._testing as tm


class TestUnaryOps:
    def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 6 Column: 5

              

class TestUnaryOps:
    def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

        expected = pd.Series(expected, index=["a", "b", "c"], name="name")

            

Reported by Pylint.

Method could be a function
Error

Line: 6 Column: 5

              

class TestUnaryOps:
    def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

        expected = pd.Series(expected, index=["a", "b", "c"], name="name")

            

Reported by Pylint.

Variable name "a" doesn't conform to snake_case naming style
Error

Line: 7 Column: 9

              
class TestUnaryOps:
    def test_invert(self):
        a = pd.array([True, False, None], dtype="boolean")
        expected = pd.array([False, True, None], dtype="boolean")
        tm.assert_extension_array_equal(~a, expected)

        expected = pd.Series(expected, index=["a", "b", "c"], name="name")
        result = ~pd.Series(a, index=["a", "b", "c"], name="name")

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 15 Column: 9

                      result = ~pd.Series(a, index=["a", "b", "c"], name="name")
        tm.assert_series_equal(result, expected)

        df = pd.DataFrame({"A": a, "B": [True, False, False]}, index=["a", "b", "c"])
        result = ~df
        expected = pd.DataFrame(
            {"A": expected, "B": [False, True, True]}, index=["a", "b", "c"]
        )
        tm.assert_frame_equal(result, expected)

            

Reported by Pylint.

pandas/core/computation/align.py
10 issues
Access to a protected member _AXIS_ORDERS of a client class
Error

Line: 54 Column: 56

              def _zip_axes_from_type(
    typ: type[FrameOrSeries], new_axes: Sequence[Index]
) -> dict[str, Index]:
    return {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)}


def _any_pandas_objects(terms) -> bool:
    """
    Check a sequence of terms for instances of PandasObject.

            

Reported by Pylint.

Access to a protected member _constructor of a client class
Error

Line: 93 Column: 11

              
    # initial axes are the axes of the largest-axis'd term
    biggest = terms[ndims.idxmax()].value
    typ = biggest._constructor
    axes = biggest.axes
    naxes = len(axes)
    gt_than_one_axis = naxes > 1

    for value in (terms[i].value for i in term_index):

            

Reported by Pylint.

Argument name "f" doesn't conform to snake_case naming style
Error

Line: 64 Column: 1

                  return any(isinstance(term.value, PandasObject) for term in terms)


def _filter_special_cases(f):
    @wraps(f)
    def wrapper(terms):
        # single unary operand
        if len(terms) == 1:
            return _align_core_single_unary_op(terms[0])

            

Reported by Pylint.

Too many local variables (27/15)
Error

Line: 83 Column: 1

              

@_filter_special_cases
def _align_core(terms):
    term_index = [i for i, term in enumerate(terms) if hasattr(term.value, "axes")]
    term_dims = [terms[i].value.ndim for i in term_index]

    from pandas import Series


            

Reported by Pylint.

Import outside toplevel (pandas.Series)
Error

Line: 87 Column: 5

                  term_index = [i for i, term in enumerate(terms) if hasattr(term.value, "axes")]
    term_dims = [terms[i].value.ndim for i in term_index]

    from pandas import Series

    ndims = Series(dict(zip(term_index, term_dims)))

    # initial axes are the axes of the largest-axis'd term
    biggest = terms[ndims.idxmax()].value

            

Reported by Pylint.

Variable name "ax" doesn't conform to snake_case naming style
Error

Line: 104 Column: 17

              
        for axis, items in enumerate(value.axes):
            if is_series_and_gt_one_axis:
                ax, itm = naxes - 1, value.index
            else:
                ax, itm = axis, items

            if not axes[ax].is_(itm):
                axes[ax] = axes[ax].join(itm, how="outer")

            

Reported by Pylint.

Variable name "ax" doesn't conform to snake_case naming style
Error

Line: 106 Column: 17

                          if is_series_and_gt_one_axis:
                ax, itm = naxes - 1, value.index
            else:
                ax, itm = axis, items

            if not axes[ax].is_(itm):
                axes[ax] = axes[ax].join(itm, how="outer")

    for i, ndim in ndims.items():

            

Reported by Pylint.

Variable name "ti" doesn't conform to snake_case naming style
Error

Line: 113 Column: 13

              
    for i, ndim in ndims.items():
        for axis, items in zip(range(ndim), axes):
            ti = terms[i].value

            if hasattr(ti, "reindex"):
                transpose = isinstance(ti, ABCSeries) and naxes > 1
                reindexer = axes[naxes - 1] if transpose else items


            

Reported by Pylint.

Variable name "w" doesn't conform to snake_case naming style
Error

Line: 124 Column: 21

              
                ordm = np.log10(max(1, abs(reindexer_size - term_axis_size)))
                if ordm >= 1 and reindexer_size >= 10000:
                    w = (
                        f"Alignment difference on axis {axis} is larger "
                        f"than an order of magnitude on term {repr(terms[i].name)}, "
                        f"by more than {ordm:.4g}; performance may suffer"
                    )
                    warnings.warn(w, category=PerformanceWarning, stacklevel=6)

            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 131 Column: 17

                                  )
                    warnings.warn(w, category=PerformanceWarning, stacklevel=6)

                f = partial(ti.reindex, reindexer, axis=axis, copy=False)

                terms[i].update(f())

        terms[i].update(terms[i].value.values)


            

Reported by Pylint.

pandas/tests/indexes/datetimes/methods/test_snap.py
10 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

from pandas import (
    DatetimeIndex,
    date_range,
)
import pandas._testing as tm



            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

from pandas import (
    DatetimeIndex,
    date_range,
)
import pandas._testing as tm



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 1

              @pytest.mark.filterwarnings("ignore::DeprecationWarning")
@pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"])
@pytest.mark.parametrize("name", [None, "my_dti"])
def test_dti_snap(name, tz):
    dti = DatetimeIndex(
        [
            "1/1/2002",
            "1/2/2002",
            "1/3/2002",

            

Reported by Pylint.

Argument name "tz" doesn't conform to snake_case naming style
Error

Line: 13 Column: 1

              @pytest.mark.filterwarnings("ignore::DeprecationWarning")
@pytest.mark.parametrize("tz", [None, "Asia/Shanghai", "Europe/Berlin"])
@pytest.mark.parametrize("name", [None, "my_dti"])
def test_dti_snap(name, tz):
    dti = DatetimeIndex(
        [
            "1/1/2002",
            "1/2/2002",
            "1/3/2002",

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 33
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  expected = date_range("12/31/2001", "1/7/2002", name=name, tz=tz, freq="w-mon")
    expected = expected.repeat([3, 4])
    tm.assert_index_equal(result, expected)
    assert result.tz == expected.tz
    assert result.freq is None
    assert expected.freq is None

    result = dti.snap(freq="B")


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 34
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  expected = expected.repeat([3, 4])
    tm.assert_index_equal(result, expected)
    assert result.tz == expected.tz
    assert result.freq is None
    assert expected.freq is None

    result = dti.snap(freq="B")

    expected = date_range("1/1/2002", "1/7/2002", name=name, tz=tz, freq="b")

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 35
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  tm.assert_index_equal(result, expected)
    assert result.tz == expected.tz
    assert result.freq is None
    assert expected.freq is None

    result = dti.snap(freq="B")

    expected = date_range("1/1/2002", "1/7/2002", name=name, tz=tz, freq="b")
    expected = expected.repeat([1, 1, 1, 2, 2])

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 42
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  expected = date_range("1/1/2002", "1/7/2002", name=name, tz=tz, freq="b")
    expected = expected.repeat([1, 1, 1, 2, 2])
    tm.assert_index_equal(result, expected)
    assert result.tz == expected.tz
    assert result.freq is None
    assert expected.freq is None

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 43
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  expected = expected.repeat([1, 1, 1, 2, 2])
    tm.assert_index_equal(result, expected)
    assert result.tz == expected.tz
    assert result.freq is None
    assert expected.freq is None

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 44
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  tm.assert_index_equal(result, expected)
    assert result.tz == expected.tz
    assert result.freq is None
    assert expected.freq is None

            

Reported by Bandit.

pandas/core/tools/times.py
10 issues
No name 'lib' in module 'pandas._libs'
Error

Line: 10 Column: 1

              
import numpy as np

from pandas._libs.lib import is_list_like

from pandas.core.dtypes.generic import (
    ABCIndex,
    ABCSeries,
)

            

Reported by Pylint.

Unable to import 'pandas._libs.lib'
Error

Line: 10 Column: 1

              
import numpy as np

from pandas._libs.lib import is_list_like

from pandas.core.dtypes.generic import (
    ABCIndex,
    ABCSeries,
)

            

Reported by Pylint.

Redefining built-in 'format'
Error

Line: 19 Column: 18

              from pandas.core.dtypes.missing import notna


def to_time(arg, format=None, infer_time_format=False, errors="raise"):
    """
    Parse time strings to time objects using fixed strptime formats ("%H:%M",
    "%H%M", "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p",
    "%I%M%S%p")


            

Reported by Pylint.

Redefining built-in 'format'
Error

Line: 47 Column: 32

                  datetime.time
    """

    def _convert_listlike(arg, format):

        if isinstance(arg, (list, tuple)):
            arg = np.array(arg, dtype="O")

        elif getattr(arg, "ndim", 1) > 1:

            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 111 Column: 36

                  elif isinstance(arg, time):
        return arg
    elif isinstance(arg, ABCSeries):
        values = _convert_listlike(arg._values, format)
        return arg._constructor(values, index=arg.index, name=arg.name)
    elif isinstance(arg, ABCIndex):
        return _convert_listlike(arg, format)
    elif is_list_like(arg):
        return _convert_listlike(arg, format)

            

Reported by Pylint.

Access to a protected member _constructor of a client class
Error

Line: 112 Column: 16

                      return arg
    elif isinstance(arg, ABCSeries):
        values = _convert_listlike(arg._values, format)
        return arg._constructor(values, index=arg.index, name=arg.name)
    elif isinstance(arg, ABCIndex):
        return _convert_listlike(arg, format)
    elif is_list_like(arg):
        return _convert_listlike(arg, format)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import annotations

from datetime import (
    datetime,
    time,
)

import numpy as np


            

Reported by Pylint.

Too many branches (18/12)
Error

Line: 47 Column: 5

                  datetime.time
    """

    def _convert_listlike(arg, format):

        if isinstance(arg, (list, tuple)):
            arg = np.array(arg, dtype="O")

        elif getattr(arg, "ndim", 1) > 1:

            

Reported by Pylint.

Unnecessary "elif" after "raise"
Error

Line: 68 Column: 21

                              try:
                    times.append(datetime.strptime(element, format).time())
                except (ValueError, TypeError) as err:
                    if errors == "raise":
                        msg = (
                            f"Cannot convert {element} to a time with given "
                            f"format {format}"
                        )
                        raise ValueError(msg) from err

            

Reported by Pylint.

Unnecessary "elif" after "return"
Error

Line: 106 Column: 5

              
        return times

    if arg is None:
        return arg
    elif isinstance(arg, time):
        return arg
    elif isinstance(arg, ABCSeries):
        values = _convert_listlike(arg._values, format)

            

Reported by Pylint.

pandas/tests/apply/test_frame_apply_relabeling.py
10 issues
Lambda may not be necessary
Error

Line: 60 Column: 18

                      cat=("B", max),
        dat=("C", "min"),
        f=("B", np.sum),
        kk=("B", lambda x: min(x)),
    )
    expected = pd.DataFrame(
        {
            "A": [1.0, 1.0, np.nan, np.nan, np.nan, np.nan],
            "B": [np.nan, np.nan, 4.0, np.nan, 10.0, 1.0],

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np

import pandas as pd
import pandas._testing as tm


def test_agg_relabel():
    # GH 26513
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 7 Column: 1

              import pandas._testing as tm


def test_agg_relabel():
    # GH 26513
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})

    # simplest case with one column, one func
    result = df.agg(foo=("B", "sum"))

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 9 Column: 5

              
def test_agg_relabel():
    # GH 26513
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})

    # simplest case with one column, one func
    result = df.agg(foo=("B", "sum"))
    expected = pd.DataFrame({"B": [10]}, index=pd.Index(["foo"]))
    tm.assert_frame_equal(result, expected)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 1

                  tm.assert_frame_equal(result, expected)


def test_agg_relabel_multi_columns_multi_methods():
    # GH 26513, test on multiple columns with multiple methods
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
    result = df.agg(
        foo=("A", "sum"),
        bar=("B", "mean"),

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 25 Column: 5

              
def test_agg_relabel_multi_columns_multi_methods():
    # GH 26513, test on multiple columns with multiple methods
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
    result = df.agg(
        foo=("A", "sum"),
        bar=("B", "mean"),
        cat=("A", "min"),
        dat=("B", "max"),

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 45 Column: 1

                  tm.assert_frame_equal(result, expected)


def test_agg_relabel_partial_functions():
    # GH 26513, test on partial, functools or more complex cases
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
    result = df.agg(foo=("A", np.mean), bar=("A", "mean"), cat=("A", min))
    expected = pd.DataFrame(
        {"A": [1.5, 1.5, 1.0]}, index=pd.Index(["foo", "bar", "cat"])

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 47 Column: 5

              
def test_agg_relabel_partial_functions():
    # GH 26513, test on partial, functools or more complex cases
    df = pd.DataFrame({"A": [1, 2, 1, 2], "B": [1, 2, 3, 4], "C": [3, 4, 5, 6]})
    result = df.agg(foo=("A", np.mean), bar=("A", "mean"), cat=("A", min))
    expected = pd.DataFrame(
        {"A": [1.5, 1.5, 1.0]}, index=pd.Index(["foo", "bar", "cat"])
    )
    tm.assert_frame_equal(result, expected)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 73 Column: 1

                  tm.assert_frame_equal(result, expected)


def test_agg_namedtuple():
    # GH 26513
    df = pd.DataFrame({"A": [0, 1], "B": [1, 2]})
    result = df.agg(
        foo=pd.NamedAgg("B", "sum"),
        bar=pd.NamedAgg("B", min),

            

Reported by Pylint.

Variable name "df" doesn't conform to snake_case naming style
Error

Line: 75 Column: 5

              
def test_agg_namedtuple():
    # GH 26513
    df = pd.DataFrame({"A": [0, 1], "B": [1, 2]})
    result = df.agg(
        foo=pd.NamedAgg("B", "sum"),
        bar=pd.NamedAgg("B", min),
        cat=pd.NamedAgg(column="B", aggfunc="count"),
        fft=pd.NamedAgg("B", aggfunc="max"),

            

Reported by Pylint.

pandas/io/excel/_pyxlsb.py
10 issues
Unable to import 'pyxlsb'
Error

Line: 36 Column: 9

              
    @property
    def _workbook_class(self):
        from pyxlsb import Workbook

        return Workbook

    def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
        from pyxlsb import open_workbook

            

Reported by Pylint.

Unable to import 'pyxlsb'
Error

Line: 41 Column: 9

                      return Workbook

    def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
        from pyxlsb import open_workbook

        # TODO: hack in buffer capability
        # This might need some modifications to the Pyxlsb library
        # Actual work for opening it is in xlsbpackage.py, line 20-ish


            

Reported by Pylint.

TODO: hack in buffer capability
Error

Line: 43 Column: 3

                  def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
        from pyxlsb import open_workbook

        # TODO: hack in buffer capability
        # This might need some modifications to the Pyxlsb library
        # Actual work for opening it is in xlsbpackage.py, line 20-ish

        return open_workbook(filepath_or_buffer)


            

Reported by Pylint.

TODO: there is no way to distinguish between floats and datetimes in pyxlsb
Error

Line: 64 Column: 3

                      return self.book.get_sheet(index + 1)

    def _convert_cell(self, cell, convert_float: bool) -> Scalar:
        # TODO: there is no way to distinguish between floats and datetimes in pyxlsb
        # This means that there is no way to read datetime types from an xlsb file yet
        if cell.v is None:
            return ""  # Prevents non-named columns from not showing up as Unnamed: i
        if isinstance(cell.v, float) and convert_float:
            val = int(cell.v)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import annotations

from pandas._typing import (
    FilePathOrBuffer,
    Scalar,
    StorageOptions,
)
from pandas.compat._optional import import_optional_dependency


            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              from pandas.io.excel._base import BaseExcelReader


class PyxlsbReader(BaseExcelReader):
    def __init__(
        self,
        filepath_or_buffer: FilePathOrBuffer,
        storage_options: StorageOptions = None,
    ):

            

Reported by Pylint.

Import outside toplevel (pyxlsb.Workbook)
Error

Line: 36 Column: 9

              
    @property
    def _workbook_class(self):
        from pyxlsb import Workbook

        return Workbook

    def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
        from pyxlsb import open_workbook

            

Reported by Pylint.

Import outside toplevel (pyxlsb.open_workbook)
Error

Line: 41 Column: 9

                      return Workbook

    def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
        from pyxlsb import open_workbook

        # TODO: hack in buffer capability
        # This might need some modifications to the Pyxlsb library
        # Actual work for opening it is in xlsbpackage.py, line 20-ish


            

Reported by Pylint.

Method could be a function
Error

Line: 63 Column: 5

                      # There's a fix for this in the source, but the pypi package doesn't have it
        return self.book.get_sheet(index + 1)

    def _convert_cell(self, cell, convert_float: bool) -> Scalar:
        # TODO: there is no way to distinguish between floats and datetimes in pyxlsb
        # This means that there is no way to read datetime types from an xlsb file yet
        if cell.v is None:
            return ""  # Prevents non-named columns from not showing up as Unnamed: i
        if isinstance(cell.v, float) and convert_float:

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 70 Column: 13

                          return ""  # Prevents non-named columns from not showing up as Unnamed: i
        if isinstance(cell.v, float) and convert_float:
            val = int(cell.v)
            if val == cell.v:
                return val
            else:
                return float(cell.v)

        return cell.v

            

Reported by Pylint.

pandas/io/formats/string.py
9 issues
Access to a protected member _get_formatted_index of a client class
Error

Line: 64 Column: 21

                      return bool(self.fmt.max_cols is None or self.fmt.max_cols > 0)

    def _insert_dot_separators(self, strcols: list[list[str]]) -> list[list[str]]:
        str_index = self.fmt._get_formatted_index(self.fmt.tr_frame)
        index_length = len(str_index)

        if self.fmt.is_truncated_horizontally:
            strcols = self._insert_dot_separator_horizontal(strcols, index_length)


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 15 Column: 1

              from pandas.io.formats.printing import pprint_thing


class StringFormatter:
    """Formatter for string representation of a dataframe."""

    def __init__(self, fmt: DataFrameFormatter, line_width: int | None = None):
        self.fmt = fmt
        self.adj = fmt.adj

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 5

                      self.frame = fmt.frame
        self.line_width = line_width

    def to_string(self) -> str:
        text = self._get_string_representation()
        if self.fmt.should_show_dimensions:
            text = "".join([text, self.fmt.dimensions_info])
        return text


            

Reported by Pylint.

Variable name "ix" doesn't conform to snake_case naming style
Error

Line: 90 Column: 13

                  ) -> list[list[str]]:
        n_header_rows = index_length - len(self.fmt.tr_frame)
        row_num = self.fmt.tr_row_num
        for ix, col in enumerate(strcols):
            cwidth = self.adj.len(col[row_num])

            if self.fmt.is_truncated_horizontally:
                is_dot_col = ix == self._adjusted_tr_col_num
            else:

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 129
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          for col in strcols
        ]

        assert lwidth is not None
        col_bins = _binify(col_widths, lwidth)
        nbins = len(col_bins)

        if self.fmt.is_truncated_vertically:
            assert self.fmt.max_rows_fitted is not None

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 134
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      nbins = len(col_bins)

        if self.fmt.is_truncated_vertically:
            assert self.fmt.max_rows_fitted is not None
            nrows = self.fmt.max_rows_fitted + 1
        else:
            nrows = len(self.frame)

        str_lst = []

            

Reported by Bandit.

Too many local variables (16/15)
Error

Line: 154 Column: 5

                          start = end
        return "\n\n".join(str_lst)

    def _fit_strcols_to_terminal_width(self, strcols: list[list[str]]) -> str:
        from pandas import Series

        lines = self.adj.adjoin(1, *strcols).split("\n")
        max_len = Series(lines).str.len().max()
        # plus truncate dot col

            

Reported by Pylint.

Import outside toplevel (pandas.Series)
Error

Line: 155 Column: 9

                      return "\n\n".join(str_lst)

    def _fit_strcols_to_terminal_width(self, strcols: list[list[str]]) -> str:
        from pandas import Series

        lines = self.adj.adjoin(1, *strcols).split("\n")
        max_len = Series(lines).str.len().max()
        # plus truncate dot col
        width, _ = get_terminal_size()

            

Reported by Pylint.

Variable name "w" doesn't conform to snake_case naming style
Error

Line: 195 Column: 12

                  bins = []
    curr_width = 0
    i_last_column = len(cols) - 1
    for i, w in enumerate(cols):
        w_adjoined = w + adjoin_width
        curr_width += w_adjoined
        if i_last_column == i:
            wrap = curr_width + 1 > line_width and i > 0
        else:

            

Reported by Pylint.

pandas/tests/extension/test_extension.py
9 issues
Unable to import 'pytest'
Error

Line: 5 Column: 1

              Tests for behavior if an author does *not* implement EA methods.
"""
import numpy as np
import pytest

from pandas.core.arrays import ExtensionArray


class MyEA(ExtensionArray):

            

Reported by Pylint.

Method '__setitem__' is abstract in class 'ExtensionArray' but is not overridden
Error

Line: 10 Column: 1

              from pandas.core.arrays import ExtensionArray


class MyEA(ExtensionArray):
    def __init__(self, values):
        self._values = values


@pytest.fixture

            

Reported by Pylint.

Redefining name 'data' from outer scope (line 16)
Error

Line: 22 Column: 27

              

class TestExtensionArray:
    def test_errors(self, data, all_arithmetic_operators):
        # invalid ops
        op_name = all_arithmetic_operators
        with pytest.raises(AttributeError):
            getattr(data, op_name)

            

Reported by Pylint.

Missing class docstring
Error

Line: 10 Column: 1

              from pandas.core.arrays import ExtensionArray


class MyEA(ExtensionArray):
    def __init__(self, values):
        self._values = values


@pytest.fixture

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 16 Column: 1

              

@pytest.fixture
def data():
    arr = np.arange(10)
    return MyEA(arr)


class TestExtensionArray:

            

Reported by Pylint.

Missing class docstring
Error

Line: 21 Column: 1

                  return MyEA(arr)


class TestExtensionArray:
    def test_errors(self, data, all_arithmetic_operators):
        # invalid ops
        op_name = all_arithmetic_operators
        with pytest.raises(AttributeError):
            getattr(data, op_name)

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 21 Column: 1

                  return MyEA(arr)


class TestExtensionArray:
    def test_errors(self, data, all_arithmetic_operators):
        # invalid ops
        op_name = all_arithmetic_operators
        with pytest.raises(AttributeError):
            getattr(data, op_name)

            

Reported by Pylint.

Method could be a function
Error

Line: 22 Column: 5

              

class TestExtensionArray:
    def test_errors(self, data, all_arithmetic_operators):
        # invalid ops
        op_name = all_arithmetic_operators
        with pytest.raises(AttributeError):
            getattr(data, op_name)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 5

              

class TestExtensionArray:
    def test_errors(self, data, all_arithmetic_operators):
        # invalid ops
        op_name = all_arithmetic_operators
        with pytest.raises(AttributeError):
            getattr(data, op_name)

            

Reported by Pylint.

pandas/tests/arrays/masked/test_function.py
9 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

from pandas.core.dtypes.common import is_integer_dtype

import pandas as pd
import pandas._testing as tm

arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]

            

Reported by Pylint.

Redefining name 'data' from outer scope (line 16)
Error

Line: 21 Column: 17

              

@pytest.fixture()
def numpy_dtype(data):
    # For integer dtype, the numpy conversion must be done to float
    if is_integer_dtype(data):
        numpy_dtype = float
    else:
        numpy_dtype = data.dtype.type

            

Reported by Pylint.

Redefining name 'numpy_dtype' from outer scope (line 21)
Error

Line: 24 Column: 9

              def numpy_dtype(data):
    # For integer dtype, the numpy conversion must be done to float
    if is_integer_dtype(data):
        numpy_dtype = float
    else:
        numpy_dtype = data.dtype.type
    return numpy_dtype



            

Reported by Pylint.

Redefining name 'data' from outer scope (line 16)
Error

Line: 30 Column: 16

                  return numpy_dtype


def test_round(data, numpy_dtype):
    # No arguments
    result = data.round()
    expected = pd.array(
        np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
    )

            

Reported by Pylint.

Redefining name 'numpy_dtype' from outer scope (line 21)
Error

Line: 30 Column: 22

                  return numpy_dtype


def test_round(data, numpy_dtype):
    # No arguments
    result = data.round()
    expected = pd.array(
        np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
    )

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import pytest

from pandas.core.dtypes.common import is_integer_dtype

import pandas as pd
import pandas._testing as tm

arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES]

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 16 Column: 1

              

@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
def data(request):
    return request.param


@pytest.fixture()
def numpy_dtype(data):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 1

              

@pytest.fixture()
def numpy_dtype(data):
    # For integer dtype, the numpy conversion must be done to float
    if is_integer_dtype(data):
        numpy_dtype = float
    else:
        numpy_dtype = data.dtype.type

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

                  return numpy_dtype


def test_round(data, numpy_dtype):
    # No arguments
    result = data.round()
    expected = pd.array(
        np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
    )

            

Reported by Pylint.