# What I've learned today - 2 - Walrus Operator (:=) in Python

## What is?

The new operator allows variable assignments within expressions (also called Walrus Operator). It started as a proposal in PEP572 and became available in Python 3.8.

## Benefits

• Make things more compact.
• Compress code when using regular expressions.
• Speed up the processing of large data.

## Examples

A good example can be found in PEP572 documentation:

• Current:

``````reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(4)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
raise Error(
"un(deep)copyable object of type %s" % cls)

``````
• Improved:

``````if reductor := dispatch_table.get(cls):
rv = reductor(x)
elif reductor := getattr(x, "__reduce_ex__", None):
rv = reductor(4)
elif reductor := getattr(x, "__reduce__", None):
rv = reductor()
else:
raise Error("un(deep)copyable object of type %s" % cls)
``````

This code is from python's core, and is a improved version of copy.py

We can use in any condition structure:

``````# While loop
while (command := input("> ")) != "quit":
print("You entered:", command)
``````
``````# Any
if any((comment := line).startswith('#') for line in lines):
print("First comment:", comment)
else:

``````
``````# List comprehenssion
stuff = [[(f(x) as .y), x/.y] for x in range(5)] # with "as"
``````

## Observations

The operator cannot be used for everything, in some cases he won't work:

``````a := 1 #INVALID must be done with a=1.
a = b := 2 #INVALID must be done with a=b=2
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.81858164,"math_prob":0.8400615,"size":1654,"snap":"2023-14-2023-23","text_gpt3_token_len":442,"char_repetition_ratio":0.13515152,"word_repetition_ratio":0.038610037,"special_character_ratio":0.29504234,"punctuation_ratio":0.18322982,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97984624,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-28T13:10:09Z\",\"WARC-Record-ID\":\"<urn:uuid:01e1cfda-61c1-4bac-a733-3ac0688c11b3>\",\"Content-Length\":\"87405\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:f62d71cf-e4ec-4f44-9d0d-0c3625007588>\",\"WARC-Concurrent-To\":\"<urn:uuid:d9c3d207-e0b5-4e92-9cea-a36057c81339>\",\"WARC-IP-Address\":\"151.101.194.217\",\"WARC-Target-URI\":\"https://dev.to/lgdev07/what-i-ve-learned-today-2-walrus-operator-in-python-1984\",\"WARC-Payload-Digest\":\"sha1:OZHA6YW32HP4EJM3WPULCA2X6F6PHFTL\",\"WARC-Block-Digest\":\"sha1:PUTZE7O5NFBQODNQTQK2D2AFJ6SYR7DC\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296948858.7_warc_CC-MAIN-20230328104523-20230328134523-00210.warc.gz\"}"}