When I issue a warnings.warn() warning in python, the output to stderr includes not just my warning method, but also the offending line from the source code. I would like to suppress this line from the source code, as it really detracts from expressing the warning clearly. Does anyone know how to do this?
Specify warning categories to ignore You can specify a warning category in the second parameter of warnings. simplefilter() , category . Warning categories include FutureWarning , DeprecationWarning , SyntaxWarning , RuntimeWarning , etc.
For example, one might want to issue a warning when a program uses an obsolete module. Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx() ; see Exception Handling for details). Warning messages are normally written to sys.
To warn about deprecation, you need to set Python's builtin DeprecationWarning as category. To let the warning refer to the caller, so you know exactly where you use deprecated code, you have to set stacklevel=2 .
Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library. Warning is actually a subclass of Exception in built-in class hierarchy.
You can monkey-patch the formatwarning function. If you look at the source, it shouldn't be too hard to write a replacement that doesn't have a line number there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With