Skip to content

Commit 826730c

Browse files
author
Joost Kranendonk
committed
simplify .str.replace TypeError reraising and test
1 parent 90779ce commit 826730c

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

pandas/core/strings.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,13 @@ def _map(f, arr, na_mask=False, na_value=np.nan, dtype=object):
170170
except (TypeError, AttributeError) as e:
171171
# Reraise the exception if callable `f` got wrong number of args.
172172
# The user may want to be warned by this, instead of getting NaN
173-
re_error = (r'(takes|(missing)) (no|(exactly )?\d+) '
174-
r'(?(2)required )(positional )?arguments?')
175-
if len(e.args) >= 1 and re.search(re_error, e.args[0]):
173+
if compat.PY2:
174+
p_err = r'takes (no|(exactly|at (least|most)) ?\d+) arguments?'
175+
else:
176+
p_err = (r'((takes)|(missing)) (?(2)from \d+ to )?\d+ '
177+
r'(?(3)required )positional arguments?')
178+
179+
if len(e.args) >= 1 and re.search(p_err, e.args[0]):
176180
raise e
177181

178182
def g(x):

pandas/tests/test_strings.py

+15-7
Original file line numberDiff line numberDiff line change
@@ -446,15 +446,23 @@ def test_replace_callable(self):
446446
exp = Series(['foObaD__baRbaD', NA])
447447
tm.assert_series_equal(result, exp)
448448

449-
# test with wrong number of arguments
450-
repl = lambda m, bad: None
451-
re_msg = "^<lambda>\(\) missing 1 required positional argument: 'bad'$"
452-
with tm.assertRaisesRegexp(TypeError, re_msg):
453-
values.str.replace('a', repl)
449+
# test with wrong number of arguments, raising an error
450+
if compat.PY2:
451+
p_err = r'takes (no|(exactly|at (least|most)) ?\d+) arguments?'
452+
else:
453+
p_err = (r'((takes)|(missing)) (?(2)from \d+ to )?\d+ '
454+
r'(?(3)required )positional arguments?')
454455

455456
repl = lambda: None
456-
re_msg = '^<lambda>\(\) takes 0 positional arguments but 1 was given$'
457-
with tm.assertRaisesRegexp(TypeError, re_msg):
457+
with tm.assertRaisesRegexp(TypeError, p_err):
458+
values.str.replace('a', repl)
459+
460+
repl = lambda m, x: None
461+
with tm.assertRaisesRegexp(TypeError, p_err):
462+
values.str.replace('a', repl)
463+
464+
repl = lambda m, x, y=None: None
465+
with tm.assertRaisesRegexp(TypeError, p_err):
458466
values.str.replace('a', repl)
459467

460468
# test regex named groups

0 commit comments

Comments
 (0)