For Python 3.8+, the use of assignment expression (a.k.a. the walrus operator - :=) allows for more compact and readable code in several situations. See PEP 0572 for complete explanation.
I have recently refactored the psycopg 3 codebase by rewriting assignments followed by an if referencing to the new name precisely once, which is one of the most clear use case: see psycopg/psycopg#1035. For example:
def download(self):
- filename = os.environ.get("LIBPQ_DOCS_FILE")
- if filename:
+ if filename := os.environ.get("LIBPQ_DOCS_FILE"):
logger.info("reading postgres libpq docs from %s", filename)
This refactoring was performed by an AST-modifying script and the changes hand-picked to exclude cases where the refactoring was less clear, as well as to exclude spurious changes caused by not using a concrete syntax tree.
I don't know what method uses pyupgrade internally to represent the code, and the script I use is not totally automatic, but I wanted to propose it as an example, mentioning the fact that I had a few people interested in seeing this feature introduced in pyupgrade.
Note: I have just found #601 closed as completed, but I don't believe this feature is introduced. If this feature is not desired, a comment about it would be welcome 🙂
Thank you very much.
For Python 3.8+, the use of assignment expression (a.k.a. the walrus operator -
:=) allows for more compact and readable code in several situations. See PEP 0572 for complete explanation.I have recently refactored the psycopg 3 codebase by rewriting assignments followed by an if referencing to the new name precisely once, which is one of the most clear use case: see psycopg/psycopg#1035. For example:
This refactoring was performed by an AST-modifying script and the changes hand-picked to exclude cases where the refactoring was less clear, as well as to exclude spurious changes caused by not using a concrete syntax tree.
I don't know what method uses pyupgrade internally to represent the code, and the script I use is not totally automatic, but I wanted to propose it as an example, mentioning the fact that I had a few people interested in seeing this feature introduced in pyupgrade.
Note: I have just found #601 closed as completed, but I don't believe this feature is introduced. If this feature is not desired, a comment about it would be welcome 🙂
Thank you very much.