Skip to content

Commit ded92ee

Browse files
committed
Fixes for raise_from()
1 parent 76a2e32 commit ded92ee

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

docs/whatsnew.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ What's new in version 0.12.5
1313
(issue #81). It still converts ``obj.next()`` method calls to
1414
``next(obj)`` correctly.
1515
- Add :ref:`compatible-idioms` from Ed Schofield's PyConAU 2014 talk.
16+
- Add ``future.utils.raise_from`` as an equivalent to Py3's ``raise ... from ...`` syntax (issue #86).
1617

1718

1819
.. whats-new-0.12.4:

future/utils/__init__.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -411,9 +411,27 @@ def raise_from(exc, cause):
411411
412412
on Python 3. (See PEP 3134).
413413
"""
414-
exc_copy = copy.copy(exc)
415-
exc_copy.__cause__ = cause
416-
raise exc_copy
414+
# Is either arg an exception class (e.g. IndexError) rather than
415+
# instance (e.g. IndexError('my message here')? If so, pass the
416+
# name of the class undisturbed through to "raise ... from ...".
417+
if isinstance(exc, type) and issubclass(exc, Exception):
418+
e = exc()
419+
# exc = exc.__name__
420+
# execstr = "e = " + _repr_strip(exc) + "()"
421+
# myglobals, mylocals = _get_caller_globals_and_locals()
422+
# exec(execstr, myglobals, mylocals)
423+
else:
424+
e = exc
425+
if isinstance(cause, type) and issubclass(cause, Exception):
426+
e.__cause__ = cause()
427+
elif cause is None:
428+
e.__cause__ = None
429+
elif isinstance(cause, BaseException):
430+
e.__cause__ = cause
431+
else:
432+
raise TypeError("exception causes must derive from BaseException")
433+
e.__context__ = sys.exc_info()[1]
434+
raise e
417435

418436
exec('''
419437
def raise_(tp, value=None, tb=None):

0 commit comments

Comments
 (0)