Unusual trick for better Python logs

Pythonlogging

You are probably used to logging variables in Python using some type of string interpolation. For example:

# Option 1
logger.info("Request succeeded for url: %s", url)
 
# Option 2, even better with f-strings
logger.info(f"Request succeeded for url: {url}")

But did you know there is a better option?

In Python 3.8 a feature called self documenting strings (opens in a new tab) was introduced. It allows you to log variable values more conciesely. The example above becomes:

logger.info(f"Request succeeded for {url=}")

The syntax requires setting {variable=} within an f-string.

Even though it's been available for a few years, it's relatively uncommon to see it in production code. I believe it's yet to become popular.

That's it.