PythonCharmers/python-future

raise_from does not behave exactly like raise from

Open

#141 ouverte le 25 avr. 2015

Voir sur GitHub
 (7 commentaires) (0 réactions) (0 assignés)Python (327 forks)batch import
0.20exceptionshelp wanted

Métriques du dépôt

Stars
 (1 172 stars)
Métriques de merge PR
 (Aucune PR mergée en 30 j)

Description

Here's a bit of sample code from [https://www.python.org/dev/peps/pep-3134/](PEP 3134):

class DatabaseError(Exception):
    pass

class FileDatabase(object):
    def __init__(self, filename):
        try:
            self.file = open(filename)
        except IOError as exc:
            raise DatabaseError('failed to open') from exc

fd = FileDatabase('dne')

This, of course, does not work on Python 2. Using Python 3 I get the following output:

Traceback (most recent call last):
  File "pepex2.py", line 7, in __init__
    self.file = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'dne'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "pepex2.py", line 11, in <module>
    fd = FileDatabase('dne')
  File "pepex2.py", line 9, in __init__
    raise DatabaseError('failed to open') from exc
__main__.DatabaseError: failed to open

When using raise_from for Python2 compatibility

from future.utils import raise_from
# [...]
            raise_from(DatabaseError('failed to open'), exc)

this output (still with Python3) changes to:

FileNotFoundError: [Errno 2] No such file or directory

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "pepex2.py", line 13, in <module>
    fd = FileDatabase('dne')
  File "pepex2.py", line 11, in __init__
    raise_from(DatabaseError('failed to open'), exc)
  File "/home/marc/.virtualenvs/scratch_future3/lib/python3.3/site-packages/future/utils/__init__.py", line 382, in raise_from
    exec(execstr, myglobals, mylocals)
  File "<string>", line 1, in <module>
__main__.DatabaseError: failed to open

Note that the traceback and exception information are missing from the FileNotFoundError.

Guide contributeur