Python warnings.simplefilter() Examples
The following are 30
code examples of warnings.simplefilter().
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: test_gluon.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 7 votes |
def test_global_norm_clip(): stypes = ['default', 'row_sparse'] def check_global_norm_clip(stype, check_isfinite): x1 = mx.nd.ones((3,3)).tostype(stype) x2 = mx.nd.ones((4,4)).tostype(stype) norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite) assert norm == 5.0 assert_almost_equal(x1.asnumpy(), np.ones((3,3))/5) assert_almost_equal(x2.asnumpy(), np.ones((4,4))/5) x3 = mx.nd.array([1.0, 2.0, float('nan')]).tostype(stype) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") gluon.utils.clip_global_norm([x1, x3], 2.0, check_isfinite=check_isfinite) assert len(w) == check_isfinite for stype in stypes: for check_isfinite in [True, False]: check_global_norm_clip(stype, check_isfinite)
Example #2
Source File: frd_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_evalfr_deprecated(self): sys_tf = ct.tf([1], [1, 2, 1]) frd_tf = FRD(sys_tf, np.logspace(-1, 1, 3)) # Deprecated version of the call (should generate warning) import warnings with warnings.catch_warnings(): # Make warnings generate an exception warnings.simplefilter('error') # Make sure that we get a pending deprecation warning self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.) # FRD.evalfr() is being deprecated import warnings with warnings.catch_warnings(): # Make warnings generate an exception warnings.simplefilter('error') # Make sure that we get a pending deprecation warning self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.)
Example #3
Source File: iosys_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setUp(self): # Turn off numpy matrix warnings import warnings warnings.simplefilter('ignore', category=PendingDeprecationWarning) # Create a single input/single output linear system self.siso_linsys = ct.StateSpace( [[-1, 1], [0, -2]], [[0], [1]], [[1, 0]], [[0]]) # Create a multi input/multi output linear system self.mimo_linsys1 = ct.StateSpace( [[-1, 1], [0, -2]], [[1, 0], [0, 1]], [[1, 0], [0, 1]], np.zeros((2,2))) # Create a multi input/multi output linear system self.mimo_linsys2 = ct.StateSpace( [[-1, 1], [0, -2]], [[0, 1], [1, 0]], [[1, 0], [0, 1]], np.zeros((2,2))) # Create simulation parameters self.T = np.linspace(0, 10, 100) self.U = np.sin(self.T) self.X0 = [0, 0]
Example #4
Source File: didyoumean_sugg_tests.py From DidYouMean-Python with MIT License | 6 votes |
def test_import_star(self): """'import *' in nested functions.""" # NICE_TO_HAVE codes = [ func_gen( 'func1', body=func_gen('func2', body='from math import *\nTrue')), func_gen( 'func1', body='from math import *\n' + func_gen('func2', body='True')), ] sys.setrecursionlimit(1000) # needed for weird PyPy versions with warnings.catch_warnings(): warnings.simplefilter("ignore", category=SyntaxWarning) for code in codes: self.throws(code, IMPORTSTAR) sys.setrecursionlimit(initial_recursion_limit)
Example #5
Source File: test_case.py From jawfish with MIT License | 6 votes |
def testAssertWarnsCallable(self): def _runtime_warn(): warnings.warn("foo", RuntimeWarning) # Success when the right warning is triggered, even several times self.assertWarns(RuntimeWarning, _runtime_warn) self.assertWarns(RuntimeWarning, _runtime_warn) # A tuple of warning classes is accepted self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) # *args and **kwargs also work self.assertWarns(RuntimeWarning, warnings.warn, "foo", category=RuntimeWarning) # Failure when no warning is triggered with self.assertRaises(self.failureException): self.assertWarns(RuntimeWarning, lambda: 0) # Failure when another warning is triggered with warnings.catch_warnings(): # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): self.assertWarns(DeprecationWarning, _runtime_warn) # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): self.assertWarns(DeprecationWarning, _runtime_warn)
Example #6
Source File: test_wallet.py From monero-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_filter_mempool_filter_address_and_payment_id(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # mempool excluded pmts = self.wallet.incoming( local_address='9tQoHWyZ4yXUgbz9nvMcFZUfDy5hxcdZabQCxmNCUukKYicXegsDL7nQpcUa3A1pF6K3fhq3scsyY88tdB1MqucULcKzWZC', payment_id='03f6649304ea4cb2') self.assertEqual(len(pmts), 0) # mempool included pmts = self.wallet.incoming( unconfirmed=True, local_address='9tQoHWyZ4yXUgbz9nvMcFZUfDy5hxcdZabQCxmNCUukKYicXegsDL7nQpcUa3A1pF6K3fhq3scsyY88tdB1MqucULcKzWZC', payment_id='03f6649304ea4cb2') self.assertEqual(len(pmts), 1) self.assertEqual( pmts[0].transaction.hash, 'd29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c') self.assertEqual(len(w), 0)
Example #7
Source File: test_wallet.py From monero-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_filter_mempool_filter_txid(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # mempool excluded pmts = self.wallet.incoming( tx_id='d29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c') self.assertEqual(len(pmts), 0) # mempool included pmts = self.wallet.incoming( unconfirmed=True, tx_id='d29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c') self.assertEqual(len(pmts), 1) self.assertEqual( pmts[0].transaction.hash, 'd29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c') self.assertEqual(len(w), 0)
Example #8
Source File: simple_moving_average.py From TradzQAI with Apache License 2.0 | 6 votes |
def simple_moving_average(data, period): """ Simple Moving Average. Formula: SUM(data / N) """ check_for_period_error(data, period) # Mean of Empty Slice RuntimeWarning doesn't affect output so it is # supressed with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) sma = list(map( lambda idx: np.mean(data[idx-(period-1):idx+1]), range(0, len(data)) )) sma = fill_for_noncomputable_vals(data, sma) return sma
Example #9
Source File: test_testing.py From calmjs with GNU General Public License v2.0 | 6 votes |
def test_rmtree_test(self): path = mkdtemp(self) utils.rmtree(path) self.assertFalse(exists(path)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') utils.rmtree(path) self.assertFalse(w) utils.stub_item_attr_value( self, utils, 'rmtree_', utils.fake_error(IOError)) path2 = mkdtemp(self) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') utils.rmtree(path2) self.assertIn("rmtree failed to remove", str(w[-1].message))
Example #10
Source File: app.py From sanic with MIT License | 6 votes |
def register_blueprint(self, *args, **kwargs): """ Proxy method provided for invoking the :func:`blueprint` method .. note:: To be deprecated in 1.0. Use :func:`blueprint` instead. :param args: Blueprint object or (list, tuple) thereof :param kwargs: option dictionary with blueprint defaults :return: None """ if self.debug: warnings.simplefilter("default") warnings.warn( "Use of register_blueprint will be deprecated in " "version 1.0. Please use the blueprint method" " instead", DeprecationWarning, ) return self.blueprint(*args, **kwargs)
Example #11
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter("ignore", category)
Example #12
Source File: checkwarns.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def __enter__(self): warnings.simplefilter('error') self.added = warnings.filters[0]
Example #13
Source File: test_pytree.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def test_deprecated_prefix_methods(self): l = pytree.Leaf(100, "foo") with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) self.assertEqual(l.get_prefix(), "") l.set_prefix("hi") self.assertEqual(l.prefix, "hi") self.assertEqual(len(w), 2) for warning in w: self.assertTrue(warning.category is DeprecationWarning) self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ "use the prefix property") self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ "use the prefix property")
Example #14
Source File: basecase.py From pyGSTi with Apache License 2.0 | 5 votes |
def assertWarns(self, callable, *args, **kwds): with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter('always') result = callable(*args, **kwds) self.assertTrue(len(warning_list) > 0) return result
Example #15
Source File: basecase.py From pyGSTi with Apache License 2.0 | 5 votes |
def assertNoWarnings(self, callable, *args, **kwds): with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter('always') result = callable(*args, **kwds) self.assertTrue(len(warning_list) == 0) return result
Example #16
Source File: base.py From baseband with GNU General Public License v3.0 | 5 votes |
def get_header0(self, kwargs): """Get header0 from kwargs or construct it from kwargs. Possible keyword arguments will be popped from kwargs. """ header0 = kwargs.get('header0', None) if header0 is None: tried = {key: value for key, value in kwargs.items() if key not in self.non_header_keys} with warnings.catch_warnings(): # Ignore possible warnings about extraneous arguments. warnings.simplefilter('ignore') header0 = self.header_class.fromvalues(**tried) # Pop the kwargs that we likely used. We do this by inspection, # but note that this may still let extraneous keywords # by eaten up by header classes that just store everything. maybe_used = ( set(inspect.signature(self.header_class.fromvalues).parameters) | set(self.header_class._properties) | set(header0.keys())) maybe_used = {key.lower() for key in maybe_used} used = set(key for key in tried if key.lower() in maybe_used) for key in used: kwargs.pop(key) return header0
Example #17
Source File: file_info.py From baseband with GNU General Public License v3.0 | 5 votes |
def header0(self): """Header of the first frame in the file.""" # Here, we do not even know whether the file is open or whether we # have the right format. We thus use a try/except and filter out all # warnings. with self._parent.temporary_offset(0) as fh: with warnings.catch_warnings(): warnings.simplefilter('ignore') return fh.read_header()
Example #18
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter("ignore", category)
Example #19
Source File: __init__.py From jawfish with MIT License | 5 votes |
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter('ignore', category)
Example #20
Source File: base.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
def __enter__(self): # The __warningregistry__'s need to be in a pristine state for tests # to work properly. for v in sys.modules.values(): if getattr(v, '__warningregistry__', None): v.__warningregistry__ = {} self.warnings_manager = warnings.catch_warnings(record=True) self.warnings = self.warnings_manager.__enter__() warnings.simplefilter("always", self.expected) return self
Example #21
Source File: lineup_optimizer.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def set_team_stacking(self, stacks: Optional[List[int]], for_positions: Optional[List[str]] = None): warnings.simplefilter('always', DeprecationWarning) warnings.warn('set_team_stacking method will be removed in 3.2, use add_stack instead', DeprecationWarning) if stacks: team_stacks = [TeamStack(stack, for_positions=for_positions, max_exposure_per_team=self.teams_exposures) for stack in stacks] for stack in team_stacks: self.add_stack(stack)
Example #22
Source File: lineup_optimizer.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def set_positions_for_same_team(self, *positions_stacks: List[Union[str, Tuple[str, ...]]]): warnings.simplefilter('always', DeprecationWarning) warnings.warn('set_positions_for_same_team method will be removed in 3.2, use add_stack instead', DeprecationWarning) if positions_stacks and positions_stacks[0] is not None: team_stacks = [ PositionsStack(stack, max_exposure_per_team=self.teams_exposures) for stack in positions_stacks] for stack in team_stacks: self.add_stack(stack)
Example #23
Source File: runner.py From firefox_decrypt with GNU General Public License v3.0 | 5 votes |
def run(self, test): result = self._makeResult() registerResult(result) result.failfast = self.failfast result.buffer = self.buffer with warnings.catch_warnings(): if getattr(self, "warnings", None): # if self.warnings is set, use it to filter all the warnings warnings.simplefilter(self.warnings) # if the filter is 'default' or 'always', special-case the # warnings from the deprecated unittest methods to show them # no more than once per module, because they can be fairly # noisy. The -Wd and -Wa flags can be used to bypass this # only when self.warnings is None. if self.warnings in ['default', 'always']: warnings.filterwarnings( 'module', category=DeprecationWarning, message='Please use assert\w+ instead.') startTestRun = getattr(result, 'startTestRun', None) if startTestRun is not None: result.total_tests = test.countTestCases() startTestRun() try: test(result) finally: stopTestRun = getattr(result, 'stopTestRun', None) if stopTestRun is not None: stopTestRun() return result
Example #24
Source File: classic.py From gist-alfred with MIT License | 5 votes |
def __call__(self, wrapped): """ Decorate your class or function. :param wrapped: Wrapped class or function. :return: the decorated class or function. .. versionchanged:: 1.2.4 Don't pass arguments to :meth:`object.__new__` (other than *cls*). """ if inspect.isclass(wrapped): old_new1 = wrapped.__new__ def wrapped_cls(cls, *args, **kwargs): msg = self.get_deprecated_msg(wrapped, None) with warnings.catch_warnings(): warnings.simplefilter(self.action, self.category) warnings.warn(msg, category=self.category, stacklevel=2) if old_new1 is object.__new__: return old_new1(cls) # actually, we don't know the real signature of *old_new1* return old_new1(*args, **kwargs) wrapped.__new__ = classmethod(wrapped_cls) return wrapped
Example #25
Source File: __init__.py From gist-alfred with MIT License | 5 votes |
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter('ignore', category)
Example #26
Source File: core_library.py From toonapilib with MIT License | 5 votes |
def is_venv_created(): warnings.simplefilter("ignore", ResourceWarning) dev_null = open(os.devnull, 'w') venv = Popen(['pipenv', '--venv'], stdout=PIPE, stderr=dev_null).stdout.read().strip() return True if venv else False
Example #27
Source File: test_mole.py From pyscf with Apache License 2.0 | 5 votes |
def test_dumps_loads(self): import warnings mol1 = gto.M() mol1.x = lambda *args: None with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") d = mol1.dumps() self.assertTrue(w[0].category, UserWarning) mol1.loads(mol0.dumps())
Example #28
Source File: nevpt2.py From pyscf with Apache License 2.0 | 5 votes |
def sc_nevpt(mc, ci=None, verbose=None): import warnings with warnings.catch_warnings(): warnings.simplefilter("once") warnings.warn('API updates: function sc_nevpt is deprecated feature. ' 'It will be removed in future release.\n' 'It is recommended to run NEVPT2 with new function ' 'mrpt.NEVPT(mc).kernel()') if ci is not None: warnings.warn('API updates: The kwarg "ci" has no effects. ' 'Use mrpt.NEVPT(mc,root=?) for excited state.') return NEVPT(mc).kernel() # register NEVPT2 in MCSCF
Example #29
Source File: df_ao2mo.py From pyscf with Apache License 2.0 | 5 votes |
def warn_pbc2d_eri(mydf): cell = mydf.cell if cell.dimension == 2 and cell.low_dim_ft_type == 'inf_vacuum': with warnings.catch_warnings(): warnings.simplefilter('once', PBC2DIntegralsWarning) warnings.warn('\nERIs of PBC-2D systems with infinity vacuum are ' 'singular. cell.low_dim_ft_type = None should be ' 'set.\n')
Example #30
Source File: imp.py From jawfish with MIT License | 5 votes |
def load_module(name, file, filename, details): """**DEPRECATED** Load a module, given information returned by find_module(). The module name must include the full package name, if any. """ suffix, mode, type_ = details with warnings.catch_warnings(): warnings.simplefilter('ignore') if mode and (not mode.startswith(('r', 'U')) or '+' in mode): raise ValueError('invalid file open mode {!r}'.format(mode)) elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: msg = 'file object required for import (type code {})'.format(type_) raise ValueError(msg) elif type_ == PY_SOURCE: return load_source(name, filename, file) elif type_ == PY_COMPILED: return load_compiled(name, filename, file) elif type_ == C_EXTENSION and load_dynamic is not None: if file is None: with open(filename, 'rb') as opened_file: return load_dynamic(name, filename, opened_file) else: return load_dynamic(name, filename, file) elif type_ == PKG_DIRECTORY: return load_package(name, filename) elif type_ == C_BUILTIN: return init_builtin(name) elif type_ == PY_FROZEN: return init_frozen(name) else: msg = "Don't know how to import {} (type code {})".format(name, type_) raise ImportError(msg, name=name)