DEV Community

Pystar
Pystar

Posted on

The Shiny New Parts of Python.

This series is about the latest additions to the Python language which at the time of writing is Python 3.8. To kick start the series, this post will focus on Positional-only parameters.
Prior to Python 3.8, some inbuilt functions allowed for positional-only arguments in functions but this feature could not be used in code by developers. The addition of the ability to specify positional-only arguments in function definitions is a new enhancement to the Python language syntax and is based on [PEP 570] https://www.python.org/dev/peps/pep-0570/).
Prior to Python 3.8, a function definition looked like:

but now with the addition of positional-only arguments, a function definition looks like:

Explainer

  • The '/' marker specifies that all parameters to its left can only be passed by position during the function call as against the normal position-or-keyword argument passing. Its then followed by positional_or_keyword_parameters and a '*' marker which specifies the end of all positional parameters and then followed by keyword_only_parameters.
  • If '/' is not specified in the function definition, that function does not accept any positional-only arguments.
  • Once a positional-only parameter is specified with a default, the following positional-only and positional-or-keyword parameters need to have defaults as well.

Examples

Playground

Advantages of positional-only parameters

  • Speed and performance: The parsing and handling of positional-only parameters is faster.
  • Logical ordering: positional-only arguments enforces the order in which arguments are mapped to parameters in the the function definition during a function call.
  • Better API design. The new syntax will enable library authors to further control how their API can be called. It will allow designating which parameters must be called as positional-only, while preventing them from being called as keyword arguments.

When and where can you use positional-only parameters?

  • Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order.
  • Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.

Top comments (0)