Skip to content

(WIP) TYP: add some obvious -> None to pandas/core #47497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas/core/array_algos/replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def compare_or_regex_search(

def _check_comparison_types(
result: ArrayLike | bool, a: ArrayLike, b: Scalar | Pattern
):
) -> None:
"""
Raises an error if the two arrays (a,b) cannot be compared.
Otherwise, returns the comparison result as expected.
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/array_algos/take.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ def _get_take_nd_function(

if func is None:

def func(arr, indexer, out, fill_value=np.nan):
def func(arr, indexer, out, fill_value=np.nan) -> None:
indexer = ensure_platform_int(indexer)
_take_nd_object(
arr, indexer, out, axis=axis, fill_value=fill_value, mask_info=mask_info
Expand All @@ -349,7 +349,7 @@ def func(arr, indexer, out, fill_value=np.nan):
def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None):
def wrapper(
arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan
):
) -> None:
if arr_dtype is not None:
arr = arr.view(arr_dtype)
if out_dtype is not None:
Expand All @@ -364,7 +364,7 @@ def wrapper(
def _convert_wrapper(f, conv_dtype):
def wrapper(
arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan
):
) -> None:
if conv_dtype == object:
# GH#39755 avoid casting dt64/td64 to integers
arr = ensure_wrapped_if_datetimelike(arr)
Expand Down Expand Up @@ -506,7 +506,7 @@ def _take_nd_object(
axis: int,
fill_value,
mask_info,
):
) -> None:
if mask_info is not None:
mask, needs_masking = mask_info
else:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def _validate_shift_value(self, fill_value):
# we can remove this and use validate_fill_value directly
return self._validate_scalar(fill_value)

def __setitem__(self, key, value):
def __setitem__(self, key, value) -> None:
key = check_array_indexer(self, key)
value = self._validate_setitem_value(value)
self._ndarray[key] = value
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/arrow/_arrow_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from pandas.core.arrays.interval import VALID_CLOSED


def fallback_performancewarning(version: str | None = None):
def fallback_performancewarning(version: str | None = None) -> None:
"""
Raise a PerformanceWarning for falling back to ExtensionArray's
non-pyarrow method
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1699,7 +1699,7 @@ def _create_arithmetic_method(cls, op):
raise AbstractMethodError(cls)

@classmethod
def _add_arithmetic_ops(cls):
def _add_arithmetic_ops(cls) -> None:
setattr(cls, "__add__", cls._create_arithmetic_method(operator.add))
setattr(cls, "__radd__", cls._create_arithmetic_method(roperator.radd))
setattr(cls, "__sub__", cls._create_arithmetic_method(operator.sub))
Expand All @@ -1724,7 +1724,7 @@ def _create_comparison_method(cls, op):
raise AbstractMethodError(cls)

@classmethod
def _add_comparison_ops(cls):
def _add_comparison_ops(cls) -> None:
setattr(cls, "__eq__", cls._create_comparison_method(operator.eq))
setattr(cls, "__ne__", cls._create_comparison_method(operator.ne))
setattr(cls, "__lt__", cls._create_comparison_method(operator.lt))
Expand All @@ -1737,7 +1737,7 @@ def _create_logical_method(cls, op):
raise AbstractMethodError(cls)

@classmethod
def _add_logical_ops(cls):
def _add_logical_ops(cls) -> None:
setattr(cls, "__and__", cls._create_logical_method(operator.and_))
setattr(cls, "__rand__", cls._create_logical_method(roperator.rand_))
setattr(cls, "__or__", cls._create_logical_method(operator.or_))
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ def categories(self):
return self.dtype.categories

@categories.setter
def categories(self, categories):
def categories(self, categories) -> None:
new_dtype = CategoricalDtype(categories, ordered=self.ordered)
if self.dtype.categories is not None and len(self.dtype.categories) != len(
new_dtype.categories
Expand Down Expand Up @@ -776,7 +776,7 @@ def codes(self) -> np.ndarray:
v.flags.writeable = False
return v

def _set_categories(self, categories, fastpath=False):
def _set_categories(self, categories, fastpath=False) -> None:
"""
Sets new categories inplace

Expand Down Expand Up @@ -1700,7 +1700,7 @@ def _internal_get_values(self):
return self.categories.astype("object").take(self._codes, fill_value=np.nan)
return np.array(self)

def check_for_ordered(self, op):
def check_for_ordered(self, op) -> None:
"""assert that we are ordered"""
if not self.ordered:
raise TypeError(
Expand Down Expand Up @@ -1931,7 +1931,7 @@ def _codes(self) -> np.ndarray:
return self._ndarray

@_codes.setter
def _codes(self, value: np.ndarray):
def _codes(self, value: np.ndarray) -> None:
warn(
"Setting the codes on a Categorical is deprecated and will raise in "
"a future version. Create a new Categorical object instead",
Expand Down Expand Up @@ -1985,7 +1985,7 @@ def __contains__(self, key) -> bool:
# ------------------------------------------------------------------
# Rendering Methods

def _formatter(self, boxed: bool = False):
def _formatter(self, boxed: bool = False) -> None:
# Defer to CategoricalFormatter's formatter.
return None

Expand Down Expand Up @@ -2713,7 +2713,7 @@ def __init__(self, data) -> None:
self._freeze()

@staticmethod
def _validate(data):
def _validate(data) -> None:
if not is_categorical_dtype(data.dtype):
raise AttributeError("Can only use .cat accessor with a 'category' dtype")

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ def __setitem__( # type: ignore[override]

self._maybe_clear_freq()

def _maybe_clear_freq(self):
def _maybe_clear_freq(self) -> None:
# inplace operations like __setitem__ may invalidate the freq of
# DatetimeArray and TimedeltaArray
pass
Expand Down Expand Up @@ -924,7 +924,7 @@ def freq(self):
return self._freq

@freq.setter
def freq(self, value):
def freq(self, value) -> None:
if value is not None:
value = to_offset(value)
self._validate_frequency(self, value)
Expand Down Expand Up @@ -976,7 +976,7 @@ def resolution(self) -> str:
return self._resolution_obj.attrname # type: ignore[union-attr]

@classmethod
def _validate_frequency(cls, index, freq, **kwargs):
def _validate_frequency(cls, index, freq, **kwargs) -> None:
"""
Validate that a frequency is compatible with the values of a given
Datetime Array/Index or Timedelta Array/Index
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ def _unbox_scalar(self, value, setitem: bool = False) -> np.datetime64:
def _scalar_from_string(self, value) -> Timestamp | NaTType:
return Timestamp(value, tz=self.tz)

def _check_compatible_with(self, other, setitem: bool = False):
def _check_compatible_with(self, other, setitem: bool = False) -> None:
if other is NaT:
return
self._assert_tzawareness_compat(other)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ def from_tuples(

return cls.from_arrays(left, right, inclusive, copy=False, dtype=dtype)

def _validate(self):
def _validate(self) -> None:
"""
Verify that the IntervalArray is valid.

Expand Down Expand Up @@ -696,7 +696,7 @@ def __getitem__(
raise ValueError("multi-dimensional indexing not allowed")
return self._shallow_copy(left, right)

def __setitem__(self, key, value):
def __setitem__(self, key, value) -> None:
value_left, value_right = self._validate_setitem_value(value)
key = check_array_indexer(self, key)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ def _unbox_scalar( # type: ignore[override]
def _scalar_from_string(self, value: str) -> Period:
return Period(value, freq=self.freq)

def _check_compatible_with(self, other, setitem: bool = False):
def _check_compatible_with(self, other, setitem: bool = False) -> None:
if other is NaT:
return
self._require_matching_freq(other)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/sparse/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class SparseAccessor(BaseAccessor, PandasDelegate):
Accessor for SparseSparse from other sparse matrix data types.
"""

def _validate(self, data):
def _validate(self, data) -> None:
if not isinstance(data.dtype, SparseDtype):
raise AttributeError(self._validation_msg)

Expand Down Expand Up @@ -222,7 +222,7 @@ class SparseFrameAccessor(BaseAccessor, PandasDelegate):
.. versionadded:: 0.25.0
"""

def _validate(self, data):
def _validate(self, data) -> None:
dtypes = data.dtypes
if not all(isinstance(t, SparseDtype) for t in dtypes):
raise AttributeError(self._validation_msg)
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
out[self.sp_index.indices] = self.sp_values
return out

def __setitem__(self, key, value):
def __setitem__(self, key, value) -> None:
# I suppose we could allow setting of non-fill_value elements.
# TODO(SparseArray.__setitem__): remove special cases in
# ExtensionBlock.where
Expand Down Expand Up @@ -657,7 +657,7 @@ def fill_value(self):
return self.dtype.fill_value

@fill_value.setter
def fill_value(self, value):
def fill_value(self, value) -> None:
self._dtype = SparseDtype(self.dtype.subtype, value)

@property
Expand Down Expand Up @@ -1387,7 +1387,7 @@ def _where(self, mask, value):
# ------------------------------------------------------------------------
# IO
# ------------------------------------------------------------------------
def __setstate__(self, state):
def __setstate__(self, state) -> None:
"""Necessary for making this object picklable"""
if isinstance(state, tuple):
# Compat for pandas < 0.24.0
Expand Down Expand Up @@ -1801,7 +1801,7 @@ def __repr__(self) -> str:
pp_index = printing.pprint_thing(self.sp_index)
return f"{pp_str}\nFill: {pp_fill}\n{pp_index}"

def _formatter(self, boxed=False):
def _formatter(self, boxed=False) -> None:
# Defer to the formatter from the GenericArrayFormatter calling us.
# This will infer the correct formatter from the dtype of the values.
return None
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/sparse/dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def fill_value(self):
"""
return self._fill_value

def _check_fill_value(self):
def _check_fill_value(self) -> None:
if not is_scalar(self._fill_value):
raise ValueError(
f"fill_value must be a scalar. Got {self._fill_value} instead"
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/sparse/scipy_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import scipy.sparse


def _check_is_partition(parts: Iterable, whole: Iterable):
def _check_is_partition(parts: Iterable, whole: Iterable) -> None:
whole = set(whole)
parts = [set(x) for x in parts]
if set.intersection(*parts) != set():
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def __init__(self, values, copy=False) -> None:
self._validate()
NDArrayBacked.__init__(self, self._ndarray, StringDtype(storage="python"))

def _validate(self):
def _validate(self) -> None:
"""Validate that we only store NA or strings."""
if len(self._ndarray) and not lib.is_string_array(self._ndarray, skipna=True):
raise ValueError("StringArray requires a sequence of strings or pandas.NA")
Expand Down Expand Up @@ -379,7 +379,7 @@ def _values_for_factorize(self):
arr[mask] = -1
return arr, -1

def __setitem__(self, key, value):
def __setitem__(self, key, value) -> None:
value = extract_array(value, extract_numpy=True)
if isinstance(value, type(self)):
# extract_array doesn't extract PandasArray subclasses
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ def _format_native_types(
# ----------------------------------------------------------------
# Arithmetic Methods

def _add_offset(self, other):
def _add_offset(self, other) -> None:
assert not isinstance(other, Tick)
raise TypeError(
f"cannot add the type {type(other).__name__} to a {type(self).__name__}"
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,14 @@ class NoNewAttributesMixin:
`object.__setattr__(self, key, value)`.
"""

def _freeze(self):
def _freeze(self) -> None:
"""
Prevents setting additional attributes.
"""
object.__setattr__(self, "__frozen", True)

# prevent adding any attribute via s.xxx.new_attribute = ...
def __setattr__(self, key: str, value):
def __setattr__(self, key: str, value) -> None:
# _cache is used by a decorator
# We need to check both 1.) cls.__dict__ and 2.) getattr(self, key)
# because
Expand Down
6 changes: 4 additions & 2 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ def temp_setattr(obj, attr: str, value) -> Iterator[None]:
setattr(obj, attr, old_value)


def require_length_match(data, index: Index):
def require_length_match(data, index: Index) -> None:
"""
Check the length of data matches the length of the index.
"""
Expand Down Expand Up @@ -665,7 +665,9 @@ def resolve_numeric_only(numeric_only: bool | None | lib.NoDefault) -> bool:
return result


def deprecate_numeric_only_default(cls: type, name: str, deprecate_none: bool = False):
def deprecate_numeric_only_default(
cls: type, name: str, deprecate_none: bool = False
) -> None:
"""Emit FutureWarning message for deprecation of numeric_only.

See GH#46560 for details on the deprecation.
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/computation/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _check_engine(engine: str | None) -> str:
return engine


def _check_parser(parser: str):
def _check_parser(parser: str) -> None:
"""
Make sure a valid parser is passed.

Expand All @@ -86,7 +86,7 @@ def _check_parser(parser: str):
)


def _check_resolvers(resolvers):
def _check_resolvers(resolvers) -> None:
if resolvers is not None:
for resolver in resolvers:
if not hasattr(resolver, "__getitem__"):
Expand All @@ -97,7 +97,7 @@ def _check_resolvers(resolvers):
)


def _check_expression(expr):
def _check_expression(expr) -> None:
"""
Make sure an expression is not an empty string

Expand Down Expand Up @@ -144,7 +144,7 @@ def _convert_expression(expr) -> str:
return s


def _check_for_locals(expr: str, stack_level: int, parser: str):
def _check_for_locals(expr: str, stack_level: int, parser: str) -> None:

at_top_of_stack = stack_level == 0
not_pandas_parser = parser != "pandas"
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/computation/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
_MIN_ELEMENTS = 1_000_000


def set_use_numexpr(v=True):
def set_use_numexpr(v=True) -> None:
# set/unset to use numexpr
global USE_NUMEXPR
if NUMEXPR_INSTALLED:
Expand All @@ -51,7 +51,7 @@ def set_use_numexpr(v=True):
_where = _where_numexpr if USE_NUMEXPR else _where_standard


def set_numexpr_threads(n=None):
def set_numexpr_threads(n=None) -> None:
# if we are using numexpr, set the threads to n
# otherwise reset
if NUMEXPR_INSTALLED and USE_NUMEXPR:
Expand Down
Loading