Use Named Expression
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: use-named-expression
Section titled “Sourcery refactoring id: use-named-expression”Description:
Section titled “Description:”Merge assignment followed by conditional check using a named expression.
Before:
Section titled “Before:”env_base = os.environ.get("PYTHONUSERBASE", None)if env_base: return env_basechunk = file.read(8192)while chunk: process(chunk) chunk = file.read(8192)After:
Section titled “After:”if env_base := os.environ.get("PYTHONUSERBASE", None): return env_basewhile chunk := file.read(8192): process(chunk)Explanation:
Section titled “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 ansAfter applying the named expression then merging the if conditions:
if self._is_special and (ans := self._check_nans(context=context)): return ans