-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignature_tools.py
234 lines (201 loc) · 9.01 KB
/
signature_tools.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
# Authors: Sylvain Marie <[email protected]>
#
# Copyright (c) Schneider Electric Industries, 2019. All right reserved.
from functools import partial
from types import BuiltinFunctionType
# needed below. from inspect and funcsigs
_WrapperDescriptor = type(type.__call__)
_MethodWrapper = type(all.__call__)
class IsBuiltInError(TypeError):
"""note "built-in" means "C built-in"""
pass
try:
from inspect import signature, FullArgSpec
try:
from inspect import _signature_is_builtin
except ImportError:
from inspect import isbuiltin, ismethoddescriptor
# from inspect
_ClassMethodWrapper = type(int.__dict__['from_bytes'])
_NonUserDefinedCallables = (_WrapperDescriptor,
_MethodWrapper,
_ClassMethodWrapper,
BuiltinFunctionType)
def _signature_is_builtin(obj):
""" From inspect"""
return (isbuiltin(obj) or
ismethoddescriptor(obj) or
isinstance(obj, _NonUserDefinedCallables) or
# Can't test 'isinstance(type)' here, as it would
# also be True for regular python classes
obj in (type, object))
def _is_builtin_value_error(e):
try:
return (e.__class__ is ValueError) and ('builtin' in e.args[0])
except:
return False
def getfullargspec(f, skip_bound_arg=False, follow_wrapped=True):
"""
This method adds `skip_bound_arg` argument to `getfullargspec` so that it is capable of skipping the 'self'
parameter of bound methods, like `signature` does.
This is the version for python 3. It is mostly the same code than in `inspect.getfullargspec`, except that
- `skip_bound_arg` is not forced to `False`
- Errors are improved if possible: if the function is a built-in the error raised is an explicit
`IsBuiltInError`.
:param f:
:param skip_bound_arg:
:param follow_wrapped:
:return:
"""
if skip_bound_arg:
try:
sig = signature(f, follow_wrapped=follow_wrapped)
except ValueError as e:
if _signature_is_builtin(f):
raise IsBuiltInError(f)
elif isinstance(f, partial) and _signature_is_builtin(f.func):
raise IsBuiltInError(f)
elif _is_builtin_value_error(e):
raise IsBuiltInError(f)
else:
raise
args = []
varargs = None
varkw = None
kwonlyargs = []
annotations = {}
defaults = ()
kwdefaults = {}
if sig.return_annotation is not sig.empty:
annotations['return'] = sig.return_annotation
for p in sig.parameters.values():
kind = p.kind
name = p.name
if kind is p.POSITIONAL_ONLY:
args.append(name)
elif kind is p.POSITIONAL_OR_KEYWORD:
args.append(name)
if p.default is not p.empty:
defaults += (p.default,)
elif kind is p.VAR_POSITIONAL:
varargs = name
elif kind is p.KEYWORD_ONLY:
kwonlyargs.append(name)
if p.default is not p.empty:
kwdefaults[name] = p.default
elif kind is p.VAR_KEYWORD:
varkw = name
if p.annotation is not p.empty:
annotations[name] = p.annotation
if not kwdefaults:
# compatibility with 'func.__kwdefaults__'
kwdefaults = None
if not defaults:
# compatibility with 'func.__defaults__'
defaults = None
return FullArgSpec(args, varargs, varkw, defaults,
kwonlyargs, kwdefaults, annotations)
else:
# use getfullargspec
raise NotImplementedError()
except ImportError:
# python 2
from inspect import getargspec
from funcsigs import signature
from collections import namedtuple
FullArgSpec = namedtuple('FullArgSpec',
'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
# from https://github.com/aliles/funcsigs/blob/master/funcsigs/__init__.py#L85
_NonUserDefinedCallables = (_WrapperDescriptor,
_MethodWrapper,
BuiltinFunctionType)
def getfullargspec(f, skip_bound_arg=False, follow_wrapped=True):
"""
This method adds `skip_bound_arg` argument to `getfullargspec` so that it is capable of skipping the 'self'
parameter of bound methods, like `signature` does.
This version is for python 2. It is based on `getargspec`.
It is also enhanced to support `partial` objects because before Python 3.4, getargspec() did't work for
functools.partial, so it needs to be handled separately.
Finally when some signatures cant be found, if the function is a built-in the error raised is an explicit
`IsBuiltInError`.
:param f:
:param skip_bound_arg:
:param follow_wrapped:
:return:
"""
if follow_wrapped:
try:
# Was this function wrapped by a decorator?
wrapped = f.__wrapped__
except AttributeError:
pass
else:
return getfullargspec(wrapped, skip_bound_arg=skip_bound_arg, follow_wrapped=follow_wrapped)
try:
if isinstance(f, partial):
# (1) partial
# from https://github.com/dsacre/pyliblo/commit/e897f9987dc97fc678d61ac0e16fe79c6a7dffc0#diff-2be46de1531c648b0e936ccfa59f1692R262
# before Python 3.4, getargspec() did't work for functools.partial, so it needs to be handled separately
p = f
f = f.func
args, varpos, varkw, defaults = getargspec(f)
nb_args_before = len(args)
nb_pos_removed = len(p.args)
args = args[nb_pos_removed:]
if defaults is None:
if p.keywords is not None and len(p.keywords) > 0:
nb_args_after = nb_args_before - nb_pos_removed
args = list(args)
end = nb_args_after
i = 0
while i < end:
if args[i] in p.keywords:
del args[i]
end -= 1
else:
i += 1
else:
nb_without_default_before = nb_args_before - len(defaults)
_diff = nb_pos_removed - nb_without_default_before
nb_pos_defaults_removed = max(0, _diff)
defaults = defaults[nb_pos_defaults_removed:]
if p.keywords is not None and len(p.keywords) > 0:
nb_args_after = nb_args_before - nb_pos_removed
nb_without_defaults_after = max(0, -_diff)
args = list(args)
defaults = list(defaults)
end = nb_args_after
i = 0
while i < end:
if args[i] in p.keywords:
del args[i]
del defaults[i - nb_without_defaults_after]
end -= 1
else:
i += 1
return FullArgSpec(args, varpos, varkw, defaults, None, None, None)
else:
# (2) nominal case
args, varpos, varkw, defaults = getargspec(f)
try:
# if bound instance or class method
if skip_bound_arg and f.__self__ is not None:
args = args[1:]
except AttributeError:
pass
return FullArgSpec(args, varpos, varkw, defaults, None, None, None)
except TypeError as e:
# built-ins...
if isinstance(f, _NonUserDefinedCallables):
# see https://docs.python.org/2/library/types.html#types.BuiltinFunctionType
# note "built-in" means "C built-in"
raise IsBuiltInError(f)
else:
# try:
# declaring_class = f.__objclass__
# # this does not make us make any progress... skip
# except AttributeError:
if e.args[0].endswith("> is not a Python function"):
raise IsBuiltInError(f)
else:
raise ValueError("unknown case")