Skip to content

Commit

Permalink
Add no_positional decorator helper for planned API
Browse files Browse the repository at this point in the history
This allows us to design the APIs so that they only take keyword
arguments to make it easier and more explicit for users.

Refs #361
  • Loading branch information
sigmavirus24 committed May 16, 2018
1 parent b9806f4 commit c7b1f61
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
23 changes: 23 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,26 @@ def test_get_password_runtime_error_suppressed(
assert len(recwarn) == 1
warning = recwarn.pop(UserWarning)
assert 'fail!' in str(warning)


def test_no_positional_on_method():
class T(object):
@utils.no_positional(allow_self=True)
def __init__(self, foo=False):
self.foo = foo

with pytest.raises(TypeError):
T(1)

t = T(foo=True)
assert t.foo

def test_no_positional_on_function():
@utils.no_positional()
def t(foo=False):
return foo

with pytest.raises(TypeError):
t(1)

assert t(foo=True)
28 changes: 28 additions & 0 deletions twine/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,31 @@ def get_password(system, username, cli_value, config):
username,
),
)


def no_positional(allow_self=False):
"""A decorator that doesn't allow for positional arguments.
:param bool allow_self:
Whether to allow ``self`` as a positional argument.
"""
def reject_positional_args(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
allowed_positional_args = 0
if allow_self:
allowed_positional_args = 1
received_positional_args = len(args)
if received_positional_args > allowed_positional_args:
function_name = function.__name__
verb = 'were' if received_positional_args > 1 else 'was'
raise TypeError(('{}() takes {} positional arguments but {} '
'{} given').format(
function_name,
allowed_positional_args,
received_positional_args,
verb,
))
return function(*args, **kwargs)
return wrapper
return reject_positional_args

0 comments on commit c7b1f61

Please sign in to comment.