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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With