18

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?

TRB
  • 181
  • 1
  • 3
  • Take a look at warning filters - https://docs.python.org/2/library/warnings.html#the-warnings-filter – shaktimaan Aug 27 '14 at 21:09
  • 2
    See e.g. [Python: Print only the message on warnings](http://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings) – hlt Aug 27 '14 at 21:09
  • 1
    2022 update: see https://stackoverflow.com/a/26433913/5122790 for a solution that doesn't require hacky monkey-patching – Chris Stenkamp Feb 06 '22 at 12:03

1 Answers1

3

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696