Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python syntax error *args with optional arg

Why is this a syntax error?? What is the appropriate way to do this thing?

>>> def f(*args, option=None):
  File "<stdin>", line 1
    def f(*args, option=None):
                      ^
SyntaxError: invalid syntax
like image 674
Him Avatar asked Dec 11 '22 17:12

Him


2 Answers

Python 2 doesn't have keyword-only argument support. If you really want your Python 2 function to have arguments that can only be passed by keyword, you need to take **kwargs and validate the keyword arguments yourself:

def my_max(*args, **kwargs):
    '''Emulate the built-in max, including the keyword-only key argument.'''
    key = kwargs.pop('key', None)
    if kwargs:
        raise TypeError('my_max() got an unexpected keyword argument {!r}'.format(next(iter(kwargs))))
    if key is None:
        # max doesn't support key=None
        return max(*args)
    else:
        return max(*args, key=key)
like image 82
user2357112 supports Monica Avatar answered Dec 13 '22 08:12

user2357112 supports Monica


In Python 2, all positional arguments must come before any *args argument. In Python 3, your current syntax is legal, creating option as a "keyword-only" argument.

So, your options are to change the order of the arguments:

def f(option=None, *args):
    ...

This would require you to provide an option argument if you wanted to provide any additional arguments though, which may not be what you want.

Another option would be to use **kwargs syntax to catch keyword arguments passed to the function. You can check if it has option (and not any other unexpected keywords) without naming it as a positional argument:

def f(*args, **kwargs):
    option = kwargs.pop("option", None)
    if kwargs:
        raise TypeError("unexpected keyword arguments found: {}".format(kwargs))
    ...

Or you could upgrade to Python 3.

like image 30
Blckknght Avatar answered Dec 13 '22 06:12

Blckknght