Pyrfecter logo Pyrfecter

Lint, format, and modernize your Python code to make it positively perfect.

Input
Output

Linting & Analysis

Simplify your Python code using the walrus operator

Python's assignment operator, lovingly called the "walrus operator" for resembling a pair of eyes above tusks (:=), can cut down on boilerplate code when creating a variable that you want to use right away. In other words, Python's walrus allows you to assign a variable the first time you use, which is particularly convenient in if statements.

Officially called "Assignment Expressions", the walrus operator was introduced in PEP 572 and shipped with Python 3.8.

For a good example of how the walrus operator can make your code more succinct, check out the following example adapted from Blury, an in-progress Python static site generator used to build this site (and developed by yours truly!):

Before:

from typing import Any

def open_graph_meta_tags(schema_data: dict[str, Any]) -> str:
    open_graph_properties = {}

    headline = schema_data.get("headline")
    if headline:
        open_graph_properties["title"] = headline

    url = schema_data.get("url")
    if url:
        open_graph_properties["url"] = url

    abstract = schema_data.get("abstract")
    if abstract:
        open_graph_properties["description"] = abstract

    return "\n".join(
        '<meta og:property="{property}" content="{content}" />'.format(property=property, content=content)
        for property, content in open_graph_properties.items()
    )

After:

from typing import Any


def open_graph_meta_tags(schema_data: dict[str, Any]) -> str:
    open_graph_properties = {}

    if headline := schema_data.get("headline"):
        open_graph_properties["title"] = headline

    if url := schema_data.get("url"):
        open_graph_properties["url"] = url

    if abstract := schema_data.get("abstract"):
        open_graph_properties["description"] = abstract

    return "\n".join(
        f'<meta og:property="{property}" content="{content}" />'
        for property, content in open_graph_properties.items()
    )

In the "Before", there were variables that are used only within if statements, like headline = schema_data.get("headline"). After running the code through Pyrfecter, which includes auto-walrus, these variable definitions are collapsed using the walrus operator so they can be used at the same time as they're defined:

if headline := schema_data.get("headline"):
    open_graph_properties["title"] = headline

It may not seem like a huge difference, but it adds up! The real version of that function has 9 if statements and 9 walrus operators, and those tusky little fellows save 9 lines of code.

(The keen-eyed among you might notice how Pyrfecter also replaced .format() with an f-string. Go check out the string formatting example for more information on that.)

So, what are you waiting for? Pyrfect those variable assignments!