Skip to content

Commit a02dea3

Browse files
committed
added item_21
1 parent c7e79fc commit a02dea3

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

item_21.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
#!/usr/bin/env python3
2+
3+
'''Item 21 from Effective Python'''
4+
5+
6+
# Example 1
7+
''' ignore OverflowError exceptions and return zero instead '''
8+
print('Example 1:\n==========')
9+
10+
def safe_division(number, divisor, ignore_overflow, ignore_zero_division):
11+
try:
12+
return number / divisor
13+
except OverflowError:
14+
if ignore_overflow:
15+
return 0
16+
else:
17+
raise
18+
except ZeroDivisionError:
19+
if ignore_zero_division:
20+
return float('inf')
21+
else:
22+
raise
23+
24+
25+
# Example 2
26+
''' This call will ignore the float overflow from division and will return zero
27+
'''
28+
print('\nExample 2:\n==========')
29+
30+
result = safe_division(1, 10**500, True, False)
31+
print(result)
32+
33+
34+
# Example 3
35+
''' This call will ignore the error from dividing by zero and will return
36+
infinity '''
37+
print('\nExample 3:\n==========')
38+
39+
result = safe_division(1, 0, False, True)
40+
print(result)
41+
42+
43+
# Example 4
44+
''' One way to improve the readability of this code is to use keyword
45+
arguments '''
46+
print('\nExample 4:\n==========')
47+
48+
49+
def safe_division_b(number, divisor,
50+
ignore_overflow=False,
51+
ignore_zero_division=False):
52+
try:
53+
return number / divisor
54+
except OverflowError:
55+
if ignore_overflow:
56+
return 0
57+
else:
58+
raise
59+
except ZeroDivisionError:
60+
if ignore_zero_division:
61+
return float('inf')
62+
else:
63+
raise
64+
65+
66+
# Example 5
67+
''' Then callers can use keyword arguments to specify which of the ignore flags
68+
they want to flip for specific operations, overriding the default behavior '''
69+
print('\nExample 5:\n==========')
70+
71+
result = safe_division_b(1, 10**500, ignore_overflow=True)
72+
print(result)
73+
result = safe_division_b(1, 10**500, ignore_zero_division=True)
74+
print(result)
75+
76+
77+
# Example 6
78+
''' In Python 3, you can demand clarity by defining your functions with
79+
keyword-only arguments. These arguments can only be supplied by keyword, never
80+
by position '''
81+
print('\nExample 6:\n==========')
82+
83+
84+
def safe_division_c(number, divisor, *,
85+
ignore_overflow=False,
86+
ignore_zero_division=False):
87+
try:
88+
return number / divisor
89+
except OverflowError:
90+
if ignore_overflow:
91+
return 0
92+
else:
93+
raise
94+
except ZeroDivisionError:
95+
if ignore_zero_division:
96+
return float('inf')
97+
else:
98+
raise
99+
100+
101+
# Example 7
102+
''' Keyword arguments and their default values work as expected '''
103+
print('\nExample 7:\n==========')
104+
105+
result = safe_division_c(1, 0, ignore_zero_division=True)
106+
print(result)

0 commit comments

Comments
 (0)