tags:

views:

74

answers:

3

What is the best style for a Python method that requires the keyword argument 'required_arg':

def test_method(required_arg, *args, **kwargs):


def test_method(*args, **kwargs):
    required_arg = kwargs.pop('required_arg')
    if kwargs:
        raise ValueError('Unexpected keyword arguments: %s' % kwargs)

Or something else? I want to use this for all my methods in the future so I'm kind of looking for the best practices way to deal with required keyword arguments in Python methods.

+7  A: 

The first method by far. Why duplicate something the language already provides for you?

Optional arguments in most cases should be known (only use *args and **kwargs when there is no possible way of knowing the arguments). Denote optional arguments by giving them their default value (def bar(foo = 0) or def bar(foo = None)). Watch out for the classic gotcha of def bar(foo = []) which doesn't do what you expect.

Yann Ramin
The first method also allows me to use a positional argument when I call the function. The second requires me to use a named argument.
gnibbler
+1  A: 

The first method offers you the opportunity to give your required argument a meaningful name; using *args doesn't. Using *args is great when you need it, but why give up the opportunity for clearer expression of your intent?

Pierce
A: 

If you don't want arbitrary keyword arguments, leave out the ** parameter. For the love of all that is holy, if you have something that is required, just make it a normal argument.

Instead of this:

def test_method(*args, **kwargs):
    required_arg = kwargs.pop('required_arg')
    if kwargs:
        raise ValueError('Unexpected keyword arguments: %s' % kwargs)

Do this:

def test_method(required_arg, *args):
    pass
dash-tom-bang