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')
python类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 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 _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 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 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 __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 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 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 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 __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)
frontend.py 文件源码
项目:tf_aws_ecs_instance_draining_on_scale_in
作者: terraform-community-modules
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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 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(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 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)