Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Python's `warnings.warn()` not mention itself

My minimum example is

#!/usr/bin/python3

import warnings

warnings.warn('Run Forest run!', stacklevel=2)
warnings.warn('Run Forest run!')

and it will output

sys:1: UserWarning: Run Forest run!
./file.py:6: UserWarning: Run Forest run!
  warnings.warn('Run Forest run!')

The first line gives me to little info. The second line is perfect, giving me source file and line number ... but I'd like to get rid of the redundant third line. Is that possible?

like image 572
arney Avatar asked Oct 17 '14 18:10

arney


People also ask

How do you create a warning message in Python?

showwarning(message, category, filename, lineno, file=None, line=None): This function Writes a warning to a file. simplefilter(action, category=Warning, lineno=0, append=False): This function adds a single entry into the warnings filter requirements list.

Which method is used to display a warning message in Python?

showwarning() This method is used to display the warning to the user.

How do I stop deprecation warning in Python?

When nothing else works: $ pip install shutup . Then at the top of the code import shutup;shutup. please() . This will disable all warnings.


2 Answers

Turns out it is possible to let warnings.warn() collect all the info and just costumize the way the info is printed:

#!/usr/bin/python3

import warnings

def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
    return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)

warnings.formatwarning = warning_on_one_line

warnings.warn('Run Forest run!', stacklevel=2)
warnings.warn('Run Forest run!')

Output:

sys:1: UserWarning: Run Forest run!
./file.py:15: UserWarning: Run Forest run!

Source: Python module of the week

like image 58
arney Avatar answered Sep 19 '22 21:09

arney


The reason you are getting the "redundant" line is because if you don't provide the stacklevel parameter the default stacklevel is 1, which is basically telling the user the exact line of code that the warning originated from, which is your warning function call warnings.warn('Run Forest Run!').

If you're not happy with the way it functions, you can use the warnings.warn_explicit() function to customise it.

https://docs.python.org/3.1/library/warnings.html#available-functions

like image 35
Alex W Avatar answered Sep 17 '22 21:09

Alex W