Skip to content

Commit 540e85e

Browse files
committed
REF: Undelete keywordonly.py module
1 parent 71e3ccc commit 540e85e

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

nibabel/keywordonly.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
""" Decorator for labeling keyword arguments as keyword only
2+
"""
3+
4+
from functools import wraps
5+
6+
7+
def kw_only_func(n):
8+
""" Return function decorator enforcing maximum of `n` positional arguments
9+
"""
10+
def decorator(func):
11+
@wraps(func)
12+
def wrapper(*args, **kwargs):
13+
if len(args) > n:
14+
raise TypeError(
15+
'{0} takes at most {1} positional argument{2}'.format(
16+
func.__name__, n, 's' if n > 1 else ''))
17+
return func(*args, **kwargs)
18+
return wrapper
19+
return decorator
20+
21+
22+
def kw_only_meth(n):
23+
""" Return method decorator enforcing maximum of `n` positional arguments
24+
25+
The method has at least one positional argument ``self`` or ``cls``; allow
26+
for that.
27+
"""
28+
return kw_only_func(n + 1)

nibabel/tests/test_keywordonly.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
""" Test kw_only decorators """
2+
3+
from ..keywordonly import kw_only_func, kw_only_meth
4+
5+
from nose.tools import assert_equal
6+
from nose.tools import assert_raises
7+
8+
9+
def test_kw_only_func():
10+
# Test decorator
11+
def func(an_arg):
12+
"My docstring"
13+
return an_arg
14+
assert_equal(func(1), 1)
15+
assert_raises(TypeError, func, 1, 2)
16+
dec_func = kw_only_func(1)(func)
17+
assert_equal(dec_func(1), 1)
18+
assert_raises(TypeError, dec_func, 1, 2)
19+
assert_raises(TypeError, dec_func, 1, akeyarg=3)
20+
assert_equal(dec_func.__doc__, 'My docstring')
21+
22+
@kw_only_func(1)
23+
def kw_func(an_arg, a_kwarg='thing'):
24+
"Another docstring"
25+
return an_arg, a_kwarg
26+
assert_equal(kw_func(1), (1, 'thing'))
27+
assert_raises(TypeError, kw_func, 1, 2)
28+
assert_equal(kw_func(1, a_kwarg=2), (1, 2))
29+
assert_raises(TypeError, kw_func, 1, akeyarg=3)
30+
assert_equal(kw_func.__doc__, 'Another docstring')
31+
32+
class C(object):
33+
34+
@kw_only_meth(1)
35+
def kw_meth(self, an_arg, a_kwarg='thing'):
36+
"Method docstring"
37+
return an_arg, a_kwarg
38+
c = C()
39+
assert_equal(c.kw_meth(1), (1, 'thing'))
40+
assert_raises(TypeError, c.kw_meth, 1, 2)
41+
assert_equal(c.kw_meth(1, a_kwarg=2), (1, 2))
42+
assert_raises(TypeError, c.kw_meth, 1, akeyarg=3)
43+
assert_equal(c.kw_meth.__doc__, 'Method docstring')

0 commit comments

Comments
 (0)