Warning
Use
  • Warn changes in language or library features
  • Report recoverable configuration errors or feature degradation from missing libraries
  • Warnings are sent to console
  • Filter
  • action
  • message, regular expression
  • category, name of an exception class
  • module, regular expression to be matched against the module name
  • line, line number
  • Generating Warnings
    import warnings
    
    warnings.warn('This is a warning message')
    
    try:
        warnings.simplefilter('error', UserWarning) # throw Exception
        warnings.warn('This is second warning message')
    except Exception as err:
        print('Exception: ', err)
                
    w1.py:3: UserWarning: This is a warning message
      warnings.warn('This is a warning message')
    Exception:  This is second warning message
                
    Controlling by Command Line
    import warnings
    
    try:
        warnings.warn('This is second warning message')
    except Exception as err:
        print('Exception: ', err)
                
    # command line
    # (action, message, category, module, and line number) separated by colons (:)
    python -W "error::UserWarning::0" w2.py
                
    Exception:  This is second warning message
                
    Message Filter
    import warnings
    
    warnings.filterwarnings('ignore', '.*do not.*',)
    
    warnings.warn('Show this message')
    warnings.warn('Do not show this message') # do not show, case insensitive
                
    w3.py:5: UserWarning: Show this message
      warnings.warn('Show this message')
                
    Module Filter
    # w4.py
    
    import warnings
    
    warnings.filterwarnings(
        'ignore',
        '.*',
        UserWarning,
        '__main__', # supress the warnings from the current module
    )
    
    warnings.warn('Do not show this message') # do not show
    
    warnings.filterwarnings(
        'ignore',
        '.*',
        UserWarning,
        'w.*', # supress the warnings form modules starting with w
    )
    
    import warning
    warning.get_warning()
                
    # warning.py
    
    import warnings
    
    def get_warning():
        warnings.warn('Warining in a sub module') # do not show
                
    Line Filter
    import warnings
    
    warnings.filterwarnings(
        'ignore',
        '.*',
        UserWarning,
        '__main__',
        12 # do not show the warning in line 12
    )
    
    warnings.warn('Show this message')
    warnings.warn('Do not show this message')
                
    Repeat Warnings
  • By default, most types of warnings are only printed the first time they occur
  • The once action can be used to suppress instances of the same message from different locations
  • import warnings
    
    def get_warning():
        warnings.warn('Warning ...')
    
    # only display once
    get_warning()
    get_warning()
    
    warnings.warn('Show this message') # display
    warnings.warn('Show this message') # display
                
    import warnings
    
    warnings.simplefilter('once', UserWarning)
    warnings.warn('Show this message') # display
    warnings.warn('Show this message') # do not display
                
    Send Warning to Log
    # replace the showwarning() function inside the warnings module
    import warnings
    import logging
    
    
    def send_warnings_to_log(message, category, filename, lineno,
                             file=None, line=None):
        logging.warning('%s:%s',category.__name__, message)
    
    
    logging.basicConfig(filename = 'log.txt', level=logging.INFO)
    
    warnings.showwarning = send_warnings_to_log
    
    warnings.warn('message')
                
    # integrate warning into logging
    import logging
    import warnings
    
    logging.basicConfig(filename='log.txt', level=logging.INFO)
    
    # send warning information to logging
    logging.captureWarnings(True)
    
    # output warning to logging file
    warnings.warn('This warning is sent to the logs')
                
    Send Warning to Log
    # replace formatwarning() function inside the warnings module
    import warnings
    
    def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
        return '-> {}:{}'.format(category.__name__, message)
    
    warnings.formatwarning = warning_on_one_line
    warnings.warn('Warning message, after')
                
    Stack
  • Display the line number of caller instead of the line number of warning
  • import warnings
    
    # stacklevel, 1, self, 2, parent, 3, parent of parent
    def old_function():
        warnings.warn(
            'old_function() is deprecated, use new_function()',
            stacklevel=3)
    
    def caller_of_old_function():
        old_function()
    
    caller_of_old_function()
                
    w10.py:12: UserWarning: old_function() is deprecated, use new_function()
      caller_of_old_function()
                
    Reference
  • Document
  • PyMOTW