Positional-only Arguments
As you continue to explore Python, you'll come across the concept of function arguments. In Python, there are different ways to pass arguments to a function. We can have default arguments, keyword arguments, and positional arguments. But there's a specific kind of argument that can only be supplied by position and not by keyword, known as positional-only arguments.
Starting from Python 3.8, there is a special syntax
/
in function definitions to indicate that some arguments are positional-only. Positional-only arguments appear before a /
in the function definition.Consider this function that adds three numbers:
def add_numbers(a, b, c):
return a + b + c
We can call this function by providing arguments in the order that they're defined, which is by position:
print(add_numbers(10, 20, 30))
# outputs: 60
And we can also call it using the names of the arguments, which is by keyword:
print(add_numbers(a=10, b=20, c=30))
# outputs: 60
But what if we want to make sure that some arguments are always provided in a specific order? That's where positional-only arguments come into play. Let's modify the
add_numbers
function to make a
and b
positional-only:def add_numbers(a, b, /, c):
return a + b + c
Now we can still call this function with arguments by position:
print(add_numbers(10, 20, 30)) # 60
print(add_numbers(a=10, b=20, c=30)) # TypeError
print(add_numbers(10, 20, c=30)) # 60
Yet, if we try to call it with the positional-only arguments as keyword arguments, we'll get a
TypeError
. In this case, we must provide a
and b
by position. The argument c
can be supplied either by position or keyword:So, the syntax for positional-only arguments is:
- The positional-only arguments come before a
/
in the function definition.
- If
/
is present in the function definition, arguments before it are positional-only.
- Positional-only arguments can't be passed by keyword.
- Arguments after
/
can be passed by position or keyword.
Are there built-in functions in Python that have positional-only arguments?
Yes, many built-in Python functions do have positional-only arguments. The
abs()
function, for instance, is a good example:help(abs)
# Help on built-in function abs in module builtins:
# abs(x, /)
# Return the absolute value of the argument.
abs(-6) # 6
abs(x=-6) # TypeError: abs() takes no keyword arguments
The parameter
x
in abs
is a positional-only argument and when we try to pass it to the function call as a keyword argument, the program throws a TypeError
.