Skip to content

Use Named Expression

Sourcery refactoring id: use-named-expression

Description:

Merge assignment followed by conditional check using a named expression.

Before:

env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
    return env_base
chunk = file.read(8192)
while chunk:
    process(chunk)
    chunk = file.read(8192)

After:

if env_base := os.environ.get("PYTHONUSERBASE", None):
    return env_base
while chunk := file.read(8192):
    process(chunk)

Explanation:

Assignment (or named) expressions were introduced into Python 3.8 via PEP 572. They are a way of assigning to a variable inside an expression. The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value. For example:

while chunk := file.read(8192):
    process(chunk)

The named expression here returns the result of file.read() to decide whether to continue the while loop, and also assigns the result to chunk so that it can be processed. Using a named expression to merge an assignment followed immediately by a condition checking the result leads to cleaner code - once you know the syntax it can be understood at a glance. It can also lead to simplification of more complex expressions involving if - for example the below:

Before:

if self._is_special:
    ans = self._check_nans(context=context)
    if ans:
        return ans

After applying the named expression then merging the if conditions:

if self._is_special and (ans := self._check_nans(context=context)):
    return ans