Do all keyword arguments have to written after all the positional arguments?


#1

Question

When writing a function in Python, do we have to place all keyword arguments so that they come after all the positional arguments in the function definition?

Answer

Yes, keyword arguments, which are assigned some value in the definition, must be written after all the positional arguments.

If we do not follow this rule, then Python will give us an error message.

Example code

# This would cause an error, because
# arg1 is a keyword argument but was placed 
# before arg2, a positional argument.
def func(arg1=10, arg2, arg3=30):
  return arg1 + arg2 + arg3

print(func(20))

# All keyword arguments must 
# follow all the positional arguments, so
# this updated function would work.
def fixed_func(arg2, arg1=10, arg3=30):
  return arg1 + arg2 + arg3

print(fixed_func(20)) # This will print 60