0

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.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
Shaun Barney
  • 596
  • 5
  • 20
  • Use parentheses for the grouping you want - `post_url := (...)`. Alternatively `"youtube" in data.get("Post url", [])` would factor out the `and`. – jonrsharpe Apr 27 '20 at 13:57
  • @jonrsharpe thanks for the comment. I tried if post_url := "youtube" in data.get("Post url", []) which still returns the boolean as does if post_url := (data.get("Post url") and "youtube" in data.get("Post url")): – Shaun Barney Apr 27 '20 at 14:17
  • 1
    Oh, so you want `if (post_url := data.get("Post url")) and "youtube" in post_url:`? You don't need to double up the `.get` – jonrsharpe Apr 27 '20 at 14:20

1 Answers1

3

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.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334