• Team FastApp

Python3.8 - Position-Only Parameters

Let's discuss something very interesting and useful improvement introduced in python3.8 (PEP 570), the position-only parameters, This is a function parameter syntax `/ ` to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments.


def func(pos1, pos2, /, pos_or_kw1, pos_or_kw2, *, kw1, kw2):

In above function parameter are explained as:

pos1, pos2 - position-only parameters

/ - tells us that the parameters appearing before this sign are position-only.

pos_or_kw1, pos_or_kw2 - position-or-keyword parameters

* - tells us that the parameters appearing before this sign are of position-or-keyword type.

kw1, kw2 - keyword-only parameters

  • With positional-or-keyword parameters, the mix of calling conventions is not always desirable. Addition of / marker for positional-only arguments improves the language’s consistency.

  • For the cases where sequence of parameters to the function matters a lot and can not be compromised.

  • There are some cases where parameter names does not really matter and provide no true meaning.

e.g. min(arg1, arg2)

  • Python library authors would have the flexibility to change the name of positional-only parameters without breaking callers.

Note: Do not use position-only parameters when parameter names have meaning and the function definition is more understandable by being explicit with names, go with keyword-only parameters instead.

e.g. namedtuple(typenames, field_names, …)

How to use position-only keywords:

def pow(x, y, /, mod=None):
    r = x ** y
    if mod is not None:
        r %= mod
    return r

different functions calls for `pow` would be like below style:

>>> pow(3, 12)  # works
>>> pow(3, 12, 13)  # works
>>> pow(3, 12, mod=12)  # works
>>> pow(x=3, y=12)  # invalid, raises TypeError
>>> pow(2, y=12)  # invalid, raises TypeError
59 views0 comments

Recent Posts

See All

Django Queryset with an unusual operation "Merge"

Consider, we have a StudentHistory model defined as: class StudentHistory(models.Model): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=150, b

Python3.6 - What the f-string !

In Python 3.6, there is a new way to format the strings, which helps the user in faster coding, less googling, and better readable code. Which was previously a little tedious by using %-format or even

Python3.8 - The Walrus Operator

In Python 3.8, we will be able to use assignment as a part of the large expressions. It has a new syntax := Examples: 1. if-else block Python3.8 my_string = "second" if (my_var := len(my_string)) > 5:


©2020 by FastApp. Created with <3