Even though Python 3.8 is not official releases, there have been a few Alpha versions floating around. There are some interesting ideas in these including one called a Walrus Operator.
Here is the explanation:
Walrus-operator is another name for assignment expressions. According to the official documentation, it is a way to assign to variables within an expression using the notation NAME := expr. The Assignment expressions allow a value to be assigned to a variable, even a variable that doesn’t exist yet, in the context of expression rather than as a stand-alone statement.
This can make a longer expression be shortened with in the context of the assignment. For example:
sample_data = [
{"userId": 1, "name": "rahul", "completed": False},
{"userId": 1, "name": "rohit", "completed": False},
{"userId": 1, "name": "ram", "completed": False},
{"userId": 1, "name": "ravan", "completed": True}
]
print("With Python 3.8 Walrus Operator:")
for entry in sample_data:
if name := entry.get("name"):
print(f'Found name: "{name}"')
Here is the same without using Walrus:
print("Without Walrus operator:")
for entry in sample_data:
name =entry.get("name")
if name:
print(f'Found name: "{name}"')
Please comment if you thing this is a good change or not. Discuss the reasons why or why not...
Top Comments