2

Python has support for postional only and keyword only arguments

  1. Positional only arguments
    def postional_only_func(a,b,/):
        ...
    
  2. Keyword only arguments
    def keyword_only_func(*,a,b):
        ...
    

But, what are its practical use case when writing a function? Is it just to make code more readable?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
ShrAwan Poudel
  • 164
  • 1
  • 8

1 Answers1

3

Both of these features were added to make writing certain functions easier. IF you want to read the full rational and motivation, you should read the corresponding PEPs:

  1. PEP 570 – Python Positional-Only Parameters

  2. PEP 3102 – Keyword-Only Arguments

For positional only, here are concrete examples for use-cases, using examples from the built-in functions:

There are functions with other interesting semantics:

  • range(), an overloaded function, accepts an optional parameter to the left of its required parameter. [4]
  • dict(), whose mapping/iterator parameter is optional and semantically must be positional-only. Any externally visible name for this parameter would occlude that name going into the **kwarg keyword variadic parameter dict. [3]

One can emulate these semantics in Python code by accepting (*args, **kwargs) and parsing the arguments manually. However, this results in a disconnect between the function definition and what the function contractually accepts. The function definition does not match the logic of the argument handling.

And for keyword-only arguments it says the following regarding motivation:

There are often cases where it is desirable for a function to take a variable number of arguments. The Python language supports this using the ‘varargs’ syntax (*name), which specifies that any ‘left over’ arguments be passed into the varargs parameter as a tuple.

One limitation on this is that currently, all of the regular argument slots must be filled before the vararg slot can be.

This is not always desirable. One can easily envision a function which takes a variable number of arguments, but also takes one or more ‘options’ in the form of keyword arguments. Currently, the only way to do this is to define both a varargs argument, and a ‘keywords’ argument (**kwargs), and then manually extract the desired keywords from the dictionary.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172