Home > Net >  What is the purpose of default arguments for forced keyword arguments in Python?
What is the purpose of default arguments for forced keyword arguments in Python?

Time:06-30

I've come across a package which consistently has functions of the form:

def function(
  arg1,
  arg2,
  *,
  arg3=None,
  arg4=None,
  ...
  argN=None
)

I'm trying to understand the purpose of forcing the keyword arguments if they have defaults. In particular, there are two scenarios:

Scenario 1: The keyword arguments are not provided. Without the defaults, this would throw an error, but with the defaults, the function has the same exact behavior it would have without the forcing.

Scenario 2: The keyword arguments are provided, again yielding the same exact behavior it would have without the forcing.

Is there something I am missing/not understanding with this approach? All of the forced arguments have defaults.

Thanks!

CodePudding user response:

It doesn't force you to provide the arguments, but it forces you to explicitly provide the keyword argument name when passing it. So function(1, 2, 3) won't work because you have to specify arg3 explicitly, i.e. function(1, 2, arg3=3). Apart from that, the behavior stays the same.

It is commonly used, when the developer realizes that without explicitly stating the name of the keyword argument for the given function can/will confuse the developer who reads the code later.

  • Related