Skip to content

Commit e9c4083

Browse files
committed
TypeGuard v0
1 parent 4184b2e commit e9c4083

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

‎Week06/typeguard.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class WrongTypeAnnotationError(TypeError):
2+
pass
3+
4+
5+
class TypeGuard:
6+
def __init__(self, label: str = "TypeGuard"):
7+
self.label = label
8+
9+
def __call__(self, func):
10+
def wrapper(*args, **kwargs):
11+
print(f"{self.label}: Type checking")
12+
print(f"Function: {func.__name__}")
13+
print(f"Type annotations: {func.__annotations__}")
14+
for k, v in func.__annotations__.items():
15+
if k in kwargs:
16+
if not isinstance(kwargs[k], v):
17+
raise WrongTypeAnnotationError(
18+
f"Argument '{k}' must be of type {v.__name__}, "
19+
f"but got {type(kwargs[k]).__name__}"
20+
)
21+
result = func(*args, **kwargs)
22+
return result
23+
24+
return wrapper
25+
26+
27+
@TypeGuard(label="Custom Type Guard")
28+
def add(*, x: int, y: int) -> int:
29+
return x + y
30+
31+
32+
def main():
33+
x = 6
34+
y = "Canbula"
35+
try:
36+
result = add(x=x, y=y)
37+
print(f"Result: {result}")
38+
except TypeError as e:
39+
print(f"TypeError: {e}")
40+
except Exception as e:
41+
print(f"Error ({e.__class__.__name__}): {e}")
42+
43+
44+
if __name__ == "__main__":
45+
main()

0 commit comments

Comments
 (0)