def prompt_bool(self, name, default=False):
warnings.warn_explicit(
"Command.prompt_bool is deprecated, use prompt_bool() function "
"instead")
prompt_bool(name, default)
python类warn_explicit()的实例源码
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 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 _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 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(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 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 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 _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 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 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