Skip to content

Proposal: introduce the use of assignment expressions #1006

@dvarrazzo

Description

@dvarrazzo

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions