Skip to content

prefer-walrus-awaited-none-guard

Bind a compact awaited lookup in its immediately following terminal None guard.

Why

When an awaited lookup and its terminal None guard are adjacent, binding in the condition keeps the operation, branch decision, and temporary name in one compact expression.

Fix

Rewrite value = await lookup(); if value is None: return as if (value := await lookup()) is None: return. Preserve is not None when the terminal branch returns or raises with the bound value. A short message assignment may remain inside the guard before the terminal statement. Keep two statements when the awaited assignment is an intentional debugging or tracing boundary.

Examples

Before — flagged An awaited lookup is split from its absence guard
service.py
async def load(store, item_id):
item = await store.get(item_id)
if item is None:
return
return item.name
After — preferred The awaited lookup is bound in its absence guard
service.py
async def load(store, item_id):
if (item := await store.get(item_id)) is None:
return
return item.name