What's New Flashcards
Release date
October 14th, 2019
:=
1) what is this?
2) what does it do?
3) ex.
1) this is a new syntax called the “walrus operator”
2) assigns values to variables as part of a larger expression.
3)
if (n := len(a)) > 10: print(f”List is too long ({n} elements, expected <= 10)”)
:=
A similar benefit arises during regular expression matching where match objects are needed twice, once to test whether a match occurred and another to extract a subgroup:
Ex.
discount = 0.0
if (mo := re.search(r’(\d+)% discount’, advertisement)): discount = float(mo.group(1)) / 100.0
:=
The operator is also useful with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop:
Ex.
# Loop over fixed length blocks while (block := f.read(256)) != '': process(block)
:=
Another motivating use case arises in list comprehensions where a value computed in a filtering condition is also needed in the expression body.
Ex.
[clean_name.title() for name in names
if (clean_name := normalize(‘NFC’, name)) in allowed_names]
Recommendation for :=
Try to limit use of the walrus operator to clean cases that reduce complexity and improve readability.
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.
This is the same notation shown byhelp()for C functions annotated with Larry Hastings’Argument Clinictool.
Positional Only Parameters example
In the following example, parametersaandbare positional-only, whilecordcan be positional or keyword, andeorfare required to be keywords:
def f(a, b, /, c, d, *, e, f): print(a, b, c, d, e, f)
The following is a valid call:
f(10, 20, 30, d=40, e=50, f=60)
However, these are invalid calls:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument
Use case for Positional Only Parameters
One use case for this notation is that it allows pure Python functions to fully emulate behaviors of existing C coded functions. For example, the built-inpow()function does not accept keyword arguments:
def pow(x, y, z=None, /): "Emulate the built in pow() function" r = x ** y return r if z is None else r%z
Pos. Only Parameters use case #2
Another use case is to preclude keyword arguments when the parameter name is not helpful. For example, the builtinlen()function has the signaturelen(obj,/). This precludes awkward calls such as:
len(obj=’hello’) # The “obj” keyword argument impairs readability
Pos. Only Parameter benefit (name changes)
A further benefit of marking a parameter as positional-only is that it allows the parameter name to be changed in the future without risk of breaking client code. For example, in thestatisticsmodule, the parameter namedistmay be changed in the future. This was made possible with the following function specification:
def quantiles(dist, /, *, n=4, method=’exclusive’)
Pos. Only Parameters and **kwargs
Since the parameters to the left of/are not exposed as possible keywords, the parameters names remain available for use in**kwargs:
>>>>>> def f(a, b, /, **kwargs): ... print(a, b, kwargs) ... >>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways 10 20 {'a': 1, 'b': 2, 'c': 3}
Pos. Only Parameters and arbitrary keyword arguments
This greatly simplifies the implementation of functions and methods that need to accept arbitrary keyword arguments. For example, here is an excerpt from code in thecollectionsmodule:
class Counter(dict): def \_\_init\_\_(self, iterable=None, /, **kwds): # Note "iterable" is a possible keyword argument