Python version 3.8 includes the ability to make certain arguments positional-only. This means you can make those arguments not usable with keywords.
For example, the len
function no longer accepts the keyword argument obj
, which is the object to check. So, this no longer works:
items = [1, 2, 3, 4]
print(len(obj=items))
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: len() takes no keyword arguments
len_obj.py
Instead, you’ll need to do this:
items = [1, 2, 3, 4]
print(len(items))
# 4
len_positional.py
This change was originally proposed in PEP 570 and is available for you to use right away.
This can be done using the new /
syntax, like this:
def func(a, b, /, c):
print(a, b, c)
func_positional_only.py
Here, you can only give a
and b
as positional arguments. c
can be given as either a positional argument or a keyword argument. If you try to give either a
or b
as keyword arguments, you’ll get an error like this:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: func() got some positional-only arguments passed as keyword arguments: 'a, b'
This change can make your code more readable as it requires you to make your code cleaner and more concise.
There are a few other new features in Python 3.8, such as the walrus operator (see this article by Jonathan Hsu and the =
specifier for f-strings.
Positional-only arguments are simple but useful, as Python should be.
#python #programming #development