Skip to content

Commit 38021ca

Browse files
behzadnourijreback
authored andcommitted
refactor **kwargs usage
1 parent 85703a7 commit 38021ca

11 files changed

+95
-60
lines changed

pandas/core/categorical.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -913,7 +913,7 @@ def argsort(self, ascending=True, **kwargs):
913913
result = result[::-1]
914914
return result
915915

916-
def order(self, inplace=False, ascending=True, na_position='last', **kwargs):
916+
def order(self, inplace=False, ascending=True, na_position='last'):
917917
""" Sorts the Category by category value returning a new Categorical by default.
918918
919919
Only ordered Categoricals can be sorted!
@@ -972,7 +972,7 @@ def order(self, inplace=False, ascending=True, na_position='last', **kwargs):
972972
name=self.name, fastpath=True)
973973

974974

975-
def sort(self, inplace=True, ascending=True, na_position='last', **kwargs):
975+
def sort(self, inplace=True, ascending=True, na_position='last'):
976976
""" Sorts the Category inplace by category value.
977977
978978
Only ordered Categoricals can be sorted!
@@ -997,7 +997,8 @@ def sort(self, inplace=True, ascending=True, na_position='last', **kwargs):
997997
--------
998998
Category.order
999999
"""
1000-
return self.order(inplace=inplace, ascending=ascending, **kwargs)
1000+
return self.order(inplace=inplace, ascending=ascending,
1001+
na_position=na_position)
10011002

10021003
def ravel(self, order='C'):
10031004
""" Return a flattened (numpy) array.
@@ -1033,7 +1034,7 @@ def to_dense(self):
10331034
"""
10341035
return np.asarray(self)
10351036

1036-
def fillna(self, fill_value=None, method=None, limit=None, **kwargs):
1037+
def fillna(self, fill_value=None, method=None, limit=None):
10371038
""" Fill NA/NaN values using the specified method.
10381039
10391040
Parameters

pandas/core/common.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1559,7 +1559,7 @@ def backfill_2d(values, limit=None, mask=None, dtype=None):
15591559
return values
15601560

15611561

1562-
def _clean_interp_method(method, order=None, **kwargs):
1562+
def _clean_interp_method(method, order=None):
15631563
valid = ['linear', 'time', 'index', 'values', 'nearest', 'zero', 'slinear',
15641564
'quadratic', 'cubic', 'barycentric', 'polynomial',
15651565
'krogh', 'piecewise_polynomial',
@@ -1574,7 +1574,7 @@ def _clean_interp_method(method, order=None, **kwargs):
15741574

15751575

15761576
def interpolate_1d(xvalues, yvalues, method='linear', limit=None,
1577-
fill_value=None, bounds_error=False, **kwargs):
1577+
fill_value=None, bounds_error=False, order=None):
15781578
"""
15791579
Logic for the 1-d interpolation. The result should be 1-d, inputs
15801580
xvalues and yvalues will each be 1-d arrays of the same length.
@@ -1657,14 +1657,14 @@ def _interp_limit(invalid, limit):
16571657

16581658
result[firstIndex:][invalid] = _interpolate_scipy_wrapper(
16591659
valid_x, valid_y, new_x, method=method, fill_value=fill_value,
1660-
bounds_error=bounds_error, **kwargs)
1660+
bounds_error=bounds_error, order=order)
16611661
if limit:
16621662
result[violate_limit] = np.nan
16631663
return result
16641664

16651665

16661666
def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
1667-
bounds_error=False, order=None, **kwargs):
1667+
bounds_error=False, order=None):
16681668
"""
16691669
passed off to scipy.interpolate.interp1d. method is scipy's kind.
16701670
Returns an array interpolated at new_x. Add any new methods to

pandas/core/config.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,11 @@ def _set_option(*args, **kwargs):
109109
"arguments")
110110

111111
# default to false
112-
silent = kwargs.get('silent', False)
112+
silent = kwargs.pop('silent', False)
113+
114+
if kwargs:
115+
raise TypeError('_set_option() got an unexpected keyword '
116+
'argument "{0}"'.format(list(kwargs.keys())[0]))
113117

114118
for k, v in zip(args[::2], args[1::2]):
115119
key = _get_single_key(k, silent)

pandas/core/generic.py

+30-15
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def _construct_axes_from_arguments(self, args, kwargs, require_all=False):
267267
raise TypeError(
268268
"not enough/duplicate arguments specified!")
269269

270-
axes = dict([(a, kwargs.get(a)) for a in self._AXIS_ORDERS])
270+
axes = dict([(a, kwargs.pop(a, None)) for a in self._AXIS_ORDERS])
271271
return axes, kwargs
272272

273273
@classmethod
@@ -444,8 +444,13 @@ def transpose(self, *args, **kwargs):
444444
new_axes = self._construct_axes_dict_from(
445445
self, [self._get_axis(x) for x in axes_names])
446446
new_values = self.values.transpose(axes_numbers)
447-
if kwargs.get('copy') or (len(args) and args[-1]):
447+
if kwargs.pop('copy', None) or (len(args) and args[-1]):
448448
new_values = new_values.copy()
449+
450+
if kwargs:
451+
raise TypeError('transpose() got an unexpected keyword '
452+
'argument "{0}"'.format(list(kwargs.keys())[0]))
453+
449454
return self._constructor(new_values, **new_axes).__finalize__(self)
450455

451456
def swapaxes(self, axis1, axis2, copy=True):
@@ -540,8 +545,12 @@ def swaplevel(self, i, j, axis=0):
540545
def rename(self, *args, **kwargs):
541546

542547
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
543-
copy = kwargs.get('copy', True)
544-
inplace = kwargs.get('inplace', False)
548+
copy = kwargs.pop('copy', True)
549+
inplace = kwargs.pop('inplace', False)
550+
551+
if kwargs:
552+
raise TypeError('rename() got an unexpected keyword '
553+
'argument "{0}"'.format(list(kwargs.keys())[0]))
545554

546555
if (com._count_not_none(*axes.values()) == 0):
547556
raise TypeError('must pass an index to rename')
@@ -1531,10 +1540,12 @@ def reindex_like(self, other, method=None, copy=True, limit=None):
15311540
-------
15321541
reindexed : same as input
15331542
"""
1534-
d = other._construct_axes_dict(method=method, copy=copy, limit=limit)
1543+
d = other._construct_axes_dict(axes=self._AXIS_ORDERS,
1544+
method=method, copy=copy, limit=limit)
1545+
15351546
return self.reindex(**d)
15361547

1537-
def drop(self, labels, axis=0, level=None, inplace=False, **kwargs):
1548+
def drop(self, labels, axis=0, level=None, inplace=False):
15381549
"""
15391550
Return new object with labels in requested axis removed
15401551
@@ -1708,11 +1719,15 @@ def reindex(self, *args, **kwargs):
17081719

17091720
# construct the args
17101721
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
1711-
method = com._clean_reindex_fill_method(kwargs.get('method'))
1712-
level = kwargs.get('level')
1713-
copy = kwargs.get('copy', True)
1714-
limit = kwargs.get('limit')
1715-
fill_value = kwargs.get('fill_value', np.nan)
1722+
method = com._clean_reindex_fill_method(kwargs.pop('method', None))
1723+
level = kwargs.pop('level', None)
1724+
copy = kwargs.pop('copy', True)
1725+
limit = kwargs.pop('limit', None)
1726+
fill_value = kwargs.pop('fill_value', np.nan)
1727+
1728+
if kwargs:
1729+
raise TypeError('reindex() got an unexpected keyword '
1730+
'argument "{0}"'.format(list(kwargs.keys())[0]))
17161731

17171732
self._consolidate_inplace()
17181733

@@ -1917,7 +1932,7 @@ def tail(self, n=5):
19171932
#----------------------------------------------------------------------
19181933
# Attribute access
19191934

1920-
def __finalize__(self, other, method=None, **kwargs):
1935+
def __finalize__(self, other, method=None):
19211936
"""
19221937
propagate metadata from other to self
19231938
@@ -3422,7 +3437,7 @@ def shift(self, periods=1, freq=None, axis=0, **kwds):
34223437

34233438
return self._constructor(new_data).__finalize__(self)
34243439

3425-
def slice_shift(self, periods=1, axis=0, **kwds):
3440+
def slice_shift(self, periods=1, axis=0):
34263441
"""
34273442
Equivalent to `shift` without copying data. The shifted data will
34283443
not include the dropped periods and the shifted axis will be smaller
@@ -4053,7 +4068,7 @@ def logical_func(self, axis=None, bool_only=None, skipna=None,
40534068
desc="Return the mean absolute deviation of the values "
40544069
"for the requested axis")
40554070
@Appender(_num_doc)
4056-
def mad(self, axis=None, skipna=None, level=None, **kwargs):
4071+
def mad(self, axis=None, skipna=None, level=None):
40574072
if skipna is None:
40584073
skipna = True
40594074
if axis is None:
@@ -4111,7 +4126,7 @@ def stat_func(self, axis=None, skipna=None, level=None, ddof=1,
41114126
desc="Return the compound percentage of the values for "
41124127
"the requested axis")
41134128
@Appender(_num_doc)
4114-
def compound(self, axis=None, skipna=None, level=None, **kwargs):
4129+
def compound(self, axis=None, skipna=None, level=None):
41154130
if skipna is None:
41164131
skipna = True
41174132
return (1 + self).prod(axis=axis, skipna=skipna, level=level) - 1

pandas/core/groupby.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -910,7 +910,7 @@ def nth(self, n, dropna=None):
910910

911911
return result
912912

913-
def cumcount(self, **kwargs):
913+
def cumcount(self, ascending=True):
914914
"""
915915
Number each item in each group from 0 to the length of that group - 1.
916916
@@ -955,7 +955,6 @@ def cumcount(self, **kwargs):
955955
956956
"""
957957
self._set_selection_from_grouper()
958-
ascending = kwargs.pop('ascending', True)
959958

960959
index = self._selected_obj.index
961960
cumcounts = self._cumcount_array(ascending=ascending)
@@ -1016,15 +1015,13 @@ def tail(self, n=5):
10161015
tail = obj[in_tail]
10171016
return tail
10181017

1019-
def _cumcount_array(self, arr=None, **kwargs):
1018+
def _cumcount_array(self, arr=None, ascending=True):
10201019
"""
10211020
arr is where cumcount gets its values from
10221021
10231022
note: this is currently implementing sort=False (though the default is sort=True)
10241023
for groupby in general
10251024
"""
1026-
ascending = kwargs.pop('ascending', True)
1027-
10281025
if arr is None:
10291026
arr = np.arange(self.grouper._max_groupsize, dtype='int64')
10301027

@@ -3094,7 +3091,7 @@ def filter(self, func, dropna=True, *args, **kwargs):
30943091
for name, group in gen:
30953092
object.__setattr__(group, 'name', name)
30963093

3097-
res = func(group)
3094+
res = func(group, *args, **kwargs)
30983095

30993096
try:
31003097
res = res.squeeze()

pandas/core/index.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ def __unicode__(self):
415415
quote_strings=True)
416416
return "%s(%s, dtype='%s')" % (type(self).__name__, prepr, self.dtype)
417417

418-
def to_series(self, **kwargs):
418+
def to_series(self):
419419
"""
420420
Create a Series with both index and values equal to the index keys
421421
useful with map for returning an indexer based on an index
@@ -1604,7 +1604,7 @@ def _get_nearest_indexer(self, target, limit):
16041604
left_indexer, right_indexer)
16051605
return indexer
16061606

1607-
def get_indexer_non_unique(self, target, **kwargs):
1607+
def get_indexer_non_unique(self, target):
16081608
""" return an indexer suitable for taking from a non unique index
16091609
return the labels in the same order as the target, and
16101610
return a missing indexer into the target (missing are marked as -1
@@ -3766,7 +3766,7 @@ def append(self, other):
37663766
return Index(new_tuples)
37673767

37683768
def argsort(self, *args, **kwargs):
3769-
return self.values.argsort()
3769+
return self.values.argsort(*args, **kwargs)
37703770

37713771
def repeat(self, n):
37723772
return MultiIndex(levels=self.levels,

pandas/core/internals.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ def delete(self, loc):
278278

279279
def apply(self, func, **kwargs):
280280
""" apply the function to my values; return a block if we are not one """
281-
result = func(self.values)
281+
result = func(self.values, **kwargs)
282282
if not isinstance(result, Block):
283283
result = make_block(values=_block_shape(result), placement=self.mgr_locs,)
284284

pandas/core/panel.py

+18-5
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,12 @@ def _init_data(self, data, copy, dtype, **kwargs):
145145
if dtype is not None:
146146
dtype = self._validate_dtype(dtype)
147147

148-
passed_axes = [kwargs.get(a) for a in self._AXIS_ORDERS]
148+
passed_axes = [kwargs.pop(a, None) for a in self._AXIS_ORDERS]
149+
150+
if kwargs:
151+
raise TypeError('_init_data() got an unexpected keyword '
152+
'argument "{0}"'.format(list(kwargs.keys())[0]))
153+
149154
axes = None
150155
if isinstance(data, BlockManager):
151156
if any(x is not None for x in passed_axes):
@@ -471,7 +476,11 @@ def get_value(self, *args, **kwargs):
471476
raise TypeError('There must be an argument for each axis, you gave'
472477
' {0} args, but {1} are required'.format(nargs,
473478
nreq))
474-
takeable = kwargs.get('takeable')
479+
takeable = kwargs.pop('takeable', None)
480+
481+
if kwargs:
482+
raise TypeError('get_value() got an unexpected keyword '
483+
'argument "{0}"'.format(list(kwargs.keys())[0]))
475484

476485
if takeable is True:
477486
lower = self._iget_item_cache(args[0])
@@ -506,7 +515,11 @@ def set_value(self, *args, **kwargs):
506515
raise TypeError('There must be an argument for each axis plus the '
507516
'value provided, you gave {0} args, but {1} are '
508517
'required'.format(nargs, nreq))
509-
takeable = kwargs.get('takeable')
518+
takeable = kwargs.pop('takeable', None)
519+
520+
if kwargs:
521+
raise TypeError('set_value() got an unexpected keyword '
522+
'argument "{0}"'.format(list(kwargs.keys())[0]))
510523

511524
try:
512525
if takeable is True:
@@ -607,7 +620,7 @@ def _needs_reindex_multi(self, axes, method, level):
607620
""" don't allow a multi reindex on Panel or above ndim """
608621
return False
609622

610-
def dropna(self, axis=0, how='any', inplace=False, **kwargs):
623+
def dropna(self, axis=0, how='any', inplace=False):
611624
"""
612625
Drop 2D from panel, holding passed axis constant
613626
@@ -1065,7 +1078,7 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
10651078

10661079
return self._construct_return_type(result, axes)
10671080

1068-
def _construct_return_type(self, result, axes=None, **kwargs):
1081+
def _construct_return_type(self, result, axes=None):
10691082
""" return the type for the ndim of the result """
10701083
ndim = getattr(result,'ndim',None)
10711084

pandas/core/series.py

+5
Original file line numberDiff line numberDiff line change
@@ -2374,6 +2374,11 @@ def dropna(self, axis=0, inplace=False, **kwargs):
23742374
inplace : boolean, default False
23752375
Do operation in place.
23762376
"""
2377+
kwargs.pop('how', None)
2378+
if kwargs:
2379+
raise TypeError('dropna() got an unexpected keyword '
2380+
'argument "{0}"'.format(list(kwargs.keys())[0]))
2381+
23772382
axis = self._get_axis_number(axis or 0)
23782383
result = remove_na(self)
23792384
if inplace:

pandas/tests/test_generic.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,26 @@ def test_split_compat(self):
369369
self.assertTrue(len(np.array_split(o,5)) == 5)
370370
self.assertTrue(len(np.array_split(o,2)) == 2)
371371

372+
def test_unexpected_keyword(self): # GH8597
373+
from pandas.util.testing import assertRaisesRegexp
374+
375+
df = DataFrame(np.random.randn(5, 2), columns=['jim', 'joe'])
376+
ca = pd.Categorical([0, 0, 2, 2, 3, np.nan])
377+
ts = df['joe'].copy()
378+
ts[2] = np.nan
379+
380+
with assertRaisesRegexp(TypeError, 'unexpected keyword'):
381+
df.drop('joe', axis=1, in_place=True)
382+
383+
with assertRaisesRegexp(TypeError, 'unexpected keyword'):
384+
df.reindex([1, 0], inplace=True)
385+
386+
with assertRaisesRegexp(TypeError, 'unexpected keyword'):
387+
ca.fillna(0, inplace=True)
388+
389+
with assertRaisesRegexp(TypeError, 'unexpected keyword'):
390+
ts.fillna(0, in_place=True)
391+
372392
class TestSeries(tm.TestCase, Generic):
373393
_typ = Series
374394
_comparator = lambda self, x, y: assert_series_equal(x,y)
@@ -602,7 +622,7 @@ def test_interp_scipy_basic(self):
602622
result = s.interpolate(method='slinear')
603623
assert_series_equal(result, expected)
604624

605-
result = s.interpolate(method='slinear', donwcast='infer')
625+
result = s.interpolate(method='slinear', downcast='infer')
606626
assert_series_equal(result, expected)
607627
# nearest
608628
expected = Series([1, 3, 3, 12, 12, 25])

0 commit comments

Comments
 (0)