ch07
This commit is contained in:
parent
b6eb3ef8a7
commit
32c12d89f4
46
ch07/context/decimal.prec.py
Normal file
46
ch07/context/decimal.prec.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
# context/decimal.prec.py
|
||||||
|
from decimal import Context, Decimal, getcontext, setcontext
|
||||||
|
|
||||||
|
one = Decimal("1")
|
||||||
|
three = Decimal("3")
|
||||||
|
|
||||||
|
orig_ctx = getcontext()
|
||||||
|
ctx = Context(prec=5)
|
||||||
|
setcontext(ctx)
|
||||||
|
print(ctx)
|
||||||
|
print(one / three)
|
||||||
|
setcontext(orig_ctx)
|
||||||
|
print(one / three)
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
$ python context/decimal.prec.py
|
||||||
|
Context(prec=5, rounding=ROUND_HALF_EVEN, Emin=-999999,
|
||||||
|
Emax=999999, capitals=1, clamp=0, flags=[],
|
||||||
|
traps=[InvalidOperation, DivisionByZero, Overflow])
|
||||||
|
0.33333
|
||||||
|
0.3333333333333333333333333333
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
orig_ctx = getcontext()
|
||||||
|
ctx = Context(prec=5)
|
||||||
|
setcontext(ctx)
|
||||||
|
try:
|
||||||
|
print(ctx)
|
||||||
|
print(one / three)
|
||||||
|
finally:
|
||||||
|
setcontext(orig_ctx)
|
||||||
|
print(one / three)
|
||||||
|
|
||||||
|
|
||||||
|
from decimal import localcontext
|
||||||
|
|
||||||
|
with localcontext(Context(prec=5)) as ctx:
|
||||||
|
print(ctx)
|
||||||
|
print(one / three)
|
||||||
|
print(one / three)
|
||||||
|
|
||||||
|
|
||||||
|
with localcontext(Context(prec=5)), open("out.txt", "w") as out_f:
|
||||||
|
out_f.write(f"{one} / {three} = {one / three}\n")
|
||||||
38
ch07/context/generator.py
Normal file
38
ch07/context/generator.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# context/generator.py
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def my_context_manager():
|
||||||
|
print("Entering 'with' context")
|
||||||
|
val = object()
|
||||||
|
print(id(val))
|
||||||
|
try:
|
||||||
|
yield val
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{type(e)=} {e=} {e.__traceback__=}")
|
||||||
|
finally:
|
||||||
|
print("Exiting 'with' context")
|
||||||
|
|
||||||
|
|
||||||
|
print("About to enter 'with' context")
|
||||||
|
with my_context_manager() as val:
|
||||||
|
print("Inside 'with' context")
|
||||||
|
print(id(val))
|
||||||
|
raise Exception("Exception inside 'with' context")
|
||||||
|
print("This line will never be reached")
|
||||||
|
|
||||||
|
print("After 'with' context")
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
$ python context/generator.py
|
||||||
|
About to enter 'with' context
|
||||||
|
Entering 'with' context
|
||||||
|
139768531985040
|
||||||
|
Inside 'with' context
|
||||||
|
139768531985040
|
||||||
|
type(e)=<class 'Exception'> e=Exception("Exception inside 'with'
|
||||||
|
context") e.__traceback__=<traceback object at 0x7f1e65a42800>
|
||||||
|
Exiting 'with' context
|
||||||
|
After 'with' context
|
||||||
|
"""
|
||||||
40
ch07/context/manager.class.py
Normal file
40
ch07/context/manager.class.py
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
# context/manager.class.py
|
||||||
|
class MyContextManager:
|
||||||
|
def __init__(self):
|
||||||
|
print("MyContextManager init", id(self))
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
print("Entering 'with' context")
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
print(f"{exc_type=} {exc_val=} {exc_tb=}")
|
||||||
|
print("Exiting 'with' context")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
ctx_mgr = MyContextManager()
|
||||||
|
|
||||||
|
print("About to enter 'with' context")
|
||||||
|
|
||||||
|
with ctx_mgr as mgr:
|
||||||
|
print("Inside 'with' context")
|
||||||
|
print(id(mgr))
|
||||||
|
raise Exception("Exception inside 'with' context")
|
||||||
|
print("This line will never be reached")
|
||||||
|
|
||||||
|
print("After 'with' context")
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
$ python context/manager.class.py
|
||||||
|
MyContextManager init 140340228792272
|
||||||
|
About to enter 'with' context
|
||||||
|
Entering 'with' context
|
||||||
|
Inside 'with' context
|
||||||
|
140340228792272
|
||||||
|
exc_type=<class 'Exception'> exc_val=Exception("Exception inside
|
||||||
|
'with' context") exc_tb=<traceback object at 0x7fa3817c5340>
|
||||||
|
Exiting 'with' context
|
||||||
|
After 'with' context
|
||||||
|
"""
|
||||||
31
ch07/exceptions/first.example.py
Normal file
31
ch07/exceptions/first.example.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# exceptions/first.example.py
|
||||||
|
# This is not a valid Python module - Don't run it.
|
||||||
|
# a few examples of exceptions
|
||||||
|
|
||||||
|
>>> gen = (n for n in range(2))
|
||||||
|
>>> next(gen)
|
||||||
|
0
|
||||||
|
>>> next(gen)
|
||||||
|
1
|
||||||
|
>>> next(gen)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 1, in <module>
|
||||||
|
StopIteration
|
||||||
|
>>> print(undefined_name)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 1, in <module>
|
||||||
|
NameError: name 'undefined_name' is not defined
|
||||||
|
>>> mylist = [1, 2, 3]
|
||||||
|
>>> mylist[5]
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 1, in <module>
|
||||||
|
IndexError: list index out of range
|
||||||
|
>>> mydict = {'a': 'A', 'b': 'B'}
|
||||||
|
>>> mydict['c']
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 1, in <module>
|
||||||
|
KeyError: 'c'
|
||||||
|
>>> 1 / 0
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 1, in <module>
|
||||||
|
ZeroDivisionError: division by zero
|
||||||
25
ch07/exceptions/for.loop.py
Normal file
25
ch07/exceptions/for.loop.py
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# exceptions/for.loop.py
|
||||||
|
n = 100
|
||||||
|
found = False
|
||||||
|
for a in range(n):
|
||||||
|
if found: break
|
||||||
|
for b in range(n):
|
||||||
|
if found: break
|
||||||
|
for c in range(n):
|
||||||
|
if 42 * a + 17 * b + c == 5096:
|
||||||
|
found = True
|
||||||
|
print(a, b, c) # 79 99 95
|
||||||
|
|
||||||
|
|
||||||
|
class ExitLoopException(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
n = 100
|
||||||
|
for a in range(n):
|
||||||
|
for b in range(n):
|
||||||
|
for c in range(n):
|
||||||
|
if 42 * a + 17 * b + c == 5096:
|
||||||
|
raise ExitLoopException(a, b, c)
|
||||||
|
except ExitLoopException as ele:
|
||||||
|
print(ele.args) # (79, 99, 95)
|
||||||
15
ch07/exceptions/multiple.py
Normal file
15
ch07/exceptions/multiple.py
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
# exceptions/multiple.py
|
||||||
|
values = (1, 2) # try (1, 0) and ('one', 2)
|
||||||
|
|
||||||
|
try:
|
||||||
|
q, r = divmod(*values)
|
||||||
|
except (ZeroDivisionError, TypeError) as e:
|
||||||
|
print(type(e), e)
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
q, r = divmod(*values)
|
||||||
|
except ZeroDivisionError:
|
||||||
|
print("You tried to divide by zero!")
|
||||||
|
except TypeError as e:
|
||||||
|
print(e)
|
||||||
6
ch07/exceptions/raising.py
Normal file
6
ch07/exceptions/raising.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
# exceptions/raising.py
|
||||||
|
# This is not a valid Python module - Don't run it.
|
||||||
|
>>> raise NotImplementedError("I'm afraid I can't do that")
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 1, in <module>
|
||||||
|
NotImplementedError: I'm afraid I can't do that
|
||||||
34
ch07/exceptions/replace.py
Normal file
34
ch07/exceptions/replace.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# exceptions/replace.py
|
||||||
|
# This is not a valid Python module - Don't run it.
|
||||||
|
>>> class NotFoundError(Exception):
|
||||||
|
... pass
|
||||||
|
...
|
||||||
|
>>> vowels = {'a': 1, 'e': 5, 'i': 9, 'o': 15, 'u': 21}
|
||||||
|
>>> try:
|
||||||
|
... pos = vowels['y']
|
||||||
|
... except KeyError as e:
|
||||||
|
... raise NotFoundError(*e.args)
|
||||||
|
...
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 2, in <module>
|
||||||
|
KeyError: 'y'
|
||||||
|
|
||||||
|
During handling of the above exception, another exception occurred:
|
||||||
|
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 4, in <module>
|
||||||
|
__main__.NotFoundError: y
|
||||||
|
>>> try:
|
||||||
|
... pos = vowels['y']
|
||||||
|
... except KeyError as e:
|
||||||
|
... raise NotFoundError(*e.args) from e
|
||||||
|
...
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 2, in <module>
|
||||||
|
KeyError: 'y'
|
||||||
|
|
||||||
|
The above exception was the direct cause of the following exception:
|
||||||
|
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<stdin>", line 4, in <module>
|
||||||
|
__main__.NotFoundError: y
|
||||||
25
ch07/exceptions/trace.back.py
Normal file
25
ch07/exceptions/trace.back.py
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# exceptions/trace.back.py
|
||||||
|
def squareroot(number):
|
||||||
|
if number < 0:
|
||||||
|
raise ValueError("No negative numbers please")
|
||||||
|
return number ** .5
|
||||||
|
|
||||||
|
def quadratic(a, b, c):
|
||||||
|
d = b ** 2 - 4 * a * c
|
||||||
|
return ((-b - squareroot(d)) / (2 * a),
|
||||||
|
(-b + squareroot(d)) / (2 * a))
|
||||||
|
|
||||||
|
quadratic(1, 0, 1) # x**2 + 1 == 0
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
$ python exceptions/trace.back.py
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "exceptions/trace.back.py", line 12, in <module>
|
||||||
|
quadratic(1, 0, 1) # x**2 + 1 == 0
|
||||||
|
File "exceptions/trace.back.py", line 9, in quadratic
|
||||||
|
return ((-b - squareroot(d)) / (2 * a),
|
||||||
|
File "exceptions/trace.back.py", line 4, in squareroot
|
||||||
|
raise ValueError("No negative numbers please")
|
||||||
|
ValueError: No negative numbers please
|
||||||
|
"""
|
||||||
30
ch07/exceptions/try.syntax.py
Normal file
30
ch07/exceptions/try.syntax.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
# exceptions/try.syntax.py
|
||||||
|
|
||||||
|
def try_syntax(numerator, denominator):
|
||||||
|
try:
|
||||||
|
print(f'In the try block: {numerator}/{denominator}')
|
||||||
|
result = numerator / denominator
|
||||||
|
except ZeroDivisionError as zde:
|
||||||
|
print(zde)
|
||||||
|
else:
|
||||||
|
print('The result is:', result)
|
||||||
|
return result
|
||||||
|
finally:
|
||||||
|
print('Exiting')
|
||||||
|
|
||||||
|
print(try_syntax(12, 4))
|
||||||
|
print(try_syntax(11, 0))
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
$ python try.syntax.py
|
||||||
|
In the try block: 12/4 # try
|
||||||
|
The result is: 3.0 # else
|
||||||
|
Exiting # finally
|
||||||
|
3.0 # return within else
|
||||||
|
|
||||||
|
In the try block: 11/0 # try
|
||||||
|
division by zero # except
|
||||||
|
Exiting # finally
|
||||||
|
None # implicit return end of function
|
||||||
|
"""
|
||||||
11
ch07/exceptions/unhandled.py
Normal file
11
ch07/exceptions/unhandled.py
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
# exceptions/unhandled.py
|
||||||
|
1 + "one"
|
||||||
|
print("This line will never be reached")
|
||||||
|
|
||||||
|
"""
|
||||||
|
$ python exceptions/unhandled.py
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "exceptions/unhandled.py", line 3, in <module>
|
||||||
|
1 + "one"
|
||||||
|
TypeError: unsupported operand type(s) for +: 'int' and 'str'
|
||||||
|
"""
|
||||||
Loading…
x
Reference in New Issue
Block a user