Python warnings.warn_explicit() Examples

The following are 30 code examples for showing how to use warnings.warn_explicit(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module warnings , or try the search function .

Example 1
Project: arches   Author: archesproject   File: decorators.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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.simplefilter("always", DeprecationWarning)  # turn off filter
        warnings.warn_explicit(
            "Call to deprecated function {}.".format(func.__name__),
            category=DeprecationWarning,
            filename=func.__code__.co_filename,
            lineno=func.__code__.co_firstlineno + 1,
        )
        warnings.simplefilter("default", DeprecationWarning)  # reset filter
        logger.warn(
            "%s - DeprecationWarning: Call to deprecated function %s. %s:%s"
            % (datetime.datetime.now(), func.__name__, func.__code__.co_filename, func.__code__.co_firstlineno + 1)
        )
        return func(*args, **kwargs)

    return new_func 
Example 2
Project: hgvs   Author: biocommons   File: deprecated.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 3
Project: faces   Author: skarlekar   File: frontend.py    License: GNU General Public License v2.0 6 votes vote down vote up
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') 
Example 4
Project: faces   Author: skarlekar   File: frontend.py    License: GNU General Public License v2.0 6 votes vote down vote up
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') 
Example 5
Project: Safejumper-for-Desktop   Author: proxysh   File: jelly.py    License: GNU General Public License v2.0 6 votes vote down vote up
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]) 
Example 6
Project: deepWordBug   Author: QData   File: frontend.py    License: Apache License 2.0 6 votes vote down vote up
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') 
Example 7
Project: scanpy   Author: theislab   File: param_police.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def show_param_warnings(app, exception):
    import inspect

    for (fname, fun), params in param_warnings.items():
        _, line = inspect.getsourcelines(fun)
        file_name = inspect.getsourcefile(fun)
        params_str = '\n'.join(f'\t{n}: {t}' for n, t in params)
        warnings.warn_explicit(
            f'\nParameters in `{fname}` have types in docstring.\n'
            f'Replace them with type annotations.\n{params_str}',
            UserWarning,
            file_name,
            line,
        )
    if param_warnings:
        raise RuntimeError('Encountered text parameter type. Use annotations.') 
Example 8
Project: jams   Author: marl   File: core.py    License: ISC License 6 votes vote down vote up
def deprecated(version, version_removed):
    '''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 __wrapper(func, *args, **kwargs):
        '''Warn the user, and then proceed.'''
        code = six.get_function_code(func)
        warnings.warn_explicit(
            "{:s}.{:s}\n\tDeprecated as of JAMS version {:s}."
            "\n\tIt will be removed in JAMS version {:s}."
            .format(func.__module__, func.__name__,
                    version, version_removed),
            category=DeprecationWarning,
            filename=code.co_filename,
            lineno=code.co_firstlineno + 1
        )
        return func(*args, **kwargs)

    return decorator(__wrapper) 
Example 9
Project: royal-chaos   Author: KTH   File: gccxmlparser.py    License: MIT License 6 votes vote down vote up
def handle_error(self, wrapper, exception, traceback_):
        if hasattr(wrapper, "gccxml_definition"):
            definition = wrapper.gccxml_definition
        elif hasattr(wrapper, "main_wrapper"):
            try:
                definition = wrapper.main_wrapper.gccxml_definition
            except AttributeError:
                definition = None
        else:
            definition = None

        if definition is None:
            print("exception %r in wrapper %s" % (exception, wrapper), file=sys.stderr)
        else:
            warnings.warn_explicit("exception %r in wrapper for %s"
                                   % (exception, definition),
                                   WrapperWarning, definition.location.file_name,
                                   definition.location.line)
        return True 
Example 10
Project: royal-chaos   Author: KTH   File: gccxmlparser.py    License: MIT License 6 votes vote down vote up
def _get_calldef_exceptions(self, calldef):
        retval = []
        for decl in calldef.exceptions:
            traits = ctypeparser.TypeTraits(normalize_name(decl.partial_decl_string))
            if traits.type_is_reference:
                name = str(traits.target)
            else:
                name = str(traits.ctype)
            exc = self.type_registry.root_module.get(name, None)
            if isinstance(exc, CppException):
                retval.append(exc)
            else:
                warnings.warn_explicit("Thrown exception '%s' was not previously detected as an exception class."
                                       " PyBindGen bug?"
                                       % (normalize_name(decl.partial_decl_string)),
                                       WrapperWarning, calldef.location.file_name, calldef.location.line)
        return retval 
Example 11
Project: Fluid-Designer   Author: Microvellum   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
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, "__init__.py",
                                    42)
            self.assertEqual(w[-1].message, message)
            del w[:]
            self.module.warn_explicit(message, UserWarning, "__init__.py",
                                    13)
            self.assertEqual(len(w), 0)
            self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
                                    42)
            self.assertEqual(len(w), 0) 
Example 12
Project: TensorFlow_DCIGN   Author: yselivonchyk   File: utils.py    License: MIT License 6 votes vote down vote up
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 
Example 13
Project: learn_python3_spider   Author: wistbean   File: jelly.py    License: MIT License 6 votes vote down vote up
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]) 
Example 14
Project: bash-lambda-layer   Author: gkrizek   File: frontend.py    License: MIT License 6 votes vote down vote up
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') 
Example 15
Project: ironpython3   Author: IronLanguages   File: test_warnings.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 16
Project: cadquery-freecad-module   Author: jmwright   File: frontend.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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') 
Example 17
Project: AWS-Transit-Gateway-Demo-MultiAccount   Author: MattTunny   File: frontend.py    License: MIT License 6 votes vote down vote up
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') 
Example 18
Project: AWS-Transit-Gateway-Demo-MultiAccount   Author: MattTunny   File: frontend.py    License: MIT License 6 votes vote down vote up
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') 
Example 19
Project: blackmamba   Author: zrzka   File: frontend.py    License: MIT License 6 votes vote down vote up
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') 
Example 20
Project: aws-extender   Author: VirtueSecurity   File: frontend.py    License: MIT License 6 votes vote down vote up
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') 
Example 21
Project: apm-agent-python   Author: elastic   File: deprecation.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 22
Project: stdm   Author: gltn   File: langhelpers.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 23
Project: kcsrv   Author: KanColleTool   File: util.py    License: MIT License 6 votes vote down vote up
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 
Example 24
Project: tellurium   Author: sys-bio   File: misc.py    License: Apache License 2.0 6 votes vote down vote up
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

# ---------------------------------------------------------------------
# Running external tools
# --------------------------------------------------------------------- 
Example 25
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
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, "__init__.py",
                                    42)
            self.assertEqual(w[-1].message, message)
            del w[:]
            self.module.warn_explicit(message, UserWarning, "__init__.py",
                                    13)
            self.assertEqual(len(w), 0)
            self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
                                    42)
            self.assertEqual(len(w), 0) 
Example 26
Project: me-ica   Author: ME-ICA   File: ecat.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_frame_order(self):
        """Returns the order of the frames stored in the file
        Sometimes Frames are not stored in the file in
        chronological order, this can be used to extract frames
        in correct order

        Returns
        -------
        id_dict: dict mapping frame number -> [mlist_row, mlist_id]

        (where mlist id is value in the first column of the mlist matrix )

        Examples
        --------
        >>> import os
        >>> import nibabel as nib
        >>> nibabel_dir = os.path.dirname(nib.__file__)
        >>> from nibabel import ecat
        >>> ecat_file = os.path.join(nibabel_dir,'tests','data','tinypet.v')
        >>> img = ecat.load(ecat_file)
        >>> mlist = img.get_mlist()
        >>> mlist.get_frame_order()
        {0: [0, 16842758]}
        """
        mlist  = self._mlist
        ids = mlist[:, 0].copy()
        n_valid = np.sum(ids > 0)
        ids[ids <=0] = ids.max() + 1 # put invalid frames at end after sort
        valid_order = np.argsort(ids)
        if not all(valid_order == sorted(valid_order)):
            #raise UserWarning if Frames stored out of order
            warnings.warn_explicit('Frames stored out of order;'\
                          'true order = %s\n'\
                          'frames will be accessed in order '\
                          'STORED, NOT true order'%(valid_order),
                          UserWarning,'ecat', 0)
        id_dict = {}
        for i in range(n_valid):
            id_dict[i] = [valid_order[i], ids[valid_order[i]]]

        return id_dict 
Example 27
Project: earthengine   Author: mortcanty   File: deprecation.py    License: MIT License 5 votes vote down vote up
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 
Example 28
Project: python-netsurv   Author: sofia-netsurv   File: python.py    License: MIT License 5 votes vote down vote up
def pytest_pycollect_makeitem(collector, name, obj):
    outcome = yield
    res = outcome.get_result()
    if res is not None:
        return
    # nothing was collected elsewhere, let's do it here
    if safe_isclass(obj):
        if collector.istestclass(obj, name):
            outcome.force_result(Class(name, parent=collector))
    elif collector.istestfunction(obj, name):
        # mock seems to store unbound methods (issue473), normalize it
        obj = getattr(obj, "__func__", obj)
        # We need to try and unwrap the function if it's a functools.partial
        # or a funtools.wrapped.
        # We musn't if it's been wrapped with mock.patch (python 2 only)
        if not (inspect.isfunction(obj) or inspect.isfunction(get_real_func(obj))):
            filename, lineno = getfslineno(obj)
            warnings.warn_explicit(
                message=PytestCollectionWarning(
                    "cannot collect %r because it is not a function." % name
                ),
                category=None,
                filename=str(filename),
                lineno=lineno + 1,
            )
        elif getattr(obj, "__test__", True):
            if is_generator(obj):
                res = Function(name, parent=collector)
                reason = deprecated.YIELD_TESTS.format(name=name)
                res.add_marker(MARK_GEN.xfail(run=False, reason=reason))
                res.warn(PytestCollectionWarning(reason))
            else:
                res = list(collector._genfunctions(name, obj))
            outcome.force_result(res) 
Example 29
Project: python-netsurv   Author: sofia-netsurv   File: nodes.py    License: MIT License 5 votes vote down vote up
def warn(self, warning):
        """Issue a warning for this item.

        Warnings will be displayed after the test session, unless explicitly suppressed

        :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.

        :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.

        Example usage:

        .. code-block:: python

            node.warn(PytestWarning("some message"))

        """
        from _pytest.warning_types import PytestWarning

        if not isinstance(warning, PytestWarning):
            raise ValueError(
                "warning must be an instance of PytestWarning or subclass, got {!r}".format(
                    warning
                )
            )
        path, lineno = get_fslocation_from_item(self)
        warnings.warn_explicit(
            warning,
            category=None,
            filename=str(path),
            lineno=lineno + 1 if lineno is not None else None,
        )

    # methods for ordering nodes 
Example 30
Project: python-netsurv   Author: sofia-netsurv   File: rewrite.py    License: MIT License 5 votes vote down vote up
def warn_about_none_ast(self, node, module_path, lineno):
        """
        Returns an AST issuing a warning if the value of node is `None`.
        This is used to warn the user when asserting a function that asserts
        internally already.
        See issue #3191 for more details.
        """

        # Using parse because it is different between py2 and py3.
        AST_NONE = ast.parse("None").body[0].value
        val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE])
        send_warning = ast.parse(
            """\
from _pytest.warning_types import PytestAssertRewriteWarning
from warnings import warn_explicit
warn_explicit(
    PytestAssertRewriteWarning('asserting the value None, please use "assert is None"'),
    category=None,
    filename={filename!r},
    lineno={lineno},
)
            """.format(
                filename=module_path, lineno=lineno
            )
        ).body
        return ast.If(val_is_none, send_warning, [])