-
Notifications
You must be signed in to change notification settings - Fork 284
/
argcheck.py
executable file
·332 lines (266 loc) · 9.58 KB
/
argcheck.py
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import namedtuple
import inspect
from itertools import chain
from six.moves import map, zip_longest
from zipline.errors import ZiplineError
Argspec = namedtuple('Argspec', ['args', 'starargs', 'kwargs'])
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class Ignore(object):
def __str__(self):
return 'Argument.ignore'
__repr__ = __str__
@singleton
class NoDefault(object):
def __str__(self):
return 'Argument.no_default'
__repr__ = __str__
@singleton
class AnyDefault(object):
def __str__(self):
return 'Argument.any_default'
__repr__ = __str__
class Argument(namedtuple('Argument', ['name', 'default'])):
"""
An argument to a function.
Argument.no_default is a value representing no default to the argument.
Argument.ignore is a value that says you should ignore the default value.
"""
no_default = NoDefault()
any_default = AnyDefault()
ignore = Ignore()
def __new__(cls, name=ignore, default=ignore):
return super(Argument, cls).__new__(cls, name, default)
def __str__(self):
if self.has_no_default(self) or self.ignore_default(self):
return str(self.name)
else:
return '='.join([str(self.name), str(self.default)])
def __repr__(self):
return 'Argument(%s, %s)' % (repr(self.name), repr(self.default))
def _defaults_match(self, arg):
return any(map(Argument.ignore_default, [self, arg])) \
or (self.default is Argument.any_default and
arg.default is not Argument.no_default) \
or (arg.default is Argument.any_default and
self.default is not Argument.no_default) \
or self.default == arg.default
def _names_match(self, arg):
return self.name == arg.name \
or self.name is Argument.ignore \
or arg.name is Argument.ignore
def matches(self, arg):
return self._names_match(arg) and self._defaults_match(arg)
__eq__ = matches
@staticmethod
def parse_argspec(callable_):
"""
Takes a callable and returns a tuple with the list of Argument objects,
the name of *args, and the name of **kwargs.
If *args or **kwargs is not present, it will be None.
This returns a namedtuple called Argspec that has three fields named:
args, starargs, and kwargs.
"""
args, varargs, keywords, defaults = inspect.getargspec(callable_)
defaults = list(defaults or [])
if getattr(callable_, '__self__', None) is not None:
# This is a bound method, drop the self param.
args = args[1:]
first_default = len(args) - len(defaults)
return Argspec(
[Argument(arg, Argument.no_default
if n < first_default else defaults[n - first_default])
for n, arg in enumerate(args)],
varargs,
keywords,
)
@staticmethod
def has_no_default(arg):
return arg.default is Argument.no_default
@staticmethod
def ignore_default(arg):
return arg.default is Argument.ignore
def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args):
"""
Checks for the presence of an extra to the argument list. Raises expections
if this is unexpected or if it is missing and expected.
"""
if present:
if not expected:
raise exc_unexpected(*exc_args)
elif expected and expected is not Argument.ignore:
raise exc_missing(*exc_args)
def verify_callable_argspec(callable_,
expected_args=Argument.ignore,
expect_starargs=Argument.ignore,
expect_kwargs=Argument.ignore):
"""
Checks the callable_ to make sure that it satisfies the given
expectations.
expected_args should be an iterable of Arguments in the order you expect to
receive them.
expect_starargs means that the function should or should not take a *args
param. expect_kwargs says the callable should or should not take **kwargs
param.
If expected_args, expect_starargs, or expect_kwargs is Argument.ignore,
then the checks related to that argument will not occur.
Example usage:
callable_check(
f,
[Argument('a'), Argument('b', 1)],
expect_starargs=True,
expect_kwargs=Argument.ignore
)
"""
if not callable(callable_):
raise NotCallable(callable_)
expected_arg_list = list(
expected_args if expected_args is not Argument.ignore else []
)
args, starargs, kwargs = Argument.parse_argspec(callable_)
exc_args = callable_, args, starargs, kwargs
# Check the *args.
_expect_extra(
expect_starargs,
starargs,
UnexpectedStarargs,
NoStarargs,
exc_args,
)
# Check the **kwargs.
_expect_extra(
expect_kwargs,
kwargs,
UnexpectedKwargs,
NoKwargs,
exc_args,
)
if expected_args is Argument.ignore:
# Ignore the argument list checks.
return
if len(args) < len(expected_arg_list):
# One or more argument that we expected was not present.
raise NotEnoughArguments(
callable_,
args,
starargs,
kwargs,
[arg for arg in expected_arg_list if arg not in args],
)
elif len(args) > len(expected_arg_list):
raise TooManyArguments(
callable_, args, starargs, kwargs
)
# Empty argument that will not match with any actual arguments.
missing_arg = Argument(object(), object())
for expected, provided in zip_longest(expected_arg_list,
args,
fillvalue=missing_arg):
if not expected.matches(provided):
raise MismatchedArguments(
callable_, args, starargs, kwargs
)
class BadCallable(TypeError, AssertionError, ZiplineError):
"""
The given callable is not structured in the expected way.
"""
_lambda_name = (lambda: None).__name__
def __init__(self, callable_, args, starargs, kwargs):
self.callable_ = callable_
self.args = args
self.starargs = starargs
self.kwargsname = kwargs
self.kwargs = {}
def format_callable(self):
if self.callable_.__name__ == self._lambda_name:
fmt = '%s %s'
name = 'lambda'
else:
fmt = '%s(%s)'
name = self.callable_.__name__
return fmt % (
name,
', '.join(
chain(
(str(arg) for arg in self.args),
('*' + sa for sa in (self.starargs,) if sa is not None),
('**' + ka for ka in (self.kwargsname,) if ka is not None),
)
)
)
@property
def msg(self):
return str(self)
class NoStarargs(BadCallable):
def __str__(self):
return '%s does not allow for *args' % self.format_callable()
class UnexpectedStarargs(BadCallable):
def __str__(self):
return '%s should not allow for *args' % self.format_callable()
class NoKwargs(BadCallable):
def __str__(self):
return '%s does not allow for **kwargs' % self.format_callable()
class UnexpectedKwargs(BadCallable):
def __str__(self):
return '%s should not allow for **kwargs' % self.format_callable()
class NotCallable(BadCallable):
"""
The provided 'callable' is not actually a callable.
"""
def __init__(self, callable_):
self.callable_ = callable_
def __str__(self):
return '%s is not callable' % self.format_callable()
def format_callable(self):
try:
return self.callable_.__name__
except AttributeError:
return str(self.callable_)
class NotEnoughArguments(BadCallable):
"""
The callback does not accept enough arguments.
"""
def __init__(self, callable_, args, starargs, kwargs, missing_args):
super(NotEnoughArguments, self).__init__(
callable_, args, starargs, kwargs
)
self.missing_args = missing_args
def __str__(self):
missing_args = list(map(str, self.missing_args))
return '%s is missing argument%s: %s' % (
self.format_callable(),
's' if len(missing_args) > 1 else '',
', '.join(missing_args),
)
class TooManyArguments(BadCallable):
"""
The callback cannot be called by passing the expected number of arguments.
"""
def __str__(self):
return '%s accepts too many arguments' % self.format_callable()
class MismatchedArguments(BadCallable):
"""
The argument lists are of the same lengths, but not in the correct order.
"""
def __str__(self):
return '%s accepts mismatched parameters' % self.format_callable()