Positional Only, Keyword Only, and Standard Argument in Python

Jahidul Hasan Hemal
2 min readJun 25, 2021

--

Source: https://www.renatocandido.org/2020/10/7-python-code-examples-for-everyday-use/

We have been using arguments for a long time. Many of us already familiar with this, but this post is dedicated to those who started their journey recently.

First of all, let’s declare a simple function with an argument. In this case, greetings is a function that will greet a user by his/her name from the parameter.

We are already familiar with this kind of parameter. What if we want something like complex. Let’s type help(float) on our python interpreter and let’s see what happens. (FYI press q if you wanna get yourself out from the help).

We can see that there are something like ‘/’ after x=0 and self for float and abs respectively. Why float uses an argument like this. Let’s examine.

For our greetings function it doesn’t matter whether we write “Hemal” or name=“Hemal”. On the other hand float(x=3) raises an error that float() takes no keyword arguments. This is actually happening because of the positional argument. The slash after the arguments make the x, a positional argument. That means we can only pass the value here. Let’s change our greetings with a positional argument and let’s see what happens.

So, adding a slash after some arguments will make them positional only. What if I want to pass value using the keyword. Then, we have to use an asterisk (*) before arguments. Let’s change our greetings with a keyword-only argument.

We can use either slash or asterisk key after or before to make an argument positional or keyword. Any parameter after the slash (/) or before the asterisk (*) will be the standard argument. They could be either positional or keyword.

Now, I guess we know how the positional and keyword arguments are created. What if we want them both in our function. Let’s update our greetings function to clarify that.

The more you know python, the more you will be amazed. It has so many awesome features that would make you fell for it. If you want to get more details about Special Parameters, you can read the Python Documentation.

--

--

Jahidul Hasan Hemal
Jahidul Hasan Hemal

Written by Jahidul Hasan Hemal

A goddamn marvel of modern science. An open-source enthusiast and an optimist who loves to read and watch movies and is trying to learn how to write.

Responses (2)