Skip to content

Commit 3cebc2f

Browse files
committed
ch11
1 parent 0c8dadd commit 3cebc2f

File tree

11 files changed

+296
-0
lines changed

11 files changed

+296
-0
lines changed

ch11/assertions.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# assertions.py
2+
mylist = [1, 2, 3] # pretend this comes from an external source
3+
4+
assert 4 == len(mylist) # this will break
5+
6+
for position in range(4):
7+
print(mylist[position])
8+
9+
10+
"""
11+
$ python assertions.py
12+
Traceback (most recent call last):
13+
File "assertions.py", line 4, in <module>
14+
assert 4 == len(mylist) # this will break
15+
AssertionError
16+
"""
17+
18+
# asserts with message
19+
assert 4 == len(mylist), f"Mylist has {len(mylist)} elements"
20+
21+
22+
"""
23+
$ python assertions.py
24+
Traceback (most recent call last):
25+
File "assertions.py", line 19, in <module>
26+
assert 4 == len(mylist), f"Mylist has {len(mylist)} elements"
27+
AssertionError: Mylist has 3 elements
28+
"""

ch11/custom.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# custom.py
2+
def debug(*msg, print_separator=True):
3+
print(*msg)
4+
if print_separator:
5+
print('-' * 40)
6+
7+
8+
debug('Data is ...')
9+
debug('Different', 'Strings', 'Are not a problem')
10+
debug('After while loop', print_separator=False)
11+
12+
13+
"""
14+
$ python custom.py
15+
Data is ...
16+
----------------------------------------
17+
Different Strings Are not a problem
18+
----------------------------------------
19+
After while loop
20+
"""

ch11/custom_timestamp.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# custom_timestamp.py
2+
from time import sleep
3+
4+
5+
def debug(*msg, timestamp=[None]):
6+
print(*msg)
7+
from time import time # local import
8+
if timestamp[0] is None:
9+
timestamp[0] = time() #1
10+
else:
11+
now = time()
12+
print(
13+
' Time elapsed: {:.3f}s'.format(now - timestamp[0])
14+
)
15+
timestamp[0] = now #2
16+
17+
18+
debug('Entering nasty piece of code...')
19+
sleep(.3)
20+
debug('First step done.')
21+
sleep(.5)
22+
debug('Second step done.')
23+
24+
25+
"""
26+
$ python custom_timestamp.py
27+
Entering nasty piece of code...
28+
First step done.
29+
Time elapsed: 0.300s
30+
Second step done.
31+
Time elapsed: 0.500s
32+
"""

ch11/log.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# log.py
2+
import logging
3+
4+
logging.basicConfig(
5+
filename='ch11.log',
6+
level=logging.DEBUG,
7+
format='[%(asctime)s] %(levelname)s: %(message)s',
8+
datefmt='%m/%d/%Y %I:%M:%S %p')
9+
10+
mylist = [1, 2, 3]
11+
logging.info('Starting to process `mylist`...')
12+
13+
for position in range(4):
14+
try:
15+
logging.debug(
16+
'Value at position %s is %s', position, mylist[position]
17+
)
18+
except IndexError:
19+
logging.exception('Faulty position: %s', position)
20+
21+
logging.info('Done processing `mylist`.')

ch11/pdebugger.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# pdebugger.py
2+
# d comes from a JSON payload we don't control
3+
d = {'first': 'v1', 'second': 'v2', 'fourth': 'v4'}
4+
# keys also comes from a JSON payload we don't control
5+
keys = ('first', 'second', 'third', 'fourth')
6+
7+
def do_something_with_value(value):
8+
print(value)
9+
10+
for key in keys:
11+
do_something_with_value(d[key])
12+
13+
print('Validation done.')
14+
15+
"""
16+
$ python pdebugger.py
17+
v1
18+
v2
19+
Traceback (most recent call last):
20+
File "pdebugger.py", line 11, in <module>
21+
do_something_with_value(d[key])
22+
KeyError: 'third'
23+
"""

ch11/pdebugger_pdb.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# pdebugger_pdb.py
2+
# d comes from a JSON payload we don't control
3+
d = {'first': 'v1', 'second': 'v2', 'fourth': 'v4'}
4+
# keys also comes from a JSON payload we don't control
5+
keys = ('first', 'second', 'third', 'fourth')
6+
7+
def do_something_with_value(value):
8+
print(value)
9+
10+
11+
import pdb
12+
pdb.set_trace()
13+
14+
# or:
15+
# breakpoint()
16+
17+
18+
for key in keys:
19+
do_something_with_value(d[key])
20+
21+
print('Validation done.')
22+
23+
24+
"""
25+
$ python pdebugger_pdb.py
26+
[0] > pdebugger_pdb.py(17)<module>()
27+
-> for key in keys:
28+
(Pdb++) l
29+
17
30+
18 -> for key in keys: # breakpoint comes in
31+
19 do_something_with_value(d[key])
32+
20
33+
34+
(Pdb++) keys # inspecting the keys tuple
35+
('first', 'second', 'third', 'fourth')
36+
(Pdb++) d.keys() # inspecting keys of `d`
37+
dict_keys(['first', 'second', 'fourth'])
38+
(Pdb++) d['third'] = 'placeholder' # add missing item
39+
(Pdb++) c # continue
40+
v1
41+
v2
42+
placeholder
43+
v4
44+
Validation done.
45+
"""

ch11/profiling/triples.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
def calc_triples(mx):
3+
triples = []
4+
for a in range(1, mx + 1):
5+
for b in range(a, mx + 1):
6+
hypotenuse = calc_hypotenuse(a, b)
7+
if is_int(hypotenuse):
8+
triples.append((a, b, int(hypotenuse)))
9+
return triples
10+
11+
12+
def calc_hypotenuse(a, b):
13+
return (a**2 + b**2) ** .5
14+
15+
16+
def is_int(n): # n is expected to be a float
17+
return n.is_integer()
18+
19+
20+
triples = calc_triples(1000)
21+
22+
"""
23+
$ python -m cProfile profiling/triples.py
24+
1502538 function calls in 0.489 seconds
25+
26+
Ordered by: standard name
27+
28+
ncalls tottime percall cumtime percall filename:lineno(function)
29+
500500 0.282 0.000 0.282 0.000 triples.py:13(calc_hypotenuse)
30+
500500 0.065 0.000 0.086 0.000 triples.py:17(is_int)
31+
1 0.000 0.000 0.489 0.489 triples.py:3(<module>)
32+
1 0.121 0.121 0.489 0.489 triples.py:3(calc_triples)
33+
1 0.000 0.000 0.489 0.489 {built-in method builtins.exec}
34+
1034 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
35+
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
36+
500500 0.021 0.000 0.021 0.000 {method 'is_integer' of 'float' objects}
37+
"""

ch11/profiling/triples_v2.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
def calc_triples(mx):
3+
triples = []
4+
for a in range(1, mx + 1):
5+
for b in range(a, mx + 1):
6+
hypotenuse = calc_hypotenuse(a, b)
7+
if is_int(hypotenuse):
8+
triples.append((a, b, int(hypotenuse)))
9+
return triples
10+
11+
12+
def calc_hypotenuse(a, b):
13+
return (a*a + b*b) ** .5
14+
15+
16+
def is_int(n): # n is expected to be a float
17+
return n.is_integer()
18+
19+
20+
triples = calc_triples(1000)
21+
22+
"""
23+
$ python -m cProfile profiling/triples_v2.py
24+
1502538 function calls in 0.288 seconds
25+
26+
Ordered by: standard name
27+
28+
ncalls tottime percall cumtime percall filename:lineno(function)
29+
500500 0.084 0.000 0.084 0.000 triples_v2.py:13(calc_hypotenuse)
30+
500500 0.064 0.000 0.084 0.000 triples_v2.py:17(is_int)
31+
1 0.000 0.000 0.288 0.288 triples_v2.py:3(<module>)
32+
1 0.120 0.120 0.288 0.288 triples_v2.py:3(calc_triples)
33+
1 0.000 0.000 0.288 0.288 {built-in method builtins.exec}
34+
1034 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
35+
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
36+
500500 0.020 0.000 0.020 0.000 {method 'is_integer' of 'float' objects}
37+
"""

ch11/profiling/triples_v3.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
def calc_triples(mx):
3+
triples = []
4+
for a in range(1, mx + 1):
5+
for b in range(a, mx + 1):
6+
hypotenuse = calc_hypotenuse(a, b)
7+
if is_int(hypotenuse):
8+
triples.append((a, b, int(hypotenuse)))
9+
return triples
10+
11+
12+
def calc_hypotenuse(a, b):
13+
return (a*a + b*b) ** .5
14+
15+
16+
def is_int(n):
17+
return n == int(n)
18+
19+
20+
triples = calc_triples(1000)
21+
22+
"""
23+
$ python -m cProfile profiling/triples_v3.py
24+
1002038 function calls in 0.269 seconds
25+
26+
Ordered by: standard name
27+
28+
ncalls tottime percall cumtime percall filename:lineno(function)
29+
500500 0.084 0.000 0.084 0.000 triples_v3.py:13(calc_hypotenuse)
30+
500500 0.068 0.000 0.068 0.000 triples_v3.py:17(is_int)
31+
1 0.000 0.000 0.269 0.269 triples_v3.py:3(<module>)
32+
1 0.116 0.116 0.269 0.269 triples_v3.py:3(calc_triples)
33+
1 0.000 0.000 0.269 0.269 {built-in method builtins.exec}
34+
1034 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
35+
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
36+
"""

ch11/requirements.in

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pdbpp

0 commit comments

Comments
 (0)