1. The walrus operator
Walrus operator is the coolest feature that was added in the Python 3.8 update python codes.
start = input("Do you want to start(y/n)?")
print(start == "y")
# double parentheses here
# using parentheses with the walrus operator is encouraged
print((start := input("Do you want to start(y/n)?")) == "y")
# With parentheses
if (sum := 10 + 5) > 10:
print(sum) #return 15
# Without parentheses
if sum := 10 + 5 > 10:
print(sum) #return True
a = [1, 2, 3, 4]
if (n := len(a)) > 3:
print(f"List is too long ({n} elements, expected <= 3)")
2. Positional-only parameters
There is a new function parameter syntax /
to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments.
def name(positional_only_parameters, /, positional_or_keyword_parameters, *, keyword_only_parameters):
>>> def f(a,b,/,**kwargs):
... print(a,b,kwargs)
...
>>> f(10,20,a=1,b=2,c=3)
10 20 {'a': 1, 'b': 2, 'c': 3}
def do_nothing(a, b, /):
print(a, b)
>>> do_nothing(1, 2)
1, 2
>>> do_nothing(a=1, b=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: do_nothing() takes no keyword arguments