The following issues were found

pandas/tests/io/test_common.py
121 issues
Unable to import 'pytest'
Error

Line: 16 Column: 1

              from pathlib import Path
import tempfile

import pytest

from pandas.compat import is_platform_windows
import pandas.util._test_decorators as td

import pandas as pd

            

Reported by Pylint.

Unable to import 'pyarrow'
Error

Line: 164 Column: 9

                  # Test that pyarrow can handle a file opened with get_handle
    @td.skip_if_no("pyarrow", min_version="0.15.0")
    def test_get_handle_pyarrow_compat(self):
        from pyarrow import csv

        # Test latin1, ucs-2, and ucs-4 chars
        data = """a,b,c
1,2,3
©,®,®

            

Reported by Pylint.

Access to a protected member _expand_user of a client class
Error

Line: 64 Column: 25

              
    def test_expand_user(self):
        filename = "~/sometest"
        expanded_name = icom._expand_user(filename)

        assert expanded_name != filename
        assert os.path.isabs(expanded_name)
        assert os.path.expanduser(filename) == expanded_name


            

Reported by Pylint.

Access to a protected member _expand_user of a client class
Error

Line: 72 Column: 25

              
    def test_expand_user_normal_path(self):
        filename = "/somefolder/sometest"
        expanded_name = icom._expand_user(filename)

        assert expanded_name == filename
        assert os.path.expanduser(filename) == expanded_name

    def test_stringify_path_pathlib(self):

            

Reported by Pylint.

TODO(ArrayManager) IO HDF5
Error

Line: 360 Column: 3

                  @pytest.mark.filterwarnings(  # pytables np.object usage
        "ignore:`np.object` is a deprecated alias:DeprecationWarning"
    )
    @td.skip_array_manager_not_yet_implemented  # TODO(ArrayManager) IO HDF5
    def test_write_fspath_hdf5(self):
        # Same test as write_fspath_all, except HDF5 files aren't
        # necessarily byte-for-byte identical for a given dataframe, so we'll
        # have to read and compare equality
        pytest.importorskip("tables")

            

Reported by Pylint.

Redefining name 'mmap_file' from outer scope (line 383)
Error

Line: 388 Column: 41

              

class TestMMapWrapper:
    def test_constructor_bad_file(self, mmap_file):
        non_file = StringIO("I am not a file")
        non_file.fileno = lambda: -1

        # the error raised is different on Windows
        if is_platform_windows():

            

Reported by Pylint.

Access to a protected member _MMapWrapper of a client class
Error

Line: 401 Column: 13

                          err = mmap.error

        with pytest.raises(err, match=msg):
            icom._MMapWrapper(non_file)

        target = open(mmap_file)
        target.close()

        msg = "I/O operation on closed file"

            

Reported by Pylint.

Access to a protected member _MMapWrapper of a client class
Error

Line: 408 Column: 13

              
        msg = "I/O operation on closed file"
        with pytest.raises(ValueError, match=msg):
            icom._MMapWrapper(target)

    def test_get_attr(self, mmap_file):
        with open(mmap_file) as target:
            wrapper = icom._MMapWrapper(target)


            

Reported by Pylint.

Redefining name 'mmap_file' from outer scope (line 383)
Error

Line: 410 Column: 29

                      with pytest.raises(ValueError, match=msg):
            icom._MMapWrapper(target)

    def test_get_attr(self, mmap_file):
        with open(mmap_file) as target:
            wrapper = icom._MMapWrapper(target)

        attrs = dir(wrapper.mmap)
        attrs = [attr for attr in attrs if not attr.startswith("__")]

            

Reported by Pylint.

Access to a protected member _MMapWrapper of a client class
Error

Line: 412 Column: 23

              
    def test_get_attr(self, mmap_file):
        with open(mmap_file) as target:
            wrapper = icom._MMapWrapper(target)

        attrs = dir(wrapper.mmap)
        attrs = [attr for attr in attrs if not attr.startswith("__")]
        attrs.append("__next__")


            

Reported by Pylint.

pandas/tests/scalar/test_na_scalar.py
120 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import pickle

import numpy as np
import pytest

from pandas._libs.missing import NA

from pandas.core.dtypes.common import is_scalar


            

Reported by Pylint.

Unable to import 'pandas._libs.missing'
Error

Line: 6 Column: 1

              import numpy as np
import pytest

from pandas._libs.missing import NA

from pandas.core.dtypes.common import is_scalar

import pandas as pd
import pandas._testing as tm

            

Reported by Pylint.

No name 'missing' in module 'pandas._libs'
Error

Line: 6 Column: 1

              import numpy as np
import pytest

from pandas._libs.missing import NA

from pandas.core.dtypes.common import is_scalar

import pandas as pd
import pandas._testing as tm

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 43 Column: 9

                      bool(NA)

    with pytest.raises(TypeError, match=msg):
        not NA


def test_hashable():
    assert hash(NA) == hash(NA)
    d = {NA: "test"}

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 161 Column: 9

              
    msg = "unsupported operand type"
    with pytest.raises(TypeError, match=msg):
        NA & 5


def test_logical_or():

    assert NA | True is True

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 174 Column: 9

              
    msg = "unsupported operand type"
    with pytest.raises(TypeError, match=msg):
        NA | 5


def test_logical_xor():

    assert NA ^ True is NA

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 187 Column: 9

              
    msg = "unsupported operand type"
    with pytest.raises(TypeError, match=msg):
        NA ^ 5


def test_logical_not():
    assert ~NA is NA


            

Reported by Pylint.

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

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

              
def test_pickle_roundtrip():
    # https://github.com/pandas-dev/pandas/issues/31847
    result = pickle.loads(pickle.dumps(NA))
    assert result is NA


def test_pickle_roundtrip_pandas():
    result = tm.round_trip_pickle(NA)

            

Reported by Bandit.

Consider possible security implications associated with pickle module.
Security blacklist

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

              import pickle

import numpy as np
import pytest

from pandas._libs.missing import NA

from pandas.core.dtypes.common import is_scalar


            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              import pickle

import numpy as np
import pytest

from pandas._libs.missing import NA

from pandas.core.dtypes.common import is_scalar


            

Reported by Pylint.

pandas/_testing/asserters.py
119 issues
Unable to import 'pandas._libs.lib'
Error

Line: 8 Column: 1

              
import numpy as np

from pandas._libs.lib import (
    NoDefault,
    no_default,
)
from pandas._libs.missing import is_matching_na
import pandas._libs.testing as _testing

            

Reported by Pylint.

No name 'lib' in module 'pandas._libs'
Error

Line: 8 Column: 1

              
import numpy as np

from pandas._libs.lib import (
    NoDefault,
    no_default,
)
from pandas._libs.missing import is_matching_na
import pandas._libs.testing as _testing

            

Reported by Pylint.

No name 'missing' in module 'pandas._libs'
Error

Line: 12 Column: 1

                  NoDefault,
    no_default,
)
from pandas._libs.missing import is_matching_na
import pandas._libs.testing as _testing

from pandas.core.dtypes.common import (
    is_bool,
    is_categorical_dtype,

            

Reported by Pylint.

Unable to import 'pandas._libs.missing'
Error

Line: 12 Column: 1

                  NoDefault,
    no_default,
)
from pandas._libs.missing import is_matching_na
import pandas._libs.testing as _testing

from pandas.core.dtypes.common import (
    is_bool,
    is_categorical_dtype,

            

Reported by Pylint.

No name 'testing' in module 'pandas._libs'
Error

Line: 13 Column: 1

                  no_default,
)
from pandas._libs.missing import is_matching_na
import pandas._libs.testing as _testing

from pandas.core.dtypes.common import (
    is_bool,
    is_categorical_dtype,
    is_extension_array_dtype,

            

Reported by Pylint.

Unable to import 'pandas._libs.testing'
Error

Line: 13 Column: 1

                  no_default,
)
from pandas._libs.missing import is_matching_na
import pandas._libs.testing as _testing

from pandas.core.dtypes.common import (
    is_bool,
    is_categorical_dtype,
    is_extension_array_dtype,

            

Reported by Pylint.

Module 'pandas._libs' has no 'sparse' member
Error

Line: 1380 Column: 38

                  assert_numpy_array_equal(left.sp_values, right.sp_values)

    # SparseIndex comparison
    assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
    assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)

    left_index = left.sp_index
    right_index = right.sp_index


            

Reported by Pylint.

Module 'pandas._libs' has no 'sparse' member
Error

Line: 1381 Column: 39

              
    # SparseIndex comparison
    assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex)
    assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex)

    left_index = left.sp_index
    right_index = right.sp_index

    if not left_index.equals(right_index):

            

Reported by Pylint.

Unused variable '__tracebackhide__'
Error

Line: 311 Column: 5

                  >>> b = pd.Index([1, 2, 3])
    >>> tm.assert_index_equal(a, b)
    """
    __tracebackhide__ = True

    def _check_types(left, right, obj="Index") -> None:
        if not exact:
            return


            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 333 Column: 26

                      # accept level number only
        unique = index.levels[level]
        level_codes = index.codes[level]
        filled = take_nd(unique._values, level_codes, fill_value=unique._na_value)
        return unique._shallow_copy(filled, name=index.names[level])

    if check_less_precise is not no_default:
        warnings.warn(
            "The 'check_less_precise' keyword in testing.assert_*_equal "

            

Reported by Pylint.

pandas/core/internals/array_manager.py
119 issues
No name 'lib' in module 'pandas._libs'
Error

Line: 16 Column: 1

              
import numpy as np

from pandas._libs import (
    NaT,
    lib,
)
from pandas._typing import (
    ArrayLike,

            

Reported by Pylint.

Instance of 'BaseArrayManager' has no 'axes' member; maybe '_axes'?
Error

Line: 136 Column: 21

                  def make_empty(self: T, axes=None) -> T:
        """Return an empty ArrayManager with the items axis of len 0 (no columns)"""
        if axes is None:
            axes = [self.axes[1:], Index([])]

        arrays: list[np.ndarray | ExtensionArray] = []
        return type(self)(arrays, axes)

    @property

            

Reported by Pylint.

Instance of 'ArrayManager' has no 'axes' member; maybe '_axes'?
Error

Line: 1051 Column: 40

                          if not ignore_failures:
                raise
            result_arrays = []
            new_axes = [self._axes[0], self.axes[1].take([])]
        else:
            result_arrays = [result[:, i] for i in range(len(self._axes[1]))]
            new_axes = self._axes

        return type(self)(result_arrays, new_axes)

            

Reported by Pylint.

TODO setstate getstate
Error

Line: 173 Column: 3

                  def get_dtypes(self):
        return np.array([arr.dtype for arr in self.arrays], dtype="object")

    # TODO setstate getstate

    def __repr__(self) -> str:
        output = type(self).__name__
        output += f"\nIndex: {self._axes[0]}"
        if self.ndim == 2:

            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 231 Column: 41

                                      if obj.ndim == 1:
                            kwargs[k] = obj.iloc[i]
                        else:
                            kwargs[k] = obj.iloc[:, i]._values
                    else:
                        # otherwise we have an array-like
                        kwargs[k] = obj[i]

            try:

            

Reported by Pylint.

# TODO not all EA operations return new EAs (eg astype)
Error

Line: 246 Column: 9

                                  raise
                continue
            # if not isinstance(applied, ExtensionArray):
            #     # TODO not all EA operations return new EAs (eg astype)
            #     applied = array(applied)
            result_arrays.append(applied)
            result_indices.append(i)

        new_axes: list[Index]

            

Reported by Pylint.

TODO copy?
Error

Line: 253 Column: 3

              
        new_axes: list[Index]
        if ignore_failures:
            # TODO copy?
            new_axes = [self._axes[0], self._axes[1][result_indices]]
        else:
            new_axes = self._axes

        # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]";

            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 281 Column: 45

                                      #  obj.axes[-1].equals(self.items)
                        if obj.ndim == 1:
                            if self.ndim == 2:
                                kwargs[k] = obj.iloc[slice(i, i + 1)]._values
                            else:
                                kwargs[k] = obj.iloc[:]._values
                        else:
                            kwargs[k] = obj.iloc[:, [i]]._values
                    else:

            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 283 Column: 45

                                          if self.ndim == 2:
                                kwargs[k] = obj.iloc[slice(i, i + 1)]._values
                            else:
                                kwargs[k] = obj.iloc[:]._values
                        else:
                            kwargs[k] = obj.iloc[:, [i]]._values
                    else:
                        # otherwise we have an ndarray
                        if obj.ndim == 2:

            

Reported by Pylint.

Access to a protected member _values of a client class
Error

Line: 285 Column: 41

                                          else:
                                kwargs[k] = obj.iloc[:]._values
                        else:
                            kwargs[k] = obj.iloc[:, [i]]._values
                    else:
                        # otherwise we have an ndarray
                        if obj.ndim == 2:
                            kwargs[k] = obj[[i]]


            

Reported by Pylint.

pandas/tests/series/methods/test_astype.py
119 issues
Unable to import 'pytest'
Error

Line: 10 Column: 1

              import sys

import numpy as np
import pytest

from pandas._libs.tslibs import iNaT
import pandas.util._test_decorators as td

from pandas import (

            

Reported by Pylint.

Module 'sys' has no 'setdefaultencoding' member; maybe 'getdefaultencoding'?
Error

Line: 352 Column: 13

                      # Restore the former encoding
        if former_encoding is not None and former_encoding != "utf-8":
            reload(sys)
            sys.setdefaultencoding(former_encoding)

    def test_astype_bytes(self):
        # GH#39474
        result = Series(["foo", "bar", "baz"]).astype(bytes)
        assert result.dtypes == np.dtype("S3")

            

Reported by Pylint.

Module 'numpy.random' has no 'RandomState' member
Error

Line: 405 Column: 22

              class TestAstypeCategorical:
    def test_astype_categorical_to_other(self):
        cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)])
        ser = Series(np.random.RandomState(0).randint(0, 10000, 100)).sort_values()
        ser = cut(ser, range(0, 10500, 500), right=False, labels=cat)

        expected = ser
        tm.assert_series_equal(ser.astype("category"), expected)
        tm.assert_series_equal(ser.astype(CategoricalDtype()), expected)

            

Reported by Pylint.

Unexpected keyword argument 'categories' in method call
Error

Line: 520 Column: 13

                      # deprecated GH#17636, removed in GH#27141
        s = Series(["a", "b", "a"])
        with pytest.raises(TypeError, match="got an unexpected"):
            s.astype("category", categories=["a", "b"], ordered=True)

    @pytest.mark.parametrize("items", [["a", "b", "c", "a"], [1, 2, 3, 1]])
    def test_astype_from_categorical(self, items):
        ser = Series(items)
        exp = Series(Categorical(items))

            

Reported by Pylint.

Unexpected keyword argument 'ordered' in method call
Error

Line: 520 Column: 13

                      # deprecated GH#17636, removed in GH#27141
        s = Series(["a", "b", "a"])
        with pytest.raises(TypeError, match="got an unexpected"):
            s.astype("category", categories=["a", "b"], ordered=True)

    @pytest.mark.parametrize("items", [["a", "b", "c", "a"], [1, 2, 3, 1]])
    def test_astype_from_categorical(self, items):
        ser = Series(items)
        exp = Series(Categorical(items))

            

Reported by Pylint.

Redefining name 'td' from outer scope (line 13)
Error

Line: 231 Column: 9

                  def test_astype_str_cast_td64(self):
        # see GH#9757

        td = Series([Timedelta(1, unit="d")])
        ser = td.astype(str)

        expected = Series(["1 days"])
        tm.assert_series_equal(ser, expected)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from datetime import (
    datetime,
    timedelta,
)
from importlib import reload
import string
import sys

import numpy as np

            

Reported by Pylint.

Missing class docstring
Error

Line: 31 Column: 1

              import pandas._testing as tm


class TestAstypeAPI:
    def test_arg_for_errors_in_astype(self):
        # see GH#14878
        ser = Series([1, 2, 3])

        msg = (

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 32 Column: 5

              

class TestAstypeAPI:
    def test_arg_for_errors_in_astype(self):
        # see GH#14878
        ser = Series([1, 2, 3])

        msg = (
            r"Expected value of kwarg 'errors' to be one of \['raise', "

            

Reported by Pylint.

Method could be a function
Error

Line: 32 Column: 5

              

class TestAstypeAPI:
    def test_arg_for_errors_in_astype(self):
        # see GH#14878
        ser = Series([1, 2, 3])

        msg = (
            r"Expected value of kwarg 'errors' to be one of \['raise', "

            

Reported by Pylint.

pandas/tests/indexes/categorical/test_category.py
118 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

from pandas._libs import index as libindex
from pandas._libs.arrays import NDArrayBacked

import pandas as pd
from pandas import (
    Categorical,

            

Reported by Pylint.

No name 'index' in module 'pandas._libs'
Error

Line: 4 Column: 1

              import numpy as np
import pytest

from pandas._libs import index as libindex
from pandas._libs.arrays import NDArrayBacked

import pandas as pd
from pandas import (
    Categorical,

            

Reported by Pylint.

No name 'arrays' in module 'pandas._libs'
Error

Line: 5 Column: 1

              import pytest

from pandas._libs import index as libindex
from pandas._libs.arrays import NDArrayBacked

import pandas as pd
from pandas import (
    Categorical,
    CategoricalDtype,

            

Reported by Pylint.

Unable to import 'pandas._libs.arrays'
Error

Line: 5 Column: 1

              import pytest

from pandas._libs import index as libindex
from pandas._libs.arrays import NDArrayBacked

import pandas as pd
from pandas import (
    Categorical,
    CategoricalDtype,

            

Reported by Pylint.

Instance of 'TestCategoricalIndex' has no '_index_cls' member
Error

Line: 25 Column: 16

              
    @pytest.fixture
    def simple_index(self) -> CategoricalIndex:
        return self._index_cls(list("aabbca"), categories=list("cab"), ordered=False)

    @pytest.fixture
    def index(self, request):
        return tm.makeCategoricalIndex(100)


            

Reported by Pylint.

Instance of 'TestCategoricalIndex' has no '_index_cls' member
Error

Line: 44 Column: 13

                  def test_pickle_compat_construction(self):
        # Once the deprecation is enforced, we can use the parent class's test
        with tm.assert_produces_warning(FutureWarning, match="without passing data"):
            self._index_cls()

    def test_insert(self, simple_index):

        ci = simple_index
        categories = ci.categories

            

Reported by Pylint.

Instance of 'CategoricalIndex' has no 'set_categories' member
Error

Line: 245 Column: 26

                      )

        # mismatched categorical -> coerced to ndarray so doesn't matter
        result = ci.isin(ci.set_categories(list("abcdefghi")))
        expected = np.array([True] * 6)
        tm.assert_numpy_array_equal(result, expected)

        result = ci.isin(ci.set_categories(list("defghi")))
        expected = np.array([False] * 5 + [True])

            

Reported by Pylint.

Instance of 'CategoricalIndex' has no 'set_categories' member
Error

Line: 249 Column: 26

                      expected = np.array([True] * 6)
        tm.assert_numpy_array_equal(result, expected)

        result = ci.isin(ci.set_categories(list("defghi")))
        expected = np.array([False] * 5 + [True])
        tm.assert_numpy_array_equal(result, expected)

    def test_identical(self):


            

Reported by Pylint.

Instance of 'CategoricalIndex' has no 'set_categories' member
Error

Line: 349 Column: 18

                  def test_method_delegation(self):

        ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
        result = ci.set_categories(list("cab"))
        tm.assert_index_equal(
            result, CategoricalIndex(list("aabbca"), categories=list("cab"))
        )

        ci = CategoricalIndex(list("aabbca"), categories=list("cab"))

            

Reported by Pylint.

Instance of 'CategoricalIndex' has no 'rename_categories' member
Error

Line: 355 Column: 18

                      )

        ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
        result = ci.rename_categories(list("efg"))
        tm.assert_index_equal(
            result, CategoricalIndex(list("ffggef"), categories=list("efg"))
        )

        # GH18862 (let rename_categories take callables)

            

Reported by Pylint.

pandas/core/strings/accessor.py
118 issues
No name 'lib' in module 'pandas._libs'
Error

Line: 15 Column: 1

              
import numpy as np

import pandas._libs.lib as lib
from pandas._typing import DtypeObj
from pandas.util._decorators import Appender

from pandas.core.dtypes.common import (
    ensure_object,

            

Reported by Pylint.

Unable to import 'pandas._libs.lib'
Error

Line: 15 Column: 1

              
import numpy as np

import pandas._libs.lib as lib
from pandas._typing import DtypeObj
from pandas.util._decorators import Appender

from pandas.core.dtypes.common import (
    ensure_object,

            

Reported by Pylint.

Access to a protected member _inferred_dtype of a client class
Error

Line: 112 Column: 16

              
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            if self._inferred_dtype not in allowed_types:
                msg = (
                    f"Cannot use .str.{func_name} with values of "
                    f"inferred dtype '{self._inferred_dtype}'."
                )
                raise TypeError(msg)

            

Reported by Pylint.

Access to a protected member _inferred_dtype of a client class
Error

Line: 114 Column: 22

                      def wrapper(self, *args, **kwargs):
            if self._inferred_dtype not in allowed_types:
                msg = (
                    f"Cannot use .str.{func_name} with values of "
                    f"inferred dtype '{self._inferred_dtype}'."
                )
                raise TypeError(msg)
            return func(self, *args, **kwargs)


            

Reported by Pylint.

Access to a protected member _data of a client class
Error

Line: 129 Column: 26

              def _map_and_wrap(name, docstring):
    @forbid_nonstring_types(["bytes"], name=name)
    def wrapper(self):
        result = getattr(self._data.array, f"_str_{name}")()
        return self._wrap_result(result)

    wrapper.__doc__ = docstring
    return wrapper


            

Reported by Pylint.

Access to a protected member _wrap_result of a client class
Error

Line: 130 Column: 16

                  @forbid_nonstring_types(["bytes"], name=name)
    def wrapper(self):
        result = getattr(self._data.array, f"_str_{name}")()
        return self._wrap_result(result)

    wrapper.__doc__ = docstring
    return wrapper



            

Reported by Pylint.

TODO: Dispatch all the methods
Error

Line: 162 Column: 3

              
    # Note: see the docstring in pandas.core.strings.__init__
    # for an explanation of the implementation.
    # TODO: Dispatch all the methods
    # Currently the following are not dispatched to the array
    # * cat
    # * extractall

    def __init__(self, data):

            

Reported by Pylint.

Unused argument 'fill_value'
Error

Line: 249 Column: 9

                      result,
        name=None,
        expand: bool | None = None,
        fill_value=np.nan,
        returns_string=True,
        returns_bool: bool = False,
    ):
        from pandas import (
            Index,

            

Reported by Pylint.

Unused argument 'returns_bool'
Error

Line: 251 Column: 9

                      expand: bool | None = None,
        fill_value=np.nan,
        returns_string=True,
        returns_bool: bool = False,
    ):
        from pandas import (
            Index,
            MultiIndex,
        )

            

Reported by Pylint.

Access to a protected member _with_infer of a client class
Error

Line: 325 Column: 24

                                  out = out.get_level_values(0)
                return out
            else:
                return Index._with_infer(result, name=name)
        else:
            index = self._orig.index
            # This is a mess.
            dtype: DtypeObj | str | None
            vdtype = getattr(result, "dtype", None)

            

Reported by Pylint.

pandas/tests/reshape/concat/test_append_common.py
117 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

import pandas as pd
from pandas import (
    Categorical,
    DataFrame,
    Index,
    Series,

            

Reported by Pylint.

Unused argument 'method'
Error

Line: 19 Column: 28

                  Test common dtype coercion rules between concat and append.
    """

    def setup_method(self, method):

        dt_data = [
            pd.Timestamp("2011-01-01"),
            pd.Timestamp("2011-01-02"),
            pd.Timestamp("2011-01-03"),

            

Reported by Pylint.

Attribute 'data' defined outside __init__
Error

Line: 44 Column: 9

                          pd.Period("2011-03", freq="M"),
        ]

        self.data = {
            "bool": [True, False, True],
            "int64": [1, 2, 3],
            "float64": [1.1, np.nan, 3.3],
            "category": Categorical(["X", "Y", "Z"]),
            "object": ["a", "b", "c"],

            

Reported by Pylint.

TODO: suspicious
Error

Line: 203 Column: 3

                                  # same dtype is tested in test_concatlike_same_dtypes
                    continue
                elif typ1 == "category" or typ2 == "category":
                    # TODO: suspicious
                    continue

                # specify expected dtype
                if typ1 == "bool" and typ2 in ("int64", "float64"):
                    # series coerces to numeric based on numpy rule

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import pytest

import pandas as pd
from pandas import (
    Categorical,
    DataFrame,
    Index,
    Series,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 5

                  Test common dtype coercion rules between concat and append.
    """

    def setup_method(self, method):

        dt_data = [
            pd.Timestamp("2011-01-01"),
            pd.Timestamp("2011-01-02"),
            pd.Timestamp("2011-01-03"),

            

Reported by Pylint.

Method could be a function
Error

Line: 56 Column: 5

                          "period[M]": period_data,
        }

    def _check_expected_dtype(self, obj, label):
        """
        Check whether obj has expected dtype depending on label
        considering not-supported dtypes
        """
        if isinstance(obj, Index):

            

Reported by Pylint.

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

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

                      """
        if isinstance(obj, Index):
            if label == "bool":
                assert obj.dtype == "object"
            else:
                assert obj.dtype == label
        elif isinstance(obj, Series):
            if label.startswith("period"):
                assert obj.dtype == "Period[M]"

            

Reported by Bandit.

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

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

                          if label == "bool":
                assert obj.dtype == "object"
            else:
                assert obj.dtype == label
        elif isinstance(obj, Series):
            if label.startswith("period"):
                assert obj.dtype == "Period[M]"
            else:
                assert obj.dtype == label

            

Reported by Bandit.

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

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

                              assert obj.dtype == label
        elif isinstance(obj, Series):
            if label.startswith("period"):
                assert obj.dtype == "Period[M]"
            else:
                assert obj.dtype == label
        else:
            raise ValueError


            

Reported by Bandit.

asv_bench/benchmarks/inference.py
117 issues
Unable to import 'pandas'
Error

Line: 11 Column: 1

              
import numpy as np

from pandas import (
    NaT,
    Series,
    date_range,
    to_datetime,
    to_numeric,

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 20 Column: 1

                  to_timedelta,
)

from .pandas_vb_common import (
    lib,
    tm,
)



            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 300 Column: 1

                      to_timedelta(self.arr, errors=errors)


from .pandas_vb_common import setup  # noqa: F401 isort:skip

            

Reported by Pylint.

Unused argument 'errors'
Error

Line: 31 Column: 21

                  params = ["ignore", "coerce"]
    param_names = ["errors"]

    def setup(self, errors):
        N = 10000
        self.float = Series(np.random.randn(N))
        self.numstr = self.float.astype("str")
        self.str = Series(tm.makeStringIndex(N))


            

Reported by Pylint.

Attribute 'float' defined outside __init__
Error

Line: 33 Column: 9

              
    def setup(self, errors):
        N = 10000
        self.float = Series(np.random.randn(N))
        self.numstr = self.float.astype("str")
        self.str = Series(tm.makeStringIndex(N))

    def time_from_float(self, errors):
        to_numeric(self.float, errors=errors)

            

Reported by Pylint.

Attribute 'numstr' defined outside __init__
Error

Line: 34 Column: 9

                  def setup(self, errors):
        N = 10000
        self.float = Series(np.random.randn(N))
        self.numstr = self.float.astype("str")
        self.str = Series(tm.makeStringIndex(N))

    def time_from_float(self, errors):
        to_numeric(self.float, errors=errors)


            

Reported by Pylint.

Attribute 'str' defined outside __init__
Error

Line: 35 Column: 9

                      N = 10000
        self.float = Series(np.random.randn(N))
        self.numstr = self.float.astype("str")
        self.str = Series(tm.makeStringIndex(N))

    def time_from_float(self, errors):
        to_numeric(self.float, errors=errors)

    def time_from_numeric_str(self, errors):

            

Reported by Pylint.

Unused argument 'downcast'
Error

Line: 76 Column: 28

                      "int32": np.repeat(np.int32(1), N),
    }

    def setup(self, dtype, downcast):
        self.data = self.data_dict[dtype]

    def time_downcast(self, dtype, downcast):
        to_numeric(self.data, downcast=downcast)


            

Reported by Pylint.

Attribute 'data' defined outside __init__
Error

Line: 77 Column: 9

                  }

    def setup(self, dtype, downcast):
        self.data = self.data_dict[dtype]

    def time_downcast(self, dtype, downcast):
        to_numeric(self.data, downcast=downcast)



            

Reported by Pylint.

Unused argument 'dtype'
Error

Line: 79 Column: 29

                  def setup(self, dtype, downcast):
        self.data = self.data_dict[dtype]

    def time_downcast(self, dtype, downcast):
        to_numeric(self.data, downcast=downcast)


class MaybeConvertNumeric:
    # maybe_convert_numeric depends _exclusively_ on _libs, could

            

Reported by Pylint.

pandas/tests/extension/decimal/test_decimal.py
116 issues
Unable to import 'pytest'
Error

Line: 6 Column: 1

              import operator

import numpy as np
import pytest

import pandas as pd
import pandas._testing as tm
from pandas.api.types import infer_dtype
from pandas.tests.extension import base

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 341 Column: 5

              class DecimalArrayWithoutFromSequence(DecimalArray):
    """Helper class for testing error handling in _from_sequence."""

    def _from_sequence(cls, scalars, dtype=None, copy=False):
        raise KeyError("For the test")


class DecimalArrayWithoutCoercion(DecimalArrayWithoutFromSequence):
    @classmethod

            

Reported by Pylint.

TODO(EA): select_dtypes
Error

Line: 99 Column: 3

              
    @classmethod
    def assert_frame_equal(cls, left, right, *args, **kwargs):
        # TODO(EA): select_dtypes
        tm.assert_index_equal(
            left.columns,
            right.columns,
            exact=kwargs.get("check_column_type", "equiv"),
            check_names=kwargs.get("check_names", True),

            

Reported by Pylint.

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

Line: 121 Column: 29

              

class TestDtype(BaseDecimal, base.BaseDtypeTests):
    def test_hashable(self, dtype):
        pass

    @pytest.mark.parametrize("skipna", [True, False])
    def test_infer_dtype(self, data, data_missing, skipna):
        # here overriding base test to ensure we fall back to return

            

Reported by Pylint.

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

Line: 125 Column: 32

                      pass

    @pytest.mark.parametrize("skipna", [True, False])
    def test_infer_dtype(self, data, data_missing, skipna):
        # here overriding base test to ensure we fall back to return
        # "unknown-array" for an EA pandas doesn't know
        assert infer_dtype(data, skipna=skipna) == "unknown-array"
        assert infer_dtype(data_missing, skipna=skipna) == "unknown-array"


            

Reported by Pylint.

Redefining name 'data_missing' from outer scope (line 36)
Error

Line: 125 Column: 38

                      pass

    @pytest.mark.parametrize("skipna", [True, False])
    def test_infer_dtype(self, data, data_missing, skipna):
        # here overriding base test to ensure we fall back to return
        # "unknown-array" for an EA pandas doesn't know
        assert infer_dtype(data, skipna=skipna) == "unknown-array"
        assert infer_dtype(data_missing, skipna=skipna) == "unknown-array"


            

Reported by Pylint.

Parameters differ from overridden 'test_value_counts' method
Error

Line: 180 Column: 5

              
class TestMethods(BaseDecimal, base.BaseMethodsTests):
    @pytest.mark.parametrize("dropna", [True, False])
    def test_value_counts(self, all_data, dropna, request):
        all_data = all_data[:10]
        if dropna:
            other = np.array(all_data[~all_data.isna()])
        else:
            other = all_data

            

Reported by Pylint.

Unused argument 'request'
Error

Line: 180 Column: 51

              
class TestMethods(BaseDecimal, base.BaseMethodsTests):
    @pytest.mark.parametrize("dropna", [True, False])
    def test_value_counts(self, all_data, dropna, request):
        all_data = all_data[:10]
        if dropna:
            other = np.array(all_data[~all_data.isna()])
        else:
            other = all_data

            

Reported by Pylint.

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

Line: 199 Column: 48

              
        tm.assert_series_equal(result, expected)

    def test_value_counts_with_normalize(self, data):
        return super().test_value_counts_with_normalize(data)


class TestCasting(BaseDecimal, base.BaseCastingTests):
    pass

            

Reported by Pylint.

Useless super delegation in method 'test_value_counts_with_normalize'
Error

Line: 199 Column: 5

              
        tm.assert_series_equal(result, expected)

    def test_value_counts_with_normalize(self, data):
        return super().test_value_counts_with_normalize(data)


class TestCasting(BaseDecimal, base.BaseCastingTests):
    pass

            

Reported by Pylint.