This post will be a quick one. I see a lot of f-string debug statements in pair programming like below;

1
2
3
4
5
6
7
8
import os


def get_os_user():
    os_user = os.getenv("USER")
    print(f"os_user = {os_user}")

    return os_user

First of all, it’s better to use python’s built-in logging module.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import logging
import os

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def get_os_user():
    os_user = os.getenv("USER")
    logger.info(f"os_user = {os_user}")

    return os_user

Note

For a detail information about logging, you can look at my previous article: python logging config.

Since python 3.8 you can use a = at the end of a expression without hard coding variable/expression:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import logging
import os

logging.basicConfig(
    level=logging.INFO,
    format="[%(asctime)s] [%(levelname)-8s] : %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S %z",
)
logger = logging.getLogger(__name__)


def get_os_user():
    os_user = os.getenv("USER")
    logger.info(f"{os_user = }")
    # whitespaces don't matter
    # logger.info(f"{os_user=}")

    return os_user

This which is equal to f"os_user = {os_user}", will enforce the variable to also be logged/printed.

[2023-03-26 22:48:43 +0300] [INFO    ] : os_user = 'user'

Note

It’s usually best to use a proper debugger. They are built-in in IDEs like VScode or PyCharm. You can also take advantage of separate ones as well such as pdb, ipdb etc, or my favorite one pudb.

python interfaces shell interfaces

All done!


Changelog

  • 2022-03-23 : Add stdout code