DEV Community

Luan Gomes
Luan Gomes

Posted on

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.
  • Code more readable.

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)
Enter fullscreen mode Exit fullscreen mode
# Any
if any((comment := line).startswith('#') for line in lines):
    print("First comment:", comment)
else:
    print("There are no comments")

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

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
Enter fullscreen mode Exit fullscreen mode

I appreciate everyone who has read through here, if you guys have anything to add, please leave a comment.

Top comments (0)