Explore Python 3.8: Assignment Expressions, Positional‑Only Params & New Features
Python 3.8 introduces several practical enhancements—including the walrus operator (:=) for assignment expressions, positional‑only parameters marked by '/', runtime audit hooks, f‑string debugging with '=', improved asyncio REPL handling, shared memory support, a built‑in @cached_property decorator, and numerous performance and library updates.
Assignment Expressions (PEP 572)
Python 3.8 adds the := operator, known as the "walrus operator," which allows assignment within an expression. This lets you combine value computation, variable assignment, and condition checking in a single if statement.
import re
pattern = re.compile('a')
data = 'abc'
match = pattern.search(data)
if match is not None:
print(match.group(0))Using the assignment expression, the same logic can be written more concisely:
if (match := pattern.search(data)) is not None:
print(match.group(0))The operator also works inside comprehensions:
filtered_data = [y for x in data if (y := func(x)) is not None]Positional‑Only Parameters (PEP 570)
Python 3.8 introduces a new syntax marker / in function definitions to indicate that parameters to its left are positional‑only and cannot be passed by keyword.
def pow(x, y, z=None, /):
r = x ** y
return r if z is None else r % z
# Valid call
pow(5, 3)
# Invalid call – raises TypeError
pow(x=5, y=3)Runtime Audit Hooks (PEP 578)
Audit hooks allow developers to monitor certain events and API calls at runtime. Below is a simple hook that prints information when an urllib.Request is made.
import sys, urllib.request
def audit_hook(event, args):
if event in ['urllib.Request']:
print(f"{event=} {args=}")
sys.addaudithook(audit_hook)
urllib.request.urlopen('https://httpbin.org/get?a=1')Refer to the official PEP‑578 documentation for more built‑in events and customization.
F‑strings Support the Equal Sign
Python 3.8 extends f‑strings with the = specifier, which prints both the expression and its value, useful for debugging.
x = 10
print(f"{x+1=}") # Output: x+1=11Asyncio Interactive Mode
When launching the REPL with python -m asyncio, you no longer need to wrap coroutine calls with asyncio.run(). Direct await works.
import asyncio
async def test():
await asyncio.sleep(1)
return 'test'
await test() # Returns 'test'Cross‑Process Shared Memory
Python 3.8 adds multiprocessing.shared_memory, providing a ShareableList that can be accessed and modified by multiple processes.
from multiprocessing import Process
from multiprocessing import shared_memory
share_nums = shared_memory.ShareableList(range(5))
def work1(nums):
for i in range(5):
nums[i] += 10
print('work1 nums = %s' % nums)
def work2(nums):
print('work2 nums = %s' % nums)
if __name__ == '__main__':
p1 = Process(target=work1, args=(share_nums,))
p1.start(); p1.join()
p2 = Process(target=work2, args=(share_nums,))
p2.start(); p2.join()
# Output:
# work1 nums = [10, 11, 12, 13, 14]
# work2 nums = [10, 11, 12, 13, 14]@cached_property
Python now includes a built‑in @cached_property decorator (in functools) that caches the result of a property after the first access.
import time
from functools import cached_property
class Example:
@cached_property
def result(self):
time.sleep(1)
print('work 1 sec...')
return 10
e = Example()
print(e.result) # First call, sleeps 1 second
print(e.result) # Second call, returns instantly from cacheOther Improvements
PEP 587: Python initialization configuration.
PEP 590: Vectorcall, a fast call protocol for CPython.
Allow continue inside finally blocks.
Typed AST merged back into CPython.
Pickle now defaults to protocol 4 for better performance. LOAD_GLOBAL opcode speed increased by ~40%. unittest now supports asynchronous tests.
On Windows, the default asyncio event loop is ProactorEventLoop.
On macOS, multiprocessing now defaults to the spawn start method.
For a complete list of new features, see the "What’s New In Python 3.8" documentation.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
