Search code examples
pythonpython-3.8python-assignment-expression

Multiple conditions for "walrus operator" assignment


I'd like to know if it's possible to use the "walrus operator" to assign the value based on some condition as well as existing. For example, assign the string to post_url if that string contains some substring:

if post_url := data.get("Post url") and ("youtube" in data.get("Post url")):
    # Do something with post_url
else:
    # Do something else

However, this is just assigning the boolean value to post_url due to the evaluation of the and operation.


Solution

  • You can use parentheses to group this how you want, you don't even need to repeat the data.get:

    if (post_url := data.get("Post url")) and "youtube" in post_url:
        # Do something with post_url
    else:
        # Do something else
    

    This will assign a value to post_url either way, so you can access None or the URL not containing "youtube" in the else block.