• 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
79 views0 comments

Recent Posts

See All

This blog post aims to make django querying simple for the developers who are new in the django world. Keep reading :) What is a django query? A django query is an expression which can be used to writ

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