Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
If you need trackback information when throwing an exception use
raise ExceptionClass(msg), otherwise, usesys.exit(msg)instead.The
assertstatement (which raisesAssertionErrorif the assertion is not met) is a very good way to ensure conditions to be met.:::python assert some_condition
import requests
import shutil
class NetworkError(Exception):
"""Exception due to network."""
def __init__(self, value):
super().__init__(f'Request to "{value}" failed.')
def download(id, output=None):
url = "https://api.crowdflower.com/v1/jobs/{id}.csv?type=full&key=QKozzkJJvuqJfq7hkSbT"
url = url.format(id=id)
resp = requests.get(url, stream=True)
if not resp.ok:
raise NetworkError(url)
if not output:
output = "f{id}.csv.zip".format(id=id)
with open(output, "wb") as f:
shutil.copyfileobj(resp.raw, f)err = NetworkError("abc")str(err)'Request to "abc" failed.'raise err---------------------------------------------------------------------------
NetworkError Traceback (most recent call last)
<ipython-input-4-9f7bdcf42c44> in <module>
----> 1 raise err
NetworkError: Request to "abc" failed.