3

The following causes some additional strange output to be printed

import warnings

def foo(x):

    if x > 100:
        msg = "Warning! x is big!"
        warnings.warn(msg)
    return True

foo(999999)

Instead of only printing:

UserWarning: Warning! x is big!

we get:

UserWarning: Warning! x is big!
   warnings.warn(msg)

Sometimes I have even gotten:

UserWarning: Warning! x is big!
   ValueError [blah, blah, blah]
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42

1 Answers1

2

Here is one way:

import warnings
import sys

if not sys.warnoptions:
    warnings.simplefilter("ignore")

def foo(x):

    if x > 100:
        msg = "Warning! x is big!"
        warnings.warn(msg)
    return True

foo(999999)

Disclaimer

The Python documentation advises not to change this setting:

sys.warnoptions

This is an implementation detail of the warnings framework; do not modify this value. Refer to the warnings module for more information on the warnings framework.

jpp
  • 159,742
  • 34
  • 281
  • 339