How to use the future.utils.raise_from function in future

To help you get started, we’ve selected a few future examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github taverntesting / tavern / tavern / util / dict_util.py View on Github external
for (_, field_name, _, _) in would_format:
        if field_name is None:
            continue

        try:
            would_replace = formatter.get_field(field_name, [], box_vars)[0]
        except KeyError as e:
            logger.error(
                "Failed to resolve string [%s] with variables [%s]", to_format, box_vars
            )
            logger.error("Key(s) not found in format: %s", field_name)
            raise_from(exceptions.MissingFormatError(field_name), e)
        except IndexError as e:
            logger.error("Empty format values are invalid")
            raise_from(exceptions.MissingFormatError(field_name), e)
        else:
            if not isinstance(would_replace, (str, ustr, int, float)):
                logger.warning(
                    "Formatting '%s' will result in it being coerced to a string (it is a %s)",
                    field_name,
                    type(would_replace),
                )

    return to_format.format(**box_vars)
github splitio / python-client / splitio / api / telemetry.py View on Github external
"""
        bulk = self._build_counters(counters)
        try:
            response = self._client.post(
                'events',
                '/metrics/counters',
                self._apikey,
                body=bulk,
                extra_headers=self._metadata
            )
            if not 200 <= response.status_code < 300:
                raise APIException(response.body, response.status_code)
        except HttpClientException as exc:
            self._logger.error('Http client is throwing exceptions')
            self._logger.debug('Error: ', exc_info=True)
            raise_from(APIException('Counters not flushed correctly.'), exc)
github opencobra / cobrapy / cobra / core / reaction.py View on Github external
-8.673617379884035e-18
        >>> solution.reduced_costs.PFK
        -8.6736173798840355e-18
        """
        try:
            check_solver_status(self._model.solver.status)
            return self.forward_variable.dual - self.reverse_variable.dual
        except AttributeError:
            raise RuntimeError(
                "reaction '{}' is not part of a model".format(self.id))
        # Due to below all-catch, which sucks, need to reraise these.
        except (RuntimeError, OptimizationError) as err:
            raise_with_traceback(err)
        # Would love to catch CplexSolverError and GurobiError here.
        except Exception as err:
            raise_from(OptimizationError(
                "Likely no solution exists. Original solver message: {}."
                "".format(str(err))), err)
github ecederstrand / exchangelib / exchangelib / autodiscover.py View on Github external
except RedirectError as e:
        redirect_url, redirect_hostname, redirect_has_ssl = e.url, e.server, e.has_ssl
        log.debug('We were redirected to %s', redirect_url)
        if redirect_hostname.startswith('www.'):
            # Try the process on the new host, without 'www'. This is beyond the autodiscover protocol and an attempt to
            # work around seriously misconfigured Exchange servers. It's probably better to just show the Exchange
            # admins the report from https://testconnectivity.microsoft.com
            redirect_hostname = redirect_hostname[4:]
        canonical_hostname = _get_canonical_name(redirect_hostname)
        if canonical_hostname:
            log.debug('Canonical hostname is %s', canonical_hostname)
            redirect_hostname = canonical_hostname
        if redirect_hostname == hostname:
            log.debug('We were redirected to the same host')
            raise_from(AutoDiscoverFailed('We were redirected to the same host'), None)
        raise_from(RedirectError(url='%s://%s' % ('https' if redirect_has_ssl else 'http', redirect_hostname)), None)
github Isilon / isilon_hadoop_tools / src / isilon_hadoop_tools / onefs.py View on Github external
def _refresh_sdk(self):
        try:
            self._revision = self.revision()  # pylint: disable=attribute-defined-outside-init
        except AttributeError as exc:
            raise_from(UndeterminableVersion, exc)
        self._sdk = sdk_for_revision(self._revision)
github splitio / python-client / splitio / api / impressions.py View on Github external
"""
        bulk = self._build_bulk(impressions)
        try:
            response = self._client.post(
                'events',
                '/testImpressions/bulk',
                self._apikey,
                body=bulk,
                extra_headers=self._metadata
            )
            if not 200 <= response.status_code < 300:
                raise APIException(response.body, response.status_code)
        except HttpClientException as exc:
            self._logger.error('Http client is throwing exceptions')
            self._logger.debug('Error: ', exc_info=True)
            raise_from(APIException('Impressions not flushed properly.'), exc)
github HIPS / autograd / autograd / errors.py View on Github external
def add_extra_error_message(e):
    etype, value, traceback = sys.exc_info()
    extra_message = check_common_errors(type(e), str(e))

    if extra_message:
        if sys.version_info >= (3,):
            raise_from(AutogradHint(extra_message), e)
        else:
            raise_(AutogradHint, (extra_message, etype, value), traceback)
    return etype, value, traceback
github splitio / python-client / splitio / storage / adapters / redis.py View on Github external
def keys(self, pattern):
        """Mimic original redis function but using user custom prefix."""
        try:
            return [
                _bytes_to_string(key)
                for key in self._remove_prefix(self._decorated.keys(self._add_prefix(pattern)))
            ]
        except RedisError as exc:
            raise_from(RedisAdapterException('Failed to execute keys operation'), exc)
github odlgroup / odl / odl / operator / operator.py View on Github external
raise TypeError('`out` parameter cannot be used '
                                'when range is a field')

            self._call_in_place(x, out=out, **kwargs)

        else:  # Out-of-place evaluation
            out = self._call_out_of_place(x, **kwargs)

            if out not in self.range:
                try:
                    out = self.range.element(out)
                except (TypeError, ValueError) as err:
                    new_exc = OpRangeError(
                        'unable to cast {!r} to an element of '
                        'the range {}.'.format(out, self.range))
                    raise_from(new_exc, err)
        return out
github nipy / nipype / nipype / utils / misc.py View on Github external
--------
    package_check('numpy', '1.3')
    package_check('scipy', '0.7', 'tutorial1')

    """

    if app:
        msg = '%s requires %s' % (app, pkg_name)
    else:
        msg = 'Nipype requires %s' % pkg_name
    if version:
        msg += ' with version >= %s' % (version, )
    try:
        mod = __import__(pkg_name)
    except ImportError as e:
        raise_from(exc_failed_import(msg), e)
    if not version:
        return
    try:
        have_version = mod.__version__
    except AttributeError as e:
        raise_from(
            exc_failed_check('Cannot find version for %s' % pkg_name), e)
    if checker(have_version) < checker(version):
        raise exc_failed_check(msg)