There are a number of new Python features have been added to the version 3.8. However, some of the features are simply awesome. This article will outline the new features of Python 3.8 which you should be familiar with.
It is also known as walrus operator.
It assigns values to variables as part of an expression without initialising them up front.
if (my_variable := get_input()) == 100:
perform_action_as_my_variable_is_hundred();
Here, the variable “my_variable” has been assigned a value.
This feature is unavailable in list comprehensions and other expression contexts. It is only available in statement forms.
If you want to call a function in Python that accepts parameters then you can pass the arguments by position or by keyword. But what if we want to restrict the callers of our API to only call our function by passing in parameters by position?
The positional-only parameter functionality solves it:
def add(a, b, c, d=None, /):
x = a+b+c
if d is not None:
x = x+d
return x
As a consequence, add(1,2,3) and add(1,2,3,4) are valid calls/
However, add(a=1,b=2,c=3) or add(1,2,3,d=4) are all invalid calls.
The specifier = can be added to the f-strings now.
f -strings are in the form of f'{expr=}'
Notice the ‘=’. The equal sign can help us evaluate the expression:
input = 100
output = 50
print(f'{input-output=}')
Would print 100-50=50
.
This makes debugging really easy as the function is evaluated and the output is produced.
functools.lru_cache is great for recursive calls. A dictionary is used to cache the results. We can now add the functools.lru_cache() decorator
@lru_cache
def my_function(input):
some io bound or recursive function
A number of times, I wanted to reverse an iterator. Luckily, reversed(input) is now added for Dict and dictviews objects. The *input *argument in the reversed function must have a reversed() function, OR it must have the len() and getitem() method whereby the arguments start at 0.
Photo by Nick Fewings on Unsplash
**Read the ****changelog **for complete list
If you want to understand Python from start to end then read this article: Everything About Python — Beginner To Advanced
This article provided a summary of the awesome Python 3.8 features.
Hope it helps.
#python