Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2dfe4de

Browse files
committed
Added support for including the filename in IOErrors and OSErrors that
involve a filesystem path. To that end: - Changed IOError to EnvironmentError and added a hack which checks for arg of len 3. When constructed with a 3-tuple, the third item is the filename and this is squirreled away in the `filename' attribute. However, for in-place unpacking backwards compatibility, self.args still only gets the first two items. Added a __str__() which prints the filename if it is given. - IOError now inherits from EnvironmentError - New class OSError which also inherits from EnvironmentError and is used by the posix module.
1 parent d086a1a commit 2dfe4de

1 file changed

Lines changed: 32 additions & 3 deletions

File tree

Lib/exceptions.py

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,15 +80,44 @@ def __init__(self, *args):
8080
def __str__(self):
8181
return str(self.msg)
8282

83-
class IOError(StandardError):
83+
class EnvironmentError(StandardError):
84+
"""Base class for exceptions that occur outside the Python system.
85+
Primarily used as a base class for OSError and IOError."""
8486
def __init__(self, *args):
8587
self.args = args
8688
self.errno = None
8789
self.strerror = None
90+
self.filename = None
91+
if len(args) == 3:
92+
# open() errors give third argument which is the filename. BUT,
93+
# so common in-place unpacking doesn't break, e.g.:
94+
#
95+
# except IOError, (errno, strerror):
96+
#
97+
# we hack args so that it only contains two items. This also
98+
# means we need our own __str__() which prints out the filename
99+
# when it was supplied.
100+
self.errno, self.strerror, self.filename = args
101+
self.args = args[0:2]
88102
if len(args) == 2:
89103
# common case: PyErr_SetFromErrno()
90-
self.errno = args[0]
91-
self.strerror = args[1]
104+
self.errno, self.strerror = args
105+
106+
def __str__(self):
107+
if self.filename:
108+
return '[Errno %d] %s: %s' % (self.errno, self.strerror,
109+
self.filename)
110+
elif self.errno and self.strerror:
111+
return '[Errno %d] %s' % (self.errno, self.strerror)
112+
else:
113+
return StandardError.__str__(self)
114+
115+
class IOError(EnvironmentError):
116+
pass
117+
118+
class OSError(EnvironmentError):
119+
"""Used by the posix module."""
120+
pass
92121

93122
class RuntimeError(StandardError):
94123
pass

0 commit comments

Comments
 (0)