Python warnings.warn_explicit() Examples

The following are 30 code examples of warnings.warn_explicit(). 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 also want to check out all available functions/classes of the module warnings , or try the search function .
Example #1
Source File: decorators.py    From arches with 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
Source File: deprecated.py    From hgvs with 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
Source File: frontend.py    From faces with 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
Source File: frontend.py    From faces with 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
Source File: jelly.py    From Safejumper-for-Desktop with 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
Source File: frontend.py    From deepWordBug with 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
Source File: param_police.py    From scanpy with 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
Source File: core.py    From jams with 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
Source File: gccxmlparser.py    From royal-chaos with 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
Source File: gccxmlparser.py    From royal-chaos with 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
Source File: __init__.py    From Fluid-Designer with 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
Source File: utils.py    From TensorFlow_DCIGN with 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
Source File: jelly.py    From learn_python3_spider with 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
Source File: frontend.py    From bash-lambda-layer with 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
Source File: test_warnings.py    From ironpython3 with 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
Source File: frontend.py    From cadquery-freecad-module with 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
Source File: frontend.py    From AWS-Transit-Gateway-Demo-MultiAccount with 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
Source File: frontend.py    From AWS-Transit-Gateway-Demo-MultiAccount with 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
Source File: frontend.py    From blackmamba with 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
Source File: frontend.py    From aws-extender with 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
Source File: deprecation.py    From apm-agent-python with 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
Source File: langhelpers.py    From stdm with 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
Source File: util.py    From kcsrv with 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
Source File: misc.py    From tellurium with 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
Source File: __init__.py    From Project-New-Reign---Nemesis-Main with 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
Source File: ecat.py    From me-ica with 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
Source File: deprecation.py    From earthengine with 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
Source File: python.py    From python-netsurv with 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
Source File: nodes.py    From python-netsurv with 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
Source File: rewrite.py    From python-netsurv with 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, [])