This commit is contained in:
adii1823 2021-10-28 17:39:13 +05:30
parent b6eb3ef8a7
commit 32c12d89f4
11 changed files with 301 additions and 0 deletions

View 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
View 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
"""

View 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
"""

View 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

View 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)

View 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)

View 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

View 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

View 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
"""

View 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
"""

View 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'
"""