New features in Python 3.8

New features in Python 3.8

Early this morning I was looking into one of my Python programs and thought about "How it would be great if I could do assignment right in a condition check expressions...". And BOOM! Meet Python 3.8 new features!

Assignment expressions

New syntax implemented (:=) that allow to do variable assignments right in the expressions.

discount = 0.0
if (mo :='(\d+)% discount', advertisement)):
    discount = float( / 100.0

Earlier I would need to do something like that:

discount = 0.0
if'(\d+)% discount', advertisement):
    mo ='(\d+)% discount', advertisement)
    discount = float( / 100.0

It recommended though to limit use of so-called "walrus" operator only in clean cases to reduce complexity and improve readability.

More info can be found in PEP 572.

f-strings support "=" for self-documenting expressions and debugging

Added an = specifier to f-strings. An f-string such as f'{expr=} will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.

>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'{user=} {member_since=}'
"user='eric_idle', 7, 31)"

The = specifier will display the whole expression so that calculations can be shown:

>>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
theta=30  cos(radians(theta))=0.866

More details in contribution bpo-36817.

Other changes

  • A continue statement now legal in the finally clause. Earlier it was illegal due to a problem with implementation.
  • When the Python interpreter is interrupted by Ctrl-C (SIGINT) and the resulting KeyboardInterrupt exception is not caught, the Python process now exits via a SIGINT signal or with the correct exit code such that the calling process can detect that it died due to a Ctrl-C. Shells on POSIX and Windows use this to properly terminate scripts in interactive sessions.

It's required to say, that for today (Aug 14) Python 3.8 is in beta-phase and release date is not known.

Share Tweet Send
You've successfully subscribed to Prox blog
Great! Next, complete checkout for full access to Prox blog
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.