Skip to content

CLN/TYP: assorted cleanup and annotations #41533

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

Merged
merged 3 commits into from
May 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion pandas/_libs/tslib.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,10 @@ def array_with_unit_to_datetime(
if issubclass(values.dtype.type, (np.integer, np.float_)):
result = values.astype("M8[ns]", copy=False)
else:
result, tz = array_to_datetime(values.astype(object), errors=errors)
result, tz = array_to_datetime(
values.astype(object, copy=False),
errors=errors,
)
return result, tz

m, p = precision_from_unit(unit)
Expand Down
1 change: 1 addition & 0 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ def _selected_obj(self):
else:
return self.obj[self._selection]

@final
@cache_readonly
def ndim(self) -> int:
return self._selected_obj.ndim
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,8 +1105,8 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame:
else:
# we get here in a number of test_multilevel tests
for name in self.indices:
data = self.get_group(name, obj=obj)
fres = func(data, *args, **kwargs)
grp_df = self.get_group(name, obj=obj)
fres = func(grp_df, *args, **kwargs)
result[name] = fres

result_index = self.grouper.result_index
Expand Down
7 changes: 4 additions & 3 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ class GroupByPlot(PandasObject):
Class implementing the .plot attribute for groupby objects.
"""

def __init__(self, groupby):
def __init__(self, groupby: GroupBy):
self._groupby = groupby

def __call__(self, *args, **kwargs):
Expand Down Expand Up @@ -727,7 +727,7 @@ def pipe(
plot = property(GroupByPlot)

@final
def get_group(self, name, obj=None):
def get_group(self, name, obj=None) -> FrameOrSeriesUnion:
"""
Construct DataFrame from group with provided name.

Expand Down Expand Up @@ -960,10 +960,11 @@ def _set_group_selection(self) -> None:

NOTE: this should be paired with a call to _reset_group_selection
"""
# This is a no-op for SeriesGroupBy
grp = self.grouper
if not (
self.as_index
and getattr(grp, "groupings", None) is not None
and grp.groupings is not None
and self.obj.ndim > 1
and self._group_selection is None
):
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def arrays_to_mgr(
if verify_integrity:
# figure out the index, if necessary
if index is None:
index = extract_index(arrays)
index = _extract_index(arrays)
else:
index = ensure_index(index)

Expand Down Expand Up @@ -424,7 +424,7 @@ def dict_to_mgr(
if index is None:
# GH10856
# raise ValueError if only scalars in dict
index = extract_index(arrays[~missing])
index = _extract_index(arrays[~missing])
else:
index = ensure_index(index)

Expand Down Expand Up @@ -603,7 +603,7 @@ def _homogenize(data, index: Index, dtype: DtypeObj | None):
return homogenized


def extract_index(data) -> Index:
def _extract_index(data) -> Index:
"""
Try to infer an Index from the passed data, raise ValueError on failure.
"""
Expand Down
18 changes: 6 additions & 12 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,26 +497,20 @@ def _to_datetime_with_format(
return _box_as_indexlike(result, utc=utc, name=name)

# fallback
if result is None:
res = _array_strptime_with_fallback(
arg, name, tz, fmt, exact, errors, infer_datetime_format
)
if res is not None:
return res
res = _array_strptime_with_fallback(
arg, name, tz, fmt, exact, errors, infer_datetime_format
)
return res

except ValueError as e:
except ValueError as err:
# Fallback to try to convert datetime objects if timezone-aware
# datetime objects are found without passing `utc=True`
try:
values, tz = conversion.datetime_to_datetime64(arg)
dta = DatetimeArray(values, dtype=tz_to_dtype(tz))
return DatetimeIndex._simple_new(dta, name=name)
except (ValueError, TypeError):
raise e

# error: Incompatible return value type (got "Optional[ndarray]", expected
# "Optional[Index]")
return result # type: ignore[return-value]
raise err


def _to_datetime_with_unit(arg, unit, name, tz, errors: str) -> Index:
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/window/rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ class BaseWindow(SelectionMixin):

_attributes: list[str] = []
exclusions: frozenset[Hashable] = frozenset()
_on: Index

def __init__(
self,
Expand Down Expand Up @@ -169,7 +170,7 @@ def win_type(self):
return self._win_type

@property
def is_datetimelike(self):
def is_datetimelike(self) -> bool:
warnings.warn(
"is_datetimelike is deprecated and will be removed in a future version.",
FutureWarning,
Expand Down Expand Up @@ -329,7 +330,7 @@ def _prep_values(self, values: ArrayLike) -> np.ndarray:
# expected "ndarray")
return values # type: ignore[return-value]

def _insert_on_column(self, result: DataFrame, obj: DataFrame):
def _insert_on_column(self, result: DataFrame, obj: DataFrame) -> None:
# if we have an 'on' column we want to put it back into
# the results in the same location
from pandas import Series
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/tools/test_to_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@ def test_iso8601_strings_mixed_offsets_with_naive(self):

def test_mixed_offsets_with_native_datetime_raises(self):
# GH 25978
s = Series(
ser = Series(
[
"nan",
Timestamp("1990-01-01"),
Expand All @@ -1089,7 +1089,7 @@ def test_mixed_offsets_with_native_datetime_raises(self):
]
)
with pytest.raises(ValueError, match="Tz-aware datetime.datetime"):
to_datetime(s)
to_datetime(ser)

def test_non_iso_strings_with_tz_offset(self):
result = to_datetime(["March 1, 2018 12:00:00+0400"] * 2)
Expand Down