Skip to content Skip to sidebar Skip to footer

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 '', line 1 def f(*args, option=None):

Solution 1:

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:

defmy_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 isNone:
        # max doesn't support key=Nonereturnmax(*args)
    else:
        returnmax(*args, key=key)

Solution 2:

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:

deff(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:

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

Or you could upgrade to Python 3.

Solution 3:

That is not supported in python 2, where *args must appear after any named/defaulted arguments in a function call signature.

The appropriate way to do that thing is to upgrade to python 3, where it is supported.

>>>deff(*args, option=None):...print(args, option)...>>>f('not_option')
('not_option',) None
>>>f(1, 2, option='beast mode on!!!')
(1, 2) beast mode on!!!

Solution 4:

In case it would help someone, i still had the error with python 3.X installed...

I am using a windows, and launched my code by right clicking my .py file and selecting "Edit with IDLE".

enter image description here

Actually, i noticed my version of IDLE was running on python 2.X. At least... when clicking on the first "Edit with IDLE" button...

Just click the second button and you'll find your solution...

enter image description here

I guess I have both versions installed :|

Post a Comment for "Python Syntax Error *args With Optional Arg"