8 Aug 2019

positional-only-parameter in Python

In recent release of python 3.8, new feature  positional-only-parameter is introduced.
I am going to cover motivations behind positional-only-parameter.
There are already some functions which takes positional arguments only like range(), id(), len().

def add(x, y):
    return x+y


Motivations:
1. Programmer does not want to expose the arguments to caller.
  in add(x=3, y=4)  x and y directly exposed to caller.

2. Tomorrow if programmer want to refactor the code and changes parameters name then existing call to the function will break.
if add(x, y) is changed to add(a, b) then add(x=3, y=4) will break. As a result of this programmer has to maintain the parameter's name.

3. add(*args, **kwargs) is not clear to caller as *args can take number of arguments without specifying any meaning of those.

4 When subclass overrides method of base class and changes the name of parameters.
class Sup(object):
  def add_one(self, x)
    return x+1

class Sub(Sup):
  def add_one(self, y)
    return y+1

Sub().add_one(x=1)

which results in error:
TypeError: add_one() got an unexpected keyword argument 'x'

5. Maintaining the logical order of arguments.
def get_args(a, b, c):
   return (a, b, c)

get_args(a=1, c=3, b=2)
get_args(c=9, a=7, b=5)


We can clearly see order of arguments is not followed in calls. positional-only-parameter will allow to maintain the order of calls.


Hope you like this article, Thanks for reading.