Skip to content

Commit 326662b

Browse files
committed
Make use of the raise ... from syntax in Python 3
1 parent 11a890f commit 326662b

20 files changed

+63
-53
lines changed

.pylintrc

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ disable =
2424
missing-docstring,
2525
no-self-use,
2626
protected-access,
27-
raise-missing-from,
2827
redefined-argument-from-local,
2928
redefined-outer-name
3029

webware/Application.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ def createSessionForTransaction(self, trans):
486486
except KeyError:
487487
trans.request().setSessionExpired(1)
488488
if not self.setting('IgnoreInvalidSession'):
489-
raise HTTPSessionExpired
489+
raise HTTPSessionExpired from None
490490
sessId = None
491491
if not sessId:
492492
session = self._sessionClass(trans)

webware/MiscUtils/Configurable.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,10 @@ def setting(self, name, default=NoDefault):
7070
if default is NoDefault:
7171
try:
7272
return self.config()[name]
73-
except KeyError:
73+
except KeyError as e:
7474
keys = ', '.join(sorted(self.config()))
75-
raise KeyError(f'{name} not found - config keys are: {keys}')
75+
raise KeyError(
76+
f'{name} not found - config keys are: {keys}') from e
7677
else:
7778
return self.config().get(name, default)
7879

@@ -154,7 +155,7 @@ def userConfig(self):
154155
del config[key]
155156
except Exception as e:
156157
raise ConfigurationError(
157-
f'Invalid configuration file, {filename} ({e}).')
158+
f'Invalid configuration file, {filename} ({e}).') from e
158159
return config
159160

160161
@staticmethod

webware/MiscUtils/DataTable.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ def setType(self, type_):
302302
except Exception:
303303
types = ', '.join(sorted(_types))
304304
raise DataTableError(f'Unknown type {type_!r}.'
305-
f' Known types are: {types}')
305+
f' Known types are: {types}') from None
306306
else:
307307
self._type = None
308308

@@ -699,9 +699,9 @@ def __init__(self, table, values=None, headings=None):
699699
else:
700700
try:
701701
self.initFromObject(values)
702-
except AttributeError:
702+
except AttributeError as e:
703703
raise DataTableError(
704-
f'Unknown type for values {values!r}.')
704+
f'Unknown type for values {values!r}.') from e
705705

706706
def initFromSequence(self, values):
707707
headings = self._headings
@@ -762,7 +762,7 @@ def __getitem__(self, key):
762762
return self._values[key]
763763
except TypeError:
764764
raise TypeError(f'key={key!r}, key type={type(key)!r},'
765-
f' values={self._values!r}')
765+
f' values={self._values!r}') from None
766766

767767
def __setitem__(self, key, value):
768768
if isinstance(key, str):

webware/MiscUtils/DateInterval.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,5 +60,5 @@ def timeDecode(s):
6060
try:
6161
time += int(match[:-1]) * timeValues[char]
6262
except KeyError:
63-
raise ValueError(f'Invalid unit of time: {char}')
63+
raise ValueError(f'Invalid unit of time: {char}') from None
6464
return time

webware/MiscUtils/NamedValueAccess.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def valueForKey(obj, key, default=NoDefault):
6262
try:
6363
return obj[key]
6464
except KeyError:
65-
raise ValueForKeyError(key)
65+
raise ValueForKeyError(key) from None
6666
else:
6767
return obj.get(key, default)
6868
else:

webware/MiscUtils/PickleRPC.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -373,9 +373,9 @@ class SafeTransport(Transport):
373373

374374
def make_connection(self, host, port=None, key_file=None, cert_file=None):
375375
"""Create an HTTPS connection object from a host descriptor."""
376-
import http.client
377376
try:
378-
return http.client.HTTPSConnection(host, port, key_file, cert_file)
379-
except AttributeError:
377+
from http.client import HTTPSConnection
378+
except ImportError as e:
380379
raise NotImplementedError(
381-
"Your version of http.client doesn't support HTTPS")
380+
"Your version of http.client doesn't support HTTPS") from e
381+
return HTTPSConnection(host, port, key_file, cert_file)

webware/PSP/PSPParser.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,9 @@ def checkScript(self, handler, reader):
172172
start = reader.mark()
173173
try:
174174
stop = reader.skipUntil('%>')
175-
except EOFError:
176-
raise EOFError("Reached EOF while looking for ending script tag")
175+
except EOFError as e:
176+
raise EOFError(
177+
"Reached EOF while looking for ending script tag") from e
177178
if stop is None:
178179
raise PSPParserException('Script not terminated')
179180
handler.setTemplateInfo(self.tmplStart, self.tmplStop)
@@ -201,9 +202,10 @@ def foo(): return 'foo'
201202
if stop is None:
202203
raise PSPParserException(
203204
'Script not terminated in <psp:file> block')
204-
except EOFError:
205+
except EOFError as e:
205206
raise EOFError(
206-
'Reached EOF while looking for ending script tag </psp:file>')
207+
'Reached EOF while looking for'
208+
' ending script tag </psp:file>') from e
207209
handler.setTemplateInfo(self.tmplStart, self.tmplStop)
208210
handler.handleScriptFile(start, stop, None)
209211
return True
@@ -228,9 +230,10 @@ def foo(self):
228230
if stop is None:
229231
raise PSPParserException(
230232
'Script not terminated in <psp:class> block')
231-
except EOFError:
233+
except EOFError as e:
232234
raise EOFError(
233-
'Reached EOF while looking for ending script tag </psp:class>')
235+
'Reached EOF while looking for'
236+
' ending script tag </psp:class>') from e
234237
handler.setTemplateInfo(self.tmplStart, self.tmplStop)
235238
handler.handleScriptClass(start, stop, None)
236239
return True

webware/PSP/PSPServletFactory.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ def loadClassFromFile(self, transaction, fileName, className):
8787
return getattr(module, className)
8888
except AttributeError:
8989
raise AttributeError(
90-
f'Cannot find expected class named {className} in {fileName}.')
90+
'Cannot find expected class'
91+
f' named {className} in {fileName}.') from None
9192

9293
def loadClass(self, transaction, path):
9394
className = self.computeClassName(path)

webware/PSP/PSPUtils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def checkAttributes(tagType, attrs, validAttrs):
4242
attrs.remove(attr)
4343
except KeyError:
4444
raise PSPParserException(
45-
f'{tagType}: Mandatory attribute {attr} missing')
45+
f'{tagType}: Mandatory attribute {attr} missing') from None
4646
optionalAttrs = validAttrs[1]
4747
for attr in attrs:
4848
if attr not in optionalAttrs:

webware/PSP/ParseEventHandler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,8 @@ def handleDirective(self, directive, start, stop, attrs):
205205
encoding = attrs.get('encoding')
206206
try:
207207
self._reader.pushFile(filename, encoding)
208-
except IOError:
209-
raise IOError(f'PSP include file not found: {filename}')
208+
except IOError as e:
209+
raise IOError(f'PSP include file not found: {filename}') from e
210210
else:
211211
raise ValueError('Invalid directive: {directive}')
212212

webware/PickleRPCServlet.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,10 @@ def respondToPost(self, trans):
8989
try:
9090
rawstring = data.read()
9191
req = self.loads(zlib.decompress(rawstring))
92-
except zlib.error:
92+
except zlib.error as e:
9393
raise RequestError(
9494
'Cannot uncompress'
95-
' compressed dict-rpc request')
95+
' compressed dict-rpc request') from e
9696
else:
9797
raise RequestError(
9898
'Cannot handle compressed dict-rpc request')
@@ -101,8 +101,9 @@ def respondToPost(self, trans):
101101
f'Cannot handle Content-Encoding of {encoding}')
102102
else:
103103
req = self.load(data)
104-
except PickleError:
105-
raise RequestError('Cannot unpickle dict-rpc request.')
104+
except PickleError as e:
105+
raise RequestError(
106+
'Cannot unpickle dict-rpc request.') from e
106107
if not isinstance(req, dict):
107108
raise RequestError(
108109
'Expecting a dictionary for dict-rpc requests, '
@@ -116,7 +117,8 @@ def respondToPost(self, trans):
116117
try:
117118
methodName = req['methodName']
118119
except KeyError:
119-
raise RequestError('Missing method in request')
120+
raise RequestError(
121+
'Missing method name in request') from None
120122
args = req.get('args', ())
121123
if methodName == '__methods__.__getitem__':
122124
# support PythonWin autoname completion

webware/Scripts/WaitressServer.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
def serve(args):
99
try:
1010
from waitress import serve
11-
except ImportError:
12-
raise RuntimeError('Waitress server is not installed')
11+
except ImportError as e:
12+
raise RuntimeError('Waitress server is not installed') from e
1313

1414
if args.browser:
1515
scheme = args.url_scheme
@@ -34,8 +34,9 @@ def openBrowser():
3434
if args.reload:
3535
try:
3636
import hupper
37-
except ImportError:
38-
raise RuntimeError('The hupper process monitor is not installed')
37+
except ImportError as e:
38+
raise RuntimeError(
39+
'The hupper process monitor is not installed') from e
3940
if not hupper.is_active():
4041
print('Running Webware with reloading option...')
4142
args.browser = args.reload = False
@@ -64,8 +65,8 @@ def openBrowser():
6465
application = scriptVars['application']
6566
except Exception as e:
6667
raise RuntimeError(
67-
f'Cannot find Webware application:\n{e}\n'
68-
'Is the current directory the application working directory?')
68+
'Cannot find Webware application.\nIs the current directory'
69+
' the application working directory?') from e
6970

7071
print("Waitress serving Webware application...")
7172
args = vars(args)

webware/Servlet.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import os
44

55
from MiscUtils import AbstractError
6-
from MiscUtils.Funcs import asclocaltime, excstr
6+
from MiscUtils.Funcs import asclocaltime
77

88

99
class Servlet:
@@ -80,8 +80,7 @@ def runTransaction(transaction):
8080
# the first exception gets hidden by the second which is often
8181
# just a result of the first. Then you're stuck scratching your
8282
# head wondering what the first might have been.
83-
raise Exception('Two exceptions. first={}; second={}'.format(
84-
excstr(first), excstr(second)))
83+
raise second from first
8584
else:
8685
# no problems with sleep() so raise the one and only exception
8786
raise

webware/SessionFileStore.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,21 +47,21 @@ def __getitem__(self, key):
4747
with self._lock:
4848
try:
4949
sessionFile = open(filename, 'rb')
50-
except IOError:
51-
raise KeyError(key) # session file not found
50+
except IOError as e:
51+
raise KeyError(key) from e # session file not found
5252
try:
5353
try:
5454
value = self.decoder()(sessionFile)
5555
finally:
5656
sessionFile.close()
57-
except Exception:
57+
except Exception as e:
5858
print("Error loading session from disk:", key)
5959
self.application().handleException()
6060
try: # remove the session file because it is corrupt
6161
os.remove(filename)
6262
except Exception:
6363
pass
64-
raise KeyError(key)
64+
raise KeyError(key) from e
6565
return value
6666

6767
def __setitem__(self, key, value):

webware/SessionMemcachedStore.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55

66
try:
77
import memcache # pylint: disable=import-error
8-
except Exception:
8+
except Exception as e:
99
raise ImportError(
10-
"For using Memcached sessions, python-memcached must be installed.")
10+
"For using Memcached sessions,"
11+
" python-memcached must be installed.") from e
1112

1213
from MiscUtils import NoDefault
1314

webware/SessionRedisStore.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
try:
66
import redis # pylint: disable=import-error
7-
except Exception:
8-
raise ImportError("For using Redis sessions, redis-py must be installed.")
7+
except Exception as e:
8+
raise ImportError(
9+
"For using Redis sessions,"
10+
" redis-py must be installed.") from e
911

1012
from MiscUtils import NoDefault
1113

webware/SessionStore.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,9 @@ def cleanStaleSessions(self, _task=None):
198198
timeout == 0 or
199199
curTime >= session.lastAccessTime() + timeout):
200200
keys.append(key)
201-
except AttributeError:
202-
raise ValueError('Not a Session object: %r' % session)
201+
except AttributeError as e:
202+
raise ValueError(
203+
f'Not a Session object: {session!r}') from e
203204
for key in keys:
204205
try:
205206
del self[key]

webware/UnknownFileTypeServlet.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,8 +189,8 @@ def serveContent(self, trans):
189189
filename = self.filename(trans)
190190
try:
191191
f = open(filename, 'rb')
192-
except IOError:
193-
raise HTTPExceptions.HTTPNotFound
192+
except IOError as e:
193+
raise HTTPExceptions.HTTPNotFound from e
194194

195195
stat = os.fstat(f.fileno())
196196
fileSize, mtime = stat[6], stat[8]

webware/WSGIStreamOut.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def startResponse(self, status, headers):
6262
' Try the setting WSGIWrite=False.')
6363
except Exception as e:
6464
print("Response Start Error:", e)
65-
raise ConnectionAbortedError
65+
raise ConnectionAbortedError from e
6666

6767
def autoCommit(self):
6868
"""Get the auto commit mode."""
@@ -109,7 +109,7 @@ def flush(self):
109109
except Exception as e:
110110
print("StreamOut Error:", e)
111111
self._closed = True
112-
raise ConnectionAbortedError
112+
raise ConnectionAbortedError from e
113113
sent += bufferSize
114114
self.pop(sent)
115115

0 commit comments

Comments
 (0)