-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.py
More file actions
92 lines (78 loc) · 2.06 KB
/
Copy pathbasic.py
File metadata and controls
92 lines (78 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""Basic examples — no API key needed, pattern matching only."""
import butwhy
# ── Example 1: NameError ──
print("=" * 50)
print("Example 1: NameError")
print("=" * 50)
try:
print(undefined_variable)
except NameError as e:
print(butwhy.explain_error(e))
# ── Example 2: KeyError ──
print("\n" + "=" * 50)
print("Example 2: KeyError")
print("=" * 50)
try:
d = {"name": "Alice", "age": 30}
print(d["email"])
except KeyError as e:
print(butwhy.explain_error(e))
# ── Example 3: ZeroDivisionError ──
print("\n" + "=" * 50)
print("Example 3: ZeroDivisionError")
print("=" * 50)
try:
x = 0
result = 100 / x
except ZeroDivisionError as e:
print(butwhy.explain_error(e))
# ── Example 4: IndexError ──
print("\n" + "=" * 50)
print("Example 4: IndexError")
print("=" * 50)
try:
items = [1, 2, 3]
print(items[5])
except IndexError as e:
print(butwhy.explain_error(e))
# ── Example 5: AttributeError (NoneType) ──
print("\n" + "=" * 50)
print("Example 5: AttributeError on None")
print("=" * 50)
try:
data = None
result = data.split(",")
except AttributeError as e:
print(butwhy.explain_error(e))
# ── Example 6: ImportError ──
print("\n" + "=" * 50)
print("Example 6: ModuleNotFoundError")
print("=" * 50)
try:
import cv2
except ModuleNotFoundError as e:
print(butwhy.explain_error(e))
# ── Example 7: Using the decorator ──
print("\n" + "=" * 50)
print("Example 7: @butwhy.explain decorator")
print("=" * 50)
@butwhy.explain
def divide(a, b):
return a / b
try:
divide(10, 0)
except ZeroDivisionError:
pass # The decorator already printed the explanation
# ── Example 8: Using the context manager ──
print("\n" + "=" * 50)
print("Example 8: with butwhy.trace()")
print("=" * 50)
with butwhy.trace(reraise=False):
nums = [1, 2]
print(nums[10]) # IndexError, but suppressed
print("Execution continues after the context manager.")
# ── Example 9: butwhy.this ──
print("\n" + "=" * 50)
print("Example 9: butwhy.this")
print("=" * 50)
print(butwhy.this)