Sys "tb_lineno" is not a known member of "None" in Pylance

When creating my code, a Type Checking alert by Pylance is being issued when I try to generate an option to collect the error line in my code, as I want to save it in a log.

The code works, but as there is currently an incompatibility in use, I would like help finding a way to solve this incompatibility and keep the code from displaying this “error”.

If there is no way to work around using tb_lineno, its ok show a
parallel indication that is accepted by Pylance without generating the
alert.

enter image description here

def log_exception(comments=''):
    logger.error(f"Line Error: {sys.exc_info()[2].tb_lineno}\nComments: {comments}", exc_info=True)
"tb_lineno" is not a known member of "None" Pylance
(property) tb_lineno: int

My complete code to make testing easier:

import logging
import sys
import os

ERROR_LOG_FILE = f'{os.path.splitext(os.path.basename(__file__))[0]}_errors.log'

def setup_logger(logger_name, log_file, level=logging.DEBUG):
    logger = logging.getLogger(logger_name)
    logger.setLevel(level)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = logging.FileHandler(log_file)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    return logger

def log_exception(comments=''):
    logger.error(f"Line Error: {sys.exc_info()[2].tb_lineno}\nComments: {comments}", exc_info=True)

logger = setup_logger(__name__, ERROR_LOG_FILE)

def main():
    try:
        a = 1/0
    except Exception as e:
        log_exception()

if __name__ == '__main__':
    main()

The issue here is that sys.exc_info() may return a tuple of Nones if there is no active exception. Your log_exception() function would fail with an AttributeError in this case. It’s bad for error handling code to fail, so I’d recommend rewriting it as something like:

def log_exception(comments=''):
    _, _, tb = sys.exc_info()
    if tb is not None:
        logger.error(f"Line Error: {tb.tb_lineno}\nComments: {comments}", exc_info=True)
    else:
        logger.error(f"log_exception() called without an active exception.\nComments: {comment}")
1 Like

Thanks for support, @Jelle !