Skip to content

Commit 430f0fd

Browse files
topper-123jreback
authored andcommitted
CLN: remove util._decorators.make_signature and make related changes (#26819)
1 parent f6e33a0 commit 430f0fd

File tree

5 files changed

+52
-121
lines changed

5 files changed

+52
-121
lines changed

pandas/_typing.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from pandas.core.dtypes.dtypes import ExtensionDtype
1111
from pandas.core.dtypes.generic import (
12-
ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries)
12+
ABCDataFrame, ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries)
1313

1414
AnyArrayLike = TypeVar('AnyArrayLike',
1515
ABCExtensionArray,
@@ -22,3 +22,5 @@
2222
Timedelta)
2323
Dtype = Union[str, np.dtype, ExtensionDtype]
2424
FilePathOrBuffer = Union[str, Path, IO[AnyStr]]
25+
26+
FrameOrSeries = TypeVar('FrameOrSeries', ABCSeries, ABCDataFrame)

pandas/core/groupby/base.py

-69
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,6 @@
33
hold the whitelist of methods that are exposed on the
44
SeriesGroupBy and the DataFrameGroupBy objects.
55
"""
6-
7-
import types
8-
9-
from pandas.util._decorators import make_signature
10-
116
from pandas.core.dtypes.common import is_list_like, is_scalar
127

138

@@ -91,67 +86,3 @@ def _gotitem(self, key, ndim, subset=None):
9186

9287
cython_cast_blacklist = frozenset(['rank', 'count', 'size', 'idxmin',
9388
'idxmax'])
94-
95-
96-
def whitelist_method_generator(base, klass, whitelist):
97-
"""
98-
Yields all GroupBy member defs for DataFrame/Series names in whitelist.
99-
100-
Parameters
101-
----------
102-
base : class
103-
base class
104-
klass : class
105-
class where members are defined.
106-
Should be Series or DataFrame
107-
whitelist : list
108-
list of names of klass methods to be constructed
109-
110-
Returns
111-
-------
112-
The generator yields a sequence of strings, each suitable for exec'ing,
113-
that define implementations of the named methods for DataFrameGroupBy
114-
or SeriesGroupBy.
115-
116-
Since we don't want to override methods explicitly defined in the
117-
base class, any such name is skipped.
118-
"""
119-
120-
method_wrapper_template = \
121-
"""def %(name)s(%(sig)s) :
122-
\"""
123-
%(doc)s
124-
\"""
125-
f = %(self)s.__getattr__('%(name)s')
126-
return f(%(args)s)"""
127-
property_wrapper_template = \
128-
"""@property
129-
def %(name)s(self) :
130-
\"""%(doc)s\"""
131-
return self.__getattr__('%(name)s')"""
132-
133-
for name in whitelist:
134-
# don't override anything that was explicitly defined
135-
# in the base class
136-
if hasattr(base, name):
137-
continue
138-
# ugly, but we need the name string itself in the method.
139-
f = getattr(klass, name)
140-
doc = f.__doc__
141-
doc = doc if type(doc) == str else ''
142-
if isinstance(f, types.MethodType):
143-
wrapper_template = method_wrapper_template
144-
decl, args = make_signature(f)
145-
# pass args by name to f because otherwise
146-
# GroupBy._make_wrapper won't know whether
147-
# we passed in an axis parameter.
148-
args_by_name = ['{0}={0}'.format(arg) for arg in args[1:]]
149-
params = {'name': name,
150-
'doc': doc,
151-
'sig': ','.join(decl),
152-
'self': args[0],
153-
'args': ','.join(args_by_name)}
154-
else:
155-
wrapper_template = property_wrapper_template
156-
params = {'name': name, 'doc': doc}
157-
yield wrapper_template % params

pandas/core/groupby/generic.py

+49-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from functools import partial
1212
from textwrap import dedent
1313
import typing
14-
from typing import Any, Callable, List, Union
14+
from typing import Any, Callable, FrozenSet, Iterator, List, Type, Union
1515
import warnings
1616

1717
import numpy as np
@@ -27,6 +27,7 @@
2727
is_integer_dtype, is_interval_dtype, is_numeric_dtype, is_scalar)
2828
from pandas.core.dtypes.missing import isna, notna
2929

30+
from pandas._typing import FrameOrSeries
3031
import pandas.core.algorithms as algorithms
3132
from pandas.core.base import DataError, SpecificationError
3233
import pandas.core.common as com
@@ -48,6 +49,51 @@
4849
AggScalar = Union[str, Callable[..., Any]]
4950

5051

52+
def whitelist_method_generator(base_class: Type[GroupBy],
53+
klass: Type[FrameOrSeries],
54+
whitelist: FrozenSet[str],
55+
) -> Iterator[str]:
56+
"""
57+
Yields all GroupBy member defs for DataFrame/Series names in whitelist.
58+
59+
Parameters
60+
----------
61+
base_class : Groupby class
62+
base class
63+
klass : DataFrame or Series class
64+
class where members are defined.
65+
whitelist : frozenset
66+
Set of names of klass methods to be constructed
67+
68+
Returns
69+
-------
70+
The generator yields a sequence of strings, each suitable for exec'ing,
71+
that define implementations of the named methods for DataFrameGroupBy
72+
or SeriesGroupBy.
73+
74+
Since we don't want to override methods explicitly defined in the
75+
base class, any such name is skipped.
76+
"""
77+
property_wrapper_template = \
78+
"""@property
79+
def %(name)s(self) :
80+
\"""%(doc)s\"""
81+
return self.__getattr__('%(name)s')"""
82+
83+
for name in whitelist:
84+
# don't override anything that was explicitly defined
85+
# in the base class
86+
if hasattr(base_class, name):
87+
continue
88+
# ugly, but we need the name string itself in the method.
89+
f = getattr(klass, name)
90+
doc = f.__doc__
91+
doc = doc if type(doc) == str else ''
92+
wrapper_template = property_wrapper_template
93+
params = {'name': name, 'doc': doc}
94+
yield wrapper_template % params
95+
96+
5197
class NDFrameGroupBy(GroupBy):
5298

5399
def _iterate_slices(self):
@@ -685,7 +731,7 @@ class SeriesGroupBy(GroupBy):
685731
# Make class defs of attributes on SeriesGroupBy whitelist
686732

687733
_apply_whitelist = base.series_apply_whitelist
688-
for _def_str in base.whitelist_method_generator(
734+
for _def_str in whitelist_method_generator(
689735
GroupBy, Series, _apply_whitelist):
690736
exec(_def_str)
691737

@@ -1289,7 +1335,7 @@ class DataFrameGroupBy(NDFrameGroupBy):
12891335

12901336
#
12911337
# Make class defs of attributes on DataFrameGroupBy whitelist.
1292-
for _def_str in base.whitelist_method_generator(
1338+
for _def_str in whitelist_method_generator(
12931339
GroupBy, DataFrame, _apply_whitelist):
12941340
exec(_def_str)
12951341

pandas/tests/util/test_util.py

-18
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66
import pandas.compat as compat
77
from pandas.compat import raise_with_traceback
8-
from pandas.util._decorators import deprecate_kwarg, make_signature
9-
from pandas.util._validators import validate_kwargs
108

119
import pandas.util.testing as tm
1210

@@ -37,22 +35,6 @@ def test_numpy_err_state_is_default():
3735
assert np.geterr() == expected
3836

3937

40-
@pytest.mark.parametrize("func,expected", [
41-
# Case where the func does not have default kwargs.
42-
(validate_kwargs, (["fname", "kwargs", "compat_args"],
43-
["fname", "kwargs", "compat_args"])),
44-
45-
# Case where the func does have default kwargs.
46-
(deprecate_kwarg, (["old_arg_name", "new_arg_name",
47-
"mapping=None", "stacklevel=2"],
48-
["old_arg_name", "new_arg_name",
49-
"mapping", "stacklevel"]))
50-
])
51-
def test_make_signature(func, expected):
52-
# see gh-17608
53-
assert make_signature(func) == expected
54-
55-
5638
def test_raise_with_traceback():
5739
with pytest.raises(LookupError, match="error_text"):
5840
try:

pandas/util/_decorators.py

-30
Original file line numberDiff line numberDiff line change
@@ -319,33 +319,3 @@ def indent(text, indents=1):
319319
return ''
320320
jointext = ''.join(['\n'] + [' '] * indents)
321321
return jointext.join(text.split('\n'))
322-
323-
324-
def make_signature(func):
325-
"""
326-
Returns a tuple containing the paramenter list with defaults
327-
and parameter list.
328-
329-
Examples
330-
--------
331-
>>> def f(a, b, c=2):
332-
>>> return a * b * c
333-
>>> print(make_signature(f))
334-
(['a', 'b', 'c=2'], ['a', 'b', 'c'])
335-
"""
336-
337-
spec = inspect.getfullargspec(func)
338-
if spec.defaults is None:
339-
n_wo_defaults = len(spec.args)
340-
defaults = ('',) * n_wo_defaults
341-
else:
342-
n_wo_defaults = len(spec.args) - len(spec.defaults)
343-
defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
344-
args = []
345-
for var, default in zip(spec.args, defaults):
346-
args.append(var if default == '' else var + '=' + repr(default))
347-
if spec.varargs:
348-
args.append('*' + spec.varargs)
349-
if spec.varkw:
350-
args.append('**' + spec.varkw)
351-
return args, spec.args

0 commit comments

Comments
 (0)