python类warn_explicit()的实例源码

commands.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def prompt_bool(self, name, default=False):
        warnings.warn_explicit(
            "Command.prompt_bool is deprecated, use prompt_bool() function "
            "instead")

        prompt_bool(name, default)
decorators.py 文件源码 项目:nelpy 作者: nelpy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
warnings.py 文件源码 项目:oa_qian 作者: sunqb 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
traitlets.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
__init__.py 文件源码 项目:incubator-airflow-old 作者: apache 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
deprecation.py 文件源码 项目:REMAP 作者: REMAPApp 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
warnings.py 文件源码 项目:pyetje 作者: rorlika 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
commands.py 文件源码 项目:pyetje 作者: rorlika 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def prompt(self, name, default=None):
        warnings.warn_explicit(
            "Command.prompt is deprecated, use prompt() function instead")

        prompt(name, default)
commands.py 文件源码 项目:pyetje 作者: rorlika 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def prompt_pass(self, name, default=None):
        warnings.warn_explicit(
            "Command.prompt_pass is deprecated, use prompt_pass() function "
            "instead")

        prompt_pass(name, default)
commands.py 文件源码 项目:pyetje 作者: rorlika 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def prompt_bool(self, name, default=False):
        warnings.warn_explicit(
            "Command.prompt_bool is deprecated, use prompt_bool() function "
            "instead")

        prompt_bool(name, default)
deprecation.py 文件源码 项目:ecodash 作者: Servir-Mekong 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
decorators.py 文件源码 项目:siphon-cli 作者: getsiphon 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
deprecation.py 文件源码 项目:aqua-monitor 作者: Deltares 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
traitlets.py 文件源码 项目:Repobot 作者: Desgard 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
deprecation.py 文件源码 项目:SurfaceWaterTool 作者: Servir-Mekong 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
test_warnings.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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))
test_warnings.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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")
test_warnings.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
test_warnings.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
test_warnings.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号