Search
  • Team FastApp

Python3.8 - The Walrus Operator

In Python 3.8, we will be able to use assignment as a part of the large expressions. It has a new syntax :=

Examples:

1. if-else block


Python3.8

my_string = "second"
if (my_var := len(my_string)) > 5:     
    print(f"Error!! String is too long, ({my_var} elements, expected <= 5)")

< Python3.8

if len(my_string) > 5: 
    print(f"Error!! List is too long ({len(my_string)} elements, expected <= 5)")

Thus need to call len() twice here. After Walrus operator's introduction this can be

one call to len() only. Thus this reduces the line count of code by 1.



2. In while-loop:

Python3.8

while (password := input("Enter the password: ")) != "my password":
    continue

< Python3.8

while True:
    password = input("Enter the password: ")   # extra line 
    if (password != "my password"):
        continue

here we save one line by using the Walrus Operator.



3. In for-loops:


Python 3.8

numbers = [11, 22, 33, 44]
accepted_numbers = [
    result 
    for number in numbers 
    if (result := call_some_function(number)) > 0
]

< Python 3.8

numbers = [11, 22, 33, 44] 
accepted_numbers = [
    call_some_function(number) 
    for number in numbers      
    if (result := call_some_function(number)) > 0 
]

Notice that this is not a good practise as we need to call call_some_function(number) twice

in the comprehension.




49 views1 comment

Recent Posts

See All

Django Queries Simplified [Part - 1]

This blog post aims to make django querying simple for the developers who are new in the django world. Keep reading :) What is a django query? A django query is an expression which can be used to writ

Django Queryset with an unusual operation "Merge"

Consider, we have a StudentHistory model defined as: class StudentHistory(models.Model): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=150, b