Python warnings.filters() Examples

The following are 30 code examples of warnings.filters(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module warnings , or try the search function .
Example #1
Source File: utils.py    From pySINDy with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #2
Source File: utils.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #3
Source File: utils.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #4
Source File: utils.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def __enter__(self):
        if self._entered:
            raise RuntimeError("Cannot enter %r twice" % self)
        self._entered = True
        self._filters = self._module.filters
        self._module.filters = self._filters[:]
        self._showwarning = self._module.showwarning
        if self._record:
            log = []

            def showwarning(*args, **kwargs):
                log.append(WarningMessage(*args, **kwargs))
            self._module.showwarning = showwarning
            return log
        else:
            return None 
Example #5
Source File: _numpy_compat.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
            """
            Add a new suppressing filter or apply it if the state is entered.

            Parameters
            ----------
            category : class, optional
                Warning class to filter
            message : string, optional
                Regular expression matching the warning message.
            module : module, optional
                Module to filter for. Note that the module (and its file)
                must match exactly and cannot be a submodule. This may make
                it unreliable for external modules.

            Notes
            -----
            When added within a context, filters are only added inside
            the context and will be forgotten when the context is exited.
            """
            self._filter(category=category, message=message, module=module,
                         record=False) 
Example #6
Source File: _numpy_compat.py    From lambda-packs with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
            """
            Add a new suppressing filter or apply it if the state is entered.

            Parameters
            ----------
            category : class, optional
                Warning class to filter
            message : string, optional
                Regular expression matching the warning message.
            module : module, optional
                Module to filter for. Note that the module (and its file)
                must match exactly and cannot be a submodule. This may make
                it unreliable for external modules.

            Notes
            -----
            When added within a context, filters are only added inside
            the context and will be forgotten when the context is exited.
            """
            self._filter(category=category, message=message, module=module,
                         record=False) 
Example #7
Source File: test_warning.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_flushedWarningsConfiguredAsErrors(self):
        """
        If a warnings filter has been installed which turns warnings into
        exceptions, tests which emit those warnings but flush them do not have
        an error added to the reporter.
        """
        class CustomWarning(Warning):
            pass

        result = TestResult()
        case = Mask.MockTests('test_flushed')
        case.category = CustomWarning

        originalWarnings = warnings.filters[:]
        try:
            warnings.simplefilter('error')
            case.run(result)
            self.assertEqual(result.errors, [])
        finally:
            warnings.filters[:] = originalWarnings 
Example #8
Source File: utils.py    From lambda-packs with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #9
Source File: utils.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def runWithWarningsSuppressed(suppressedWarnings, f, *a, **kw):
    """Run the function C{f}, but with some warnings suppressed.

    @param suppressedWarnings: A list of arguments to pass to filterwarnings.
                               Must be a sequence of 2-tuples (args, kwargs).
    @param f: A callable, followed by its arguments and keyword arguments
    """
    for args, kwargs in suppressedWarnings:
        warnings.filterwarnings(*args, **kwargs)
    addedFilters = warnings.filters[:len(suppressedWarnings)]
    try:
        result = f(*a, **kw)
    except:
        exc_info = sys.exc_info()
        _resetWarningFilters(None, addedFilters)
        reraise(exc_info[1], exc_info[2])
    else:
        if isinstance(result, defer.Deferred):
            result.addBoth(_resetWarningFilters, addedFilters)
        else:
            _resetWarningFilters(None, addedFilters)
        return result 
Example #10
Source File: utils.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #11
Source File: PyShell.py    From BinderFilter with MIT License 6 votes vote down vote up
def runsource(self, source):
        "Extend base class method: Stuff the source in the line cache first"
        filename = self.stuffsource(source)
        self.more = 0
        self.save_warnings_filters = warnings.filters[:]
        warnings.filterwarnings(action="error", category=SyntaxWarning)
        if isinstance(source, types.UnicodeType):
            from idlelib import IOBinding
            try:
                source = source.encode(IOBinding.encoding)
            except UnicodeError:
                self.tkconsole.resetoutput()
                self.write("Unsupported characters in input\n")
                return
        try:
            # InteractiveInterpreter.runsource() calls its runcode() method,
            # which is overridden (see below)
            return InteractiveInterpreter.runsource(self, source, filename)
        finally:
            if self.save_warnings_filters is not None:
                warnings.filters[:] = self.save_warnings_filters
                self.save_warnings_filters = None 
Example #12
Source File: PyShell.py    From oss-ftp with MIT License 6 votes vote down vote up
def runsource(self, source):
        "Extend base class method: Stuff the source in the line cache first"
        filename = self.stuffsource(source)
        self.more = 0
        self.save_warnings_filters = warnings.filters[:]
        warnings.filterwarnings(action="error", category=SyntaxWarning)
        if isinstance(source, types.UnicodeType):
            from idlelib import IOBinding
            try:
                source = source.encode(IOBinding.encoding)
            except UnicodeError:
                self.tkconsole.resetoutput()
                self.write("Unsupported characters in input\n")
                return
        try:
            # InteractiveInterpreter.runsource() calls its runcode() method,
            # which is overridden (see below)
            return InteractiveInterpreter.runsource(self, source, filename)
        finally:
            if self.save_warnings_filters is not None:
                warnings.filters[:] = self.save_warnings_filters
                self.save_warnings_filters = None 
Example #13
Source File: test_testing.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_warn_wrong_warning(self):
        def f():
            warnings.warn("yo", DeprecationWarning)

        failed = False
        filters = sys.modules['warnings'].filters[:]
        try:
            try:
                # Should raise an AssertionError
                assert_warns(UserWarning, f)
                failed = True
            except AssertionError:
                pass
        finally:
            sys.modules['warnings'].filters = filters

        if failed:
            raise AssertionError("wrong warning caught by assert_warn")


# Tests for docstrings: 
Example #14
Source File: utils.py    From recruit with Apache License 2.0 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #15
Source File: PyShell.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def runsource(self, source):
        "Extend base class method: Stuff the source in the line cache first"
        filename = self.stuffsource(source)
        self.more = 0
        self.save_warnings_filters = warnings.filters[:]
        warnings.filterwarnings(action="error", category=SyntaxWarning)
        # at the moment, InteractiveInterpreter expects str
        assert isinstance(source, str)
        #if isinstance(source, str):
        #    from idlelib import IOBinding
        #    try:
        #        source = source.encode(IOBinding.encoding)
        #    except UnicodeError:
        #        self.tkconsole.resetoutput()
        #        self.write("Unsupported characters in input\n")
        #        return
        try:
            # InteractiveInterpreter.runsource() calls its runcode() method,
            # which is overridden (see below)
            return InteractiveInterpreter.runsource(self, source, filename)
        finally:
            if self.save_warnings_filters is not None:
                warnings.filters[:] = self.save_warnings_filters
                self.save_warnings_filters = None 
Example #16
Source File: utils.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def filter(self, category=Warning, message="", module=None):
        """
        Add a new suppressing filter or apply it if the state is entered.

        Parameters
        ----------
        category : class, optional
            Warning class to filter
        message : string, optional
            Regular expression matching the warning message.
        module : module, optional
            Module to filter for. Note that the module (and its file)
            must match exactly and cannot be a submodule. This may make
            it unreliable for external modules.

        Notes
        -----
        When added within a context, filters are only added inside
        the context and will be forgotten when the context is exited.
        """
        self._filter(category=category, message=message, module=module,
                     record=False) 
Example #17
Source File: test_deprecate.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_filteredOnceWarning(self):
        """
        L{deprecate.warnAboutFunction} emits a warning that will be filtered
        once if L{warnings.filterwarning} is called with the module name of the
        deprecated function and an action of once.
        """
        # Clean up anything *else* that might spuriously filter out the warning,
        # such as the "always" simplefilter set up by unittest._collectWarnings.
        # We'll also rely on trial to restore the original filters afterwards.
        del warnings.filters[:]

        warnings.filterwarnings(
            action="module", module="twisted_private_helper")

        from twisted_private_helper import module
        module.callTestFunction()
        module.callTestFunction()

        warningsShown = self.flushWarnings()
        self.assertEqual(len(warningsShown), 1)
        message = warningsShown[0]['message']
        category = warningsShown[0]['category']
        filename = warningsShown[0]['filename']
        lineno = warningsShown[0]['lineno']
        msg = warnings.formatwarning(message, category, filename, lineno)
        self.assertTrue(
            msg.endswith("module.py:9: DeprecationWarning: A Warning String\n"
                         "  return a\n"),
            "Unexpected warning string: %r" % (msg,)) 
Example #18
Source File: test_repr_info.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_repr_unsortable(self):
        # columns are not sortable
        import warnings
        warn_filters = warnings.filters
        warnings.filterwarnings('ignore',
                                category=FutureWarning,
                                module=".*format")

        unsortable = DataFrame({'foo': [1] * 50,
                                datetime.today(): [1] * 50,
                                'bar': ['bar'] * 50,
                                datetime.today() + timedelta(1): ['bar'] * 50},
                               index=np.arange(50))
        repr(unsortable)

        fmt.set_option('display.precision', 3, 'display.column_space', 10)
        repr(self.frame)

        fmt.set_option('display.max_rows', 10, 'display.max_columns', 2)
        repr(self.frame)

        fmt.set_option('display.max_rows', 1000, 'display.max_columns', 1000)
        repr(self.frame)

        tm.reset_display_options()

        warnings.filters = warn_filters 
Example #19
Source File: test_format.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def setup_method(self, method):
        self.warn_filters = warnings.filters
        warnings.filterwarnings('ignore', category=FutureWarning,
                                module=".*format")

        self.frame = _frame.copy() 
Example #20
Source File: utils.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def __exit__(self, *exc_info):
        warnings.showwarning = self._orig_show
        warnings.filters = self._filters
        self._clear_registries()
        self._entered = False
        del self._orig_show
        del self._filters 
Example #21
Source File: utils.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __enter__(self):
        if self._entered:
            raise RuntimeError("cannot enter suppress_warnings twice.")

        self._orig_show = warnings.showwarning
        self._filters = warnings.filters
        warnings.filters = self._filters[:]

        self._entered = True
        self._tmp_suppressions = []
        self._tmp_modules = set()
        self._forwarded = set()

        self.log = []  # reset global log (no need to keep same list)

        for cat, mess, _, mod, log in self._suppressions:
            if log is not None:
                del log[:]  # clear the log
            if mod is None:
                warnings.filterwarnings(
                    "always", category=cat, message=mess)
            else:
                module_regex = mod.__name__.replace('.', r'\.') + '$'
                warnings.filterwarnings(
                    "always", category=cat, message=mess,
                    module=module_regex)
                self._tmp_modules.add(mod)
        warnings.showwarning = self._showwarning
        self._clear_registries()

        return self 
Example #22
Source File: regrtest.py    From jawfish with MIT License 5 votes vote down vote up
def restore_warnings_filters(self, saved_filters):
        warnings.filters = saved_filters[1]
        warnings.filters[:] = saved_filters[2] 
Example #23
Source File: utils.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _clear_registries(self):
        if hasattr(warnings, "_filters_mutated"):
            # clearing the registry should not be necessary on new pythons,
            # instead the filters should be mutated.
            warnings._filters_mutated()
            return
        # Simply clear the registry, this should normally be harmless,
        # note that on new pythons it would be invalidated anyway.
        for module in self._tmp_modules:
            if hasattr(module, "__warningregistry__"):
                module.__warningregistry__.clear() 
Example #24
Source File: test_defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_circularChainException(self):
        """
        If the deprecation warning for circular deferred callbacks is
        configured to be an error, the exception will become the failure
        result of the Deferred.
        """
        self.addCleanup(setattr, warnings, "filters", warnings.filters)
        warnings.filterwarnings("error", category=DeprecationWarning)
        d = defer.Deferred()
        def circularCallback(result):
            return d
        d.addCallback(circularCallback)
        d.callback("foo")
        failure = self.failureResultOf(d)
        failure.trap(DeprecationWarning) 
Example #25
Source File: utils.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _resetWarningFilters(passthrough, addedFilters):
    for f in addedFilters:
        try:
            warnings.filters.remove(f)
        except ValueError:
            pass
    return passthrough 
Example #26
Source File: utils.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __exit__(self, *exc_info):
        warnings.showwarning = self._orig_show
        warnings.filters = self._filters
        self._clear_registries()
        self._entered = False
        del self._orig_show
        del self._filters 
Example #27
Source File: test_warning.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_warningsConfiguredAsErrors(self):
        """
        If a warnings filter has been installed which turns warnings into
        exceptions, tests have an error added to the reporter for them for each
        unflushed warning.
        """
        class CustomWarning(Warning):
            pass

        result = TestResult()
        case = Mask.MockTests('test_unflushed')
        case.category = CustomWarning

        originalWarnings = warnings.filters[:]
        try:
            warnings.simplefilter('error')
            case.run(result)
            self.assertEqual(len(result.errors), 1)
            self.assertIdentical(result.errors[0][0], case)
            self.assertTrue(
                # Different python versions differ in whether they report the
                # fully qualified class name or just the class name.
                result.errors[0][1].splitlines()[-1].endswith(
                    "CustomWarning: some warning text"))
        finally:
            warnings.filters[:] = originalWarnings 
Example #28
Source File: _synctest.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _collectWarnings(observeWarning, f, *args, **kwargs):
    """
    Call C{f} with C{args} positional arguments and C{kwargs} keyword arguments
    and collect all warnings which are emitted as a result in a list.

    @param observeWarning: A callable which will be invoked with a L{_Warning}
        instance each time a warning is emitted.

    @return: The return value of C{f(*args, **kwargs)}.
    """
    def showWarning(message, category, filename, lineno, file=None, line=None):
        assert isinstance(message, Warning)
        observeWarning(_Warning(
                str(message), category, filename, lineno))

    # Disable the per-module cache for every module otherwise if the warning
    # which the caller is expecting us to collect was already emitted it won't
    # be re-emitted by the call to f which happens below.
    _setWarningRegistryToNone(sys.modules)

    origFilters = warnings.filters[:]
    origShow = warnings.showwarning
    warnings.simplefilter('always')
    try:
        warnings.showwarning = showWarning
        result = f(*args, **kwargs)
    finally:
        warnings.filters[:] = origFilters
        warnings.showwarning = origShow
    return result 
Example #29
Source File: test_http_client.py    From shippo-python-client with MIT License 5 votes vote down vote up
def setUp(self):
        super(HttpClientTests, self).setUp()

        self.original_filters = warnings.filters[:]
        warnings.simplefilter('ignore') 
Example #30
Source File: test_http_client.py    From shippo-python-client with MIT License 5 votes vote down vote up
def tearDown(self):
        warnings.filters = self.original_filters

        super(HttpClientTests, self).tearDown()