Python error invalid syntax for method arguments

In python you can have error related to named/keyword arguments like:

def method(arg1, arg_list: List[str] = None):
                                               ^
SyntaxError: invalid syntax

This error most probably is related to python version incompability. In other words this code is valid Python 3 code but invalid in Python 2. In order to fix the problem you have several options like:

  • migrate your code to Python 3
  • workaround the problem

Migrating or porting your code to Python 3 is tough but important job(since Python 2 support ends in 2020). At least you can try to run your program in Python 3 vritual environment.

In some cases it's easier to workaround the problem by:

In python 3

def method(arg1, arg2=1, arg3=2):
    pass

In python 2

def method(arg1, **kwargs):
    arg2 = kwargs.pop('arg2', 1) 
    arg3 = kwargs.pop('arg3', 2) 

The idea is simple - get arguments from kwargs if not then use default values.