-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypewrap.py
More file actions
87 lines (68 loc) · 2.43 KB
/
typewrap.py
File metadata and controls
87 lines (68 loc) · 2.43 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
# typewrap.py
# created by Austin Poor
import functools
import inspect
from typing import Callable
__version__ = "0.3.0"
def checkInputs(f: Callable) -> Callable:
"""Function input type-checking decorator.
Wraps a function with argument type annotations.
When function is called, checks input arguments
against annotated types.
:param f: Function with argument type hints to check
:raises TypeCheckError: If `not isinstance(argValue,argType)`
Examples::
>>> @checkInputs
>>> def add(a: int, b: int
... return a + b
>>> add(1, 2) # Works
>>> add(1, 2.0) # Raises TypeCheckError
"""
# Get the function signature
sig = inspect.signature(f)
@functools.wraps(f)
def inner(*args,**kwargs):
# Check the inputs
bound = sig.bind(*args,**kwargs)
for arg, val in bound.arguments.items():
argtype = sig.parameters.get(arg).annotation
if argtype is inspect._empty: continue
if not isinstance(val,argtype):
raise TypeCheckError(f"Input type mismatch: `type({val!r}) != {argtype!r}`")
# Return the result
return f(*args,**kwargs)
return inner
def checkOutputs(f: Callable) -> Callable:
"""Function output type-checking decorator.
Wraps a function with argument type annotations.
When function is called, checks output value
type against annotated type.
:param f: Function with return type hint to check
:raises TypeCheckError: If `not isinstance(returnValue,returnType)`
Examples::
>>> @checkOutputs
>>> def add(a, b) -> int:
... return a + b
>>> add(1, 2) # Works
>>> @checkOutputs
>>> def add(a, b) -> str:
... return a + b
>>> add(1, 2) # Raises TypeCheckError
"""
# Get the function signature
sig = inspect.signature(f)
@functools.wraps(f)
def inner(*args,**kwargs):
# Compute the result
result = f(*args,**kwargs)
# Check the output
return_type = sig.return_annotation
if return_type is not inspect._empty:
if not isinstance(result,return_type):
raise TypeCheckError(f"Output type mismatch: `type({result!r}) != {return_type!r}`")
return result
return inner
class TypeCheckError(TypeError):
"""Subclass of `TypeError` for type checking
input or output exceptions."""
pass