-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypecheck.py
More file actions
163 lines (144 loc) · 4.72 KB
/
typecheck.py
File metadata and controls
163 lines (144 loc) · 4.72 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#
# Module containing the main typecheck decorator.
# Author: khz
# Date: 03 / 2013
# Hosted on Github: https://github.com/pythononwheels/icanhastype
#
import inspect
import functools
import re
import sys
from itertools import chain
import types
import string
ALL_PARAM_TYPES_PATTERN = r":type[\s]+(\w+):[\s]+([\w\.]+)"
ALL_RETURN_TYPES_PATTERN = r":rtype:[\s]+([\w\.]+)"
def print_list(name, alist):
""" just printing a parameter list in a readable way
:type name: types.StringType
:type alist: types.ListType
"""
print " ** %s" % (name)
print "-"*50
for elem in alist:
print "\t" + elem[0] + "\t" + elem[1]
def print_func_spec(func):
""" print a function specification including
function arguments and type specs.
:type func: types.FunctionType
"""
spec = inspect.getargspec(func)
doc = inspect.getdoc(func)
print
print " ** Printing specification for function: %s" % (str(func))
print "-"*70
print " getargspec: %s" % (str(spec))
print " Parameter Type spec in docstring: "
print string.replace("\t" + doc,"\n", "\n\t")
types = re.compile(ALL_PARAM_TYPES_PATTERN, re.IGNORECASE)
rtypes = re.compile(ALL_RETURN_TYPES_PATTERN, re.IGNORECASE)
res = types.findall(doc)
print_list("Listing parameter types", res)
res = rtypes.findall(doc)
print " ** return type"
print "-"*50
print "\t" + res[0]
def get_class_type(kls):
"""
get and return the type of a class
:type kls: types.StringType
"""
#print "get_class_type for %s" % (kls), type(kls)
if type(kls) == str:
if kls.count(".") > 0:
#kls_instance = reduce(getattr, str.split("."), sys.modules[__name__])
#print "partitioned: ", kls.rpartition(".")
module = kls.rpartition(".")[0]
mod = __import__(module, globals(), locals(), [], -1)
klass = kls.rpartition(".")[2]
#print module, mod, klass
kls_instance = getattr(mod, klass)
else:
#print dir(sys.modules[__name__])
#print sys.modules[__name__]
kls_instance = getattr(sys.modules[__name__], kls)
#print kls_instance
#print type(kls_instance)
else:
#print "type was not str"
kls_instance = kls
return kls_instance
def typesafe(parameter_spec = None):
def typecheck(func):
""" Decorator to verify function argument types
inspired and partly take from the book:
Pro Python. (Expert's Voice in Open Source)
From Marty Alchin
(see)[http://www.amazon.de/Python-Experts-Voice-Open-Source/dp/1430227575]
:type func: types.FunctionType
:rtype: types.FunctionType
"""
#print "-"*70
#print "Checking Type Safety for function: %s" % (str(func))
#print "-"*70
error = "Wrong type for %s: expected: %s, got %s."
fine = "Right type for %s: expected: %s, and successfully got %s."
if sys.version_info[0] == 3:
##########################
# Handle python > 3.x
##########################
#spec = inspect.getfullargspec(func)
#doc = inspect.getdoc(func)
#annotations = spec.annotations
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Not implemented for python 3.x, yet
return func
# handle keyword args
#for name, arg in chain(zip(spec.args,args), kwargs.items()):
# if name in annotations and not isinstance(arg, annotations[name]):
# raise TypeError( error % ( name,
# annotations[name].__name__,
# type(arg).__name__ ) )
#return func
return wrapper
else:
############################
# Handle python < 3.x
############################
spec = inspect.getargspec(func)
doc = inspect.getdoc(func)
type_dict = {}
if parameter_spec:
# the parameter specification is passed as a paramter to the decorator
all_types = parameter_spec.items()
else:
# the parameter spec is defined as docstring.
# Regexps for the func specs
all_param_types = re.compile(ALL_PARAM_TYPES_PATTERN, re.IGNORECASE)
all_rtypes = re.compile(ALL_RETURN_TYPES_PATTERN, re.IGNORECASE)
all_types = all_param_types.findall(doc)
#print "all_types:", all_types
for name, atype in all_types:
#print "trying to get Type %s for: %s" % (name, atype)
obj = get_class_type(atype)
#print "got: %s" % (obj)
type_dict[name] = obj
#print type_dict
@functools.wraps(func)
def wrapper(*args, **kwargs):
# handle keyword args
for name, arg in chain(zip(spec.args,args), kwargs.items()):
if name in type_dict and not isinstance(arg, type_dict[name]):
raise TypeError( error % ( name,
type_dict[name],
type(arg).__name__ ) )
else:
#print fine % ( name, type_dict[name], type(arg).__name__ )
pass
return func
return wrapper
return typecheck
if __name__ == "__main__":
print "not intended to be used on the cli ;)"
print "usage: see: https://github.com/pythononwheels/icanhastypecheck "