f-strings to document and debug

f-strings are one of the most loved features of python. It was originally introduced in python3.6 and in Python3.8, it received had a major update. f-strings now support self-documentation.

An example of f-strings,

name = "amalshaji"
value = 345

print(f"name={name} value={value}")
❯ python test.py
name=amalshaji value=345

Developers have this habit of naming their variables what they're supposed to do/hold. Look at this piece of code,

def rev(string: str):
    return string[::-1]

reversed_string = rev("amalshaji")
print(f"reversed string: {reversed_string}")
❯ python test.py
reversed string: ijahslama

With the new upgrade to f-strings in python3.8, you don't have to manually print out the names for debugging or for info. Just append a = at the end of any variable inside f-string.

def rev(string: str):
    return string[::-1]

reversed_string = rev("amalshaji")
print(f"{reversed_string=}")
❯ python test.py
reversed_string='ijahslama'

Easy to debug long expressions

from math import sin, cos, tan

a = 10

print(f"{a=} {sin(cos(tan(a)))=}")
❯ python test.py
a=10 sin(cos(tan(a)))=0.7153149717720886
one_million = 1000000
print(f"{one_million=:,d}")
❯ python test.py
one_million=1,000,000

Happy Hacking✨✨✨

Comments (1)

UDOKAKU UGOCHUKWU's photo

This is nice