我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用warnings.warn_explicit()。
def handle_old_config(self, filename): warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, filename, 0) options = self.get_section('options') if not self.has_section('general'): self.add_section('general') for key, value in options.items(): if key in self.old_settings: section, setting = self.old_settings[key] if not self.has_section(section): self.add_section(section) else: section = 'general' setting = key if not self.has_option(section, setting): self.set(section, setting, value) self.remove_section('options')
def warn(msg, stacklevel=3): """Issue a warning. If msg is a string, :class:`.exc.SAWarning` is used as the category. .. note:: This function is swapped out when the test suite runs, with a compatible version that uses warnings.warn_explicit, so that the warnings registry can be controlled. """ if isinstance(msg, compat.string_types): warnings.warn(msg, exc.SAWarning, stacklevel=stacklevel) else: warnings.warn(msg, stacklevel=stacklevel)
def deprecated(alternative=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def real_decorator(func): @functools.wraps(func) def new_func(*args, **kwargs): msg = "Call to deprecated function {0}.".format(func.__name__) if alternative: msg += " Use {0} instead".format(alternative) warnings.warn_explicit( msg, category=DeprecationWarning, filename=compat.get_function_code(func).co_filename, lineno=compat.get_function_code(func).co_firstlineno + 1 ) return func(*args, **kwargs) return new_func return real_decorator
def _raise_typecheck_error(msg, is_return=False, value=None, received_type=None, expected_type=None, func=None): if pytypes.warning_mode: import traceback tb = traceback.extract_stack() off = util._calc_traceback_list_offset(tb) cat = pytypes.ReturnTypeWarning if is_return else pytypes.InputTypeWarning warn_explicit(msg, cat, tb[off][0], tb[off][1]) # if not func is None: # warn_explicit(msg, cat, func.__code__.co_filename, # func.__code__.co_firstlineno, func.__module__) # else: # warn(msg, pytypes.ReturnTypeWarning) else: if is_return: raise pytypes.ReturnTypeError(msg) else: raise pytypes.InputTypeError(msg)
def warn(msg, stacklevel=3): """Issue a warning. If msg is a string, :class:`.exc.SAWarning` is used as the category. .. note:: This function is swapped out when the test suite runs, with a compatible version that uses warnings.warn_explicit, so that the warnings registry can be controlled. """ if isinstance(msg, basestring): warnings.warn(msg, exc.SAWarning, stacklevel=stacklevel) else: warnings.warn(msg, stacklevel=stacklevel)
def deprecated(func): """Mark functions as deprecated. Using this decorator on a function or methos will emit a warning when the function is called. From http://wiki.python.org/moin/PythonDecoratorLibrary """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function/method {}.".format(func.__name__), category=DeprecationWarning, filename=func.func_code.co_filename, lineno=func.func_code.co_firstlineno + 1 ) return func(*args, **kwargs) return new_func
def __call__(self, obj, *args, **kwargs): @wraps(obj) def new_func(*args, **kwargs): msg = "Call to deprecated function or class {0} ({1})".format(obj.__name__, self.reason) if inspect.isfunction(obj): _code = self._wrap_function(obj) elif inspect.isclass(obj): _code = self._wrap_class(obj) warnings.warn_explicit( '{0}.'.format(msg), category=UserWarning, filename=_code.co_filename, lineno=_code.co_firstlineno + 1 ) return obj(*args, **kwargs) return new_func
def test_once(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) message = UserWarning("FilterTests.test_once") self.module.warn_explicit(message, UserWarning, "test_warnings.py", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "test_warnings.py", 13) self.assertEqual(len(w), 0) self.module.warn_explicit(message, UserWarning, "test_warnings2.py", 42) self.assertEqual(len(w), 0)
def execute(self, monitor): parameters = self.get_monitor_params(monitor) observables = [] try: for params in self.get_parameters_cycles(parameters): observables.extend(monitor.execute(params)) monitor.save_headers() monitor.save_last_execution() except PermissionError: warnings.warn_explicit('No permissions for monitor. Check execution perms and read perms.', UserWarning, monitor.script_path, 1) return [] new_observables = [] for observable in observables: if observable not in new_observables: new_observables.append(observable) return new_observables
def _unjelly_instance(self, rest): """ (internal) Unjelly an instance. Called to handle the deprecated I{instance} token. @param rest: The s-expression representing the instance. @return: The unjellied instance. """ warnings.warn_explicit( "Unjelly support for the instance atom is deprecated since " "Twisted 15.0.0. Upgrade peer for modern instance support.", category=DeprecationWarning, filename="", lineno=0) clz = self.unjelly(rest[0]) if not _PY3 and type(clz) is not _OldStyleClass: raise InsecureJelly("Legacy 'instance' found with new-style class") return self._genericUnjelly(clz, rest[1])
def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. https://wiki.python.org/moin/PythonDecoratorLibrary#Generating_Deprecation_Warnings """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, filename=func.func_code.co_filename, lineno=func.func_code.co_firstlineno + 1 ) return func(*args, **kwargs) return new_func
def handle_old_config(self, filename): warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, filename, 0) options = self.get_section('options') if not self.has_section('general'): self.add_section('general') for key, value in list(options.items()): if key in self.old_settings: section, setting = self.old_settings[key] if not self.has_section(section): self.add_section(section) else: section = 'general' setting = key if not self.has_option(section, setting): self.set(section, setting, value) self.remove_section('options')
def __call__(self, func): msg = "Call to deprecated function {}".format(func.__name__) if self.use_instead: msg += '; use ' + self.use_instead + ' instead' def wrapper(*args, **kwargs): fingerprint = (func.__name__, func.__code__.co_filename, func.__code__.co_firstlineno) if fingerprint not in self.seen: warnings.warn_explicit( msg, category=DeprecationWarning, filename=func.__code__.co_filename, lineno=func.__code__.co_firstlineno + 1) self.seen.update([fingerprint]) return func(*args, **kwargs) wrapper.__doc__ = "Deprecated" if self.use_instead: wrapper.__doc__ += '; use ' + self.use_instead + ' instead' return wrapper
def deprecated(func): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, filename=func.func_code.co_filename, lineno=func.func_code.co_firstlineno + 1 ) return func(*args, **kwargs) return new_func
def _deprecated_method(method, cls, method_name, msg): """Show deprecation warning about a magic method definition. Uses warn_explicit to bind warning to method definition instead of triggering code, which isn't relevant. """ warn_msg = "{classname}.{method_name} is deprecated: {msg}".format( classname=cls.__name__, method_name=method_name, msg=msg ) for parent in inspect.getmro(cls): if method_name in parent.__dict__: cls = parent break try: fname = inspect.getsourcefile(method) or "<unknown>" lineno = inspect.getsourcelines(method)[1] or 0 except (IOError, TypeError) as e: # Failed to inspect for some reason warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning) else: warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. ## Usage examples ## @deprecated def my_func(): pass @other_decorators_must_be_upper @deprecated def my_func(): pass """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function %(funcname)s." % { 'funcname': func.__name__, }, category=DeprecationWarning, filename=func.__code__.co_filename, lineno=func.__code__.co_firstlineno + 1 ) return func(*args, **kwargs) return new_func
def handle_error(self, wrapper, exception, traceback_): stack = getattr(wrapper, 'stack_where_defined', []) stack.reverse() for l in stack: if l[0] == self.apidefs_file: warnings.warn_explicit("exception %r in wrapper %s" % (exception, wrapper), Warning, l[0], l[1]) break else: warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True #print >> sys.stderr, ">>>>>>>>>>>>>>>>>>>>>>>>>>>> ", bool(eval(os.environ["GCC_RTTI_ABI_COMPLETE"]))
def deprecated(f): """Prints a deprecation warning when called.""" @functools.wraps(f) def wrapper(*args,**kw): warnings.warn_explicit("calling deprecated function %s"%f.__name__, category=DeprecationWarning, filename=f.func_code.co_filename, lineno=f.func_code.co_firstlineno+1) return f(*args,**kw) return wrapper
def deprecated(instructions): """Flags a method as deprecated. This function returns a decorator which can be used to mark deprecated functions. Applying this decorator will result in a warning being emitted when the function is used. Args: instructions (str): Specific guidance for the developer, e.g.: 'Please migrate to add_proxy(...)'' """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): message = 'Call to deprecated function {0}(...). {1}'.format( func.__name__, instructions) frame = inspect.currentframe().f_back warnings.warn_explicit(message, category=DeprecatedWarning, filename=inspect.getfile(frame.f_code), lineno=frame.f_lineno) return func(*args, **kwargs) return wrapper return decorator
def testing_warn(msg, stacklevel=3): """Replaces sqlalchemy.util.warn during tests.""" filename = "sqlalchemy.testing.warnings" lineno = 1 if isinstance(msg, util.string_types): warnings.warn_explicit(msg, sa_exc.SAWarning, filename, lineno) else: warnings.warn_explicit(msg, filename, lineno)
def prompt(self, name, default=None): warnings.warn_explicit( "Command.prompt is deprecated, use prompt() function instead") prompt(name, default)
def prompt_pass(self, name, default=None): warnings.warn_explicit( "Command.prompt_pass is deprecated, use prompt_pass() function " "instead") prompt_pass(name, default)
def prompt_bool(self, name, default=False): warnings.warn_explicit( "Command.prompt_bool is deprecated, use prompt_bool() function " "instead") prompt_bool(name, default)
def deprecated(func): '''This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.''' @functools.wraps(func) def new_func(*args, **kwargs): warnings.warn_explicit( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, filename=func.__code__.co_filename, lineno=func.__code__.co_firstlineno + 1 ) return func(*args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ new_func.__dict__.update(func.__dict__) return new_func # ## Usage examples ## # @deprecated # def my_func(): # pass # @other_decorators_must_be_upper # @deprecated # def my_func(): # pass
def _deprecated_method(method, cls, method_name, msg): """Show deprecation warning about a magic method definition. Uses warn_explicit to bind warning to method definition instead of triggering code, which isn't relevant. """ warn_msg = "{classname}.{method_name} is deprecated in traitlets 4.1: {msg}".format( classname=cls.__name__, method_name=method_name, msg=msg ) for parent in inspect.getmro(cls): if method_name in parent.__dict__: cls = parent break # limit deprecation messages to once per package package_name = cls.__module__.split('.', 1)[0] key = (package_name, msg) if not _should_warn(key): return try: fname = inspect.getsourcefile(method) or "<unknown>" lineno = inspect.getsourcelines(method)[1] or 0 except (IOError, TypeError) as e: # Failed to inspect for some reason warn(warn_msg + ('\n(inspection failed) %s' % e), DeprecationWarning) else: warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
def apply_defaults(func): warnings.warn_explicit( """ You are importing apply_defaults from airflow.utils which will be deprecated in a future version. Please use : from airflow.utils.decorators import apply_defaults """, category=PendingDeprecationWarning, filename=func.__code__.co_filename, lineno=func.__code__.co_firstlineno + 1 ) return _apply_defaults(func)
def Deprecated(message): """Returns a decorator with a given warning message.""" def Decorator(func): """Emits a deprecation warning when the decorated function is called. Also adds the deprecation message to the function's docstring. Args: func: The function to deprecate. Returns: func: The wrapped function. """ @functools.wraps(func) def Wrapper(*args, **kwargs): warnings.warn_explicit( '%s() is deprecated: %s' % (func.__name__, message), category=DeprecationWarning, filename=func.func_code.co_filename, lineno=func.func_code.co_firstlineno + 1) return func(*args, **kwargs) Wrapper.__doc__ += '\nDEPRECATED: ' + message return Wrapper return Decorator
def testing_warn(msg, stacklevel=3): """Replaces sqlalchemy.util.warn during tests.""" filename = "sqlalchemy.testing.warnings" lineno = 1 if isinstance(msg, basestring): warnings.warn_explicit(msg, sa_exc.SAWarning, filename, lineno) else: warnings.warn_explicit(msg, filename, lineno)
def Deprecated(message): """Returns a decorator with a given warning message.""" def Decorator(func): """Emits a deprecation warning when the decorated function is called. Also adds the deprecation message to the function's docstring. Args: func: The function to deprecate. Returns: func: The wrapped function. """ @functools.wraps(func) def Wrapper(*args, **kwargs): warnings.warn_explicit( '%s() is deprecated: %s' % (func.__name__, message), category=DeprecationWarning, filename=func.__code__.co_filename, lineno=func.__code__.co_firstlineno + 1) return func(*args, **kwargs) Wrapper.__doc__ += '\nDEPRECATED: ' + message return Wrapper return Decorator
def test_module_all_attribute(self): self.assertTrue(hasattr(self.module, '__all__')) target_api = ["warn", "warn_explicit", "showwarning", "formatwarning", "filterwarnings", "simplefilter", "resetwarnings", "catch_warnings"] self.assertSetEqual(set(self.module.__all__), set(target_api))
def test_mutate_filter_list(self): class X: def match(self, a): L[:] = [] L = [("default",X(),UserWarning,X(),0) for i in range(2)] with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.filters = L self.module.warn_explicit(UserWarning("b"), None, "f.py", 42) self.assertEqual(str(w[-1].message), "b")
def test_warn_explicit_non_ascii_filename(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("always", category=UserWarning) for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"): try: os.fsencode(filename) except UnicodeEncodeError: continue self.module.warn_explicit("text", UserWarning, filename, 1) self.assertEqual(w[-1].filename, filename)
def test_warn_explicit_type_errors(self): # warn_explicit() should error out gracefully if it is given objects # of the wrong types. # lineno is expected to be an integer. self.assertRaises(TypeError, self.module.warn_explicit, None, UserWarning, None, None) # Either 'message' needs to be an instance of Warning or 'category' # needs to be a subclass. self.assertRaises(TypeError, self.module.warn_explicit, None, None, None, 1) # 'registry' must be a dict or None. self.assertRaises((TypeError, AttributeError), self.module.warn_explicit, None, Warning, None, 1, registry=42)
def test_default_action(self): # Replacing or removing defaultaction should be okay. message = UserWarning("defaultaction test") original = self.module.defaultaction try: with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 42, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) # One actual registry key plus the "version" key self.assertEqual(len(registry), 2) self.assertIn("version", registry) del w[:] # Test removal. del self.module.defaultaction __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 43, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) self.assertEqual(len(registry), 2) del w[:] # Test setting. self.module.defaultaction = "ignore" __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 44, registry=registry) self.assertEqual(len(w), 0) finally: self.module.defaultaction = original