Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading