Search code examples
pythonf-string

How to use *args or **kwargs in f-strings?


For example, I need *missing_vars to be an f-string in this logging. Because for logging.critical() one msg argument is needed, so I can't do this:

logging.critical(f'Required environment variables are missing: {*missing_vars}')

I can do it without *args, but I need it for a beautiful output, because it turns out like this:

>>> logging.critical(f'Required environment variables are missing: {missing_vars}')
Required environment variables are missing: ['PRACTICUM_TOKEN', 'TELEGRAM_TOKEN']`

But, I want like this:

Required environment variables are missing: PRACTICUM_TOKEN, TELEGRAM_TOKEN

My function:

def check_tokens():
    """Checks the availability of environment variables."""
    ENV_VARS = {
        'PRACTICUM_TOKEN': PRACTICUM_TOKEN,
        'TELEGRAM_TOKEN': TELEGRAM_TOKEN,
        'TELEGRAM_CHAT_ID': TELEGRAM_CHAT_ID,
    }
    missing_vars = [var for var, value in ENV_VARS.items() if not value]
    if missing_vars:
        logging.critical(f'Required environment variables are missing: {*missing_vars}') # <--
    else:
        return True

Solution

  • According to the comments of Mechanic Pig, I have updated my function and the output I need now, thank you!

    def check_tokens():
        """Checks the availability of environment variables."""
        ENV_VARS = {
            'PRACTICUM_TOKEN': PRACTICUM_TOKEN,
            'TELEGRAM_TOKEN': TELEGRAM_TOKEN,
            'TELEGRAM_CHAT_ID': TELEGRAM_CHAT_ID,
        }
        missing_vars = [var for var, value in ENV_VARS.items() if not value]
        if missing_vars:
            logging.critical(
                f'Required environment variables are missing: '
                f'{", ".join(missing_vars)}'
            )
        else:
            return True
    

    Output:

    CRITICAL:root:Required environment variables are missing: PRACTICUM_TOKEN, TELEGRAM_TOKEN, TELEGRAM_CHAT_ID