DEV Community

HAP
HAP

Posted on

Python Throws a Bone to Other Developers

This may be a bit late to the party, but I recently found out that, starting with Python 3.8, You can assign variables within expressions. This was something I really disliked about Python way back in the 2.5 days when I switched over from C.

So, now instead of a code block like this:

if len(data) > 0:
    process(data)
print(f"Processed {len(data)} bytes!")
Enter fullscreen mode Exit fullscreen mode

You can combine variable assignment and the comparison in one line of code!

if (dat_len := len(data)) > 0:
    process(data)
print(f"Processed {dat_len} bytes!")
Enter fullscreen mode Exit fullscreen mode

It's all thanks to the addition of the := operator.

For those of you who started programming in Python, this may not be such a big deal. But for those of us who come to Python from other languages, this is a real benefit, IMHO, as it helps the transition of programming in a "Pythonic" way that is also similar to the programming patterns from other languages.

See the docs here.

Top comments (0)