Python: Hidden Features — part 3

Advanced Features You Didn’t Know You Needed

Pravash
3 min readMay 8, 2024

--

Hi Everyone, In this article I will go throw couple of techniques or features which anyone can use in day to day coding.

In my journey through these Python features, I’ve uncovered techniques that go beyond the ordinary adding a touch of magic to our code.

Lets get started -

1. walrus operator (:=)

This was released in python 3.8 version. This helps us in defining value while using inside function.

Lets see an example -

def extract_val():
for i in range(10):
yield i
yield -1

def some_func(val):
pass

gen_obj = extract_val()
val = next(gen_obj)
while val != -1:
some_func(val)
val = next(gen_obj)

In this example I am creating a generaor object and then calling the next function to get the next value.
I am checking if the value is not negative 1, then I am calling some other function and then getting the next value.
Now lets see the same example with walrus -

def extract_val():
for i in range(10):
yield i
yield -1

def some_func(val):
pass

gen_obj = extract_val()
while (val := next(gen_obj))!= -1:
some_func(val)

Basically, here I am using the value as a result of my loop and at the same time I am using the result as the part of the…

--

--

Pravash
Pravash

Written by Pravash

I am a passionate Data Engineer and Technology Enthusiast. Here I am using this platform to share my knowledge and experience on tech stacks.

Responses (2)