Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

What are positional-only arguments in Python?

Aiyan Tufail

Positional-only arguments are a feature in Python 3.8 used for specifying positional only parameters with the ‘/’ marker in function definitions.

Why were positional-only arguments introduced?

Keyword-only arguments are another attribute of Python functions that have been available since Python 3.0. These arguments are specified using the ‘*’ marker. They prompt the user to state the keyword used in the already defined function when making a call to the same function. Therefore, the introduction of positional-only arguments improves the flexibility of the language in the following ways:

  • Adds the ability to rename parameters which, in the case of keyword-only arguments, would be a breaking change.

  • Forces users to call functions by specifying arguments by their position only. Here, the name of the argument provides no intrinsic value (such functions include min() and max() among others).

How to use positional-only arguments

The ‘/’ marker needs to be added after all those arguments to be specified as positional-only in the function definition. The generic form of a function consisting of positional-only, keyword-only, and either of the previous two would look like:

Code

def equation(x , y , / , z):
    return x * y + z
#The arguments to the left of '/' (in this case x and y) can only be passed postionally whereas the argument to the right of '/' can be passed positionally or with a keyword 

print(equation(2 , 3 , 5)) #all three arguments are positional 
print(equation(2 , 3 , z = 5)) #the first two arguments are positional while the third is a keyword argument

Guidelines for when to use positional-only arguments

  • When the arguments of a function have no explicit meaning, there is no need to specify a name.

  • When there are only a few arguments that will always be passed in the same order.

RELATED TAGS

python
community creator
RELATED COURSES

View all Courses

Keep Exploring