Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork252
Expand file tree
/
Copy pathinspection.py
More file actions
405 lines (342 loc) · 13.2 KB
/
inspection.py
File metadata and controls
405 lines (342 loc) · 13.2 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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# The MIT License
#
# Copyright (c) 2009-2011 the bpython authors.
# Copyright (c) 2015 Sebastian Ramacher
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
importinspect
importkeyword
importpydoc
importre
fromdataclassesimportdataclass
fromtypingimport (
Any,
Callable,
Optional,
Type,
Dict,
List,
ContextManager,
Literal,
)
fromtypesimportMemberDescriptorType,TracebackType
frompygments.tokenimportToken
frompygments.lexersimportPython3Lexer
from .lazyreimportLazyReCompile
class_Repr:
"""
Helper for `ArgSpec`: Returns the given value in `__repr__()`.
"""
__slots__= ("value",)
def__init__(self,value:str)->None:
self.value=value
def__repr__(self)->str:
returnself.value
__str__=__repr__
@dataclass
classArgSpec:
args:List[str]
varargs:Optional[str]
varkwargs:Optional[str]
defaults:Optional[List[_Repr]]
kwonly:List[str]
kwonly_defaults:Optional[Dict[str,_Repr]]
annotations:Optional[Dict[str,Any]]
@dataclass
classFuncProps:
func:str
argspec:ArgSpec
is_bound_method:bool
classAttrCleaner(ContextManager[None]):
"""A context manager that tries to make an object not exhibit side-effects
on attribute lookup.
Unless explicitly required, prefer `getattr_safe`."""
def__init__(self,obj:Any)->None:
self._obj=obj
def__enter__(self)->None:
"""Try to make an object not exhibit side-effects on attribute
lookup."""
type_=type(self._obj)
# Dark magic:
# If __getattribute__ doesn't exist on the class and __getattr__ does
# then __getattr__ will be called when doing
# getattr(type_, '__getattribute__', None)
# so we need to first remove the __getattr__, then the
# __getattribute__, then look up the attributes and then restore the
# original methods. :-(
# The upshot being that introspecting on an object to display its
# attributes will avoid unwanted side-effects.
__getattr__=getattr(type_,"__getattr__",None)
if__getattr__isnotNone:
try:
setattr(type_,"__getattr__", (lambda*_,**__:None))
except (TypeError,AttributeError):
__getattr__=None
__getattribute__=getattr(type_,"__getattribute__",None)
if__getattribute__isnotNone:
try:
setattr(type_,"__getattribute__",object.__getattribute__)
except (TypeError,AttributeError):
# XXX: This happens for e.g. built-in types
__getattribute__=None
self._attribs= (__getattribute__,__getattr__)
# /Dark magic
def__exit__(
self,
exc_type:Optional[Type[BaseException]],
exc_val:Optional[BaseException],
exc_tb:Optional[TracebackType],
)->Literal[False]:
"""Restore an object's magic methods."""
type_=type(self._obj)
__getattribute__,__getattr__=self._attribs
# Dark magic:
if__getattribute__isnotNone:
setattr(type_,"__getattribute__",__getattribute__)
if__getattr__isnotNone:
setattr(type_,"__getattr__",__getattr__)
# /Dark magic
returnFalse
defparsekeywordpairs(signature:str)->Dict[str,str]:
preamble=True
stack= []
substack:List[str]= []
parendepth=0
annotation=False
fortoken,valueinPython3Lexer().get_tokens(signature):
ifpreamble:
iftokenisToken.Punctuationandvalue=="(":
# First "(" starts the list of arguments
preamble=False
continue
iftokenisToken.Punctuation:
ifvaluein"({[":
parendepth+=1
elifvaluein")}]":
parendepth-=1
elifvalue==":":
ifparendepth==-1:
# End of signature reached
break
elifparendepth==0:
# Start of type annotation
annotation=True
if (value,parendepth)in ((",",0), (")",-1)):
# End of current argument
stack.append(substack)
substack= []
# If type annotation didn't end before, it does now.
annotation=False
continue
eliftokenisToken.Operatorandvalue=="="andparendepth==0:
# End of type annotation
annotation=False
ifvalueandnotannotationand (parendepth>0orvalue.strip()):
substack.append(value)
return {item[0]:"".join(item[2:])foriteminstackiflen(item)>=3}
def_fix_default_values(f:Callable,argspec:ArgSpec)->ArgSpec:
"""Functions taking default arguments that are references to other objects
will cause breakage, so we swap out the object itself with the name it was
referenced with in the source by parsing the source itself!"""
ifargspec.defaultsisNoneandargspec.kwonly_defaultsisNone:
# No keyword args, no need to do anything
returnargspec
try:
src,_=inspect.getsourcelines(f)
except (OSError,IndexError):
# IndexError is raised in inspect.findsource(), can happen in
# some situations. See issue #94.
returnargspec
exceptTypeError:
# No source code is available, so replace the default values with what we have.
ifargspec.defaultsisnotNone:
argspec.defaults= [_Repr(str(value))forvalueinargspec.defaults]
ifargspec.kwonly_defaultsisnotNone:
argspec.kwonly_defaults= {
key:_Repr(str(value))
forkey,valueinargspec.kwonly_defaults.items()
}
returnargspec
kwparsed=parsekeywordpairs("".join(src))
ifargspec.defaultsisnotNone:
values=list(argspec.defaults)
keys=argspec.args[-len(values) :]
fori,keyinenumerate(keys):
values[i]=_Repr(kwparsed[key])
argspec.defaults=values
ifargspec.kwonly_defaultsisnotNone:
forkeyinargspec.kwonly_defaults.keys():
argspec.kwonly_defaults[key]=_Repr(kwparsed[key])
returnargspec
_getpydocspec_re=LazyReCompile(
r"([a-zA-Z_][a-zA-Z0-9_]*?)\((.*?)\)",re.DOTALL
)
def_getpydocspec(f:Callable)->Optional[ArgSpec]:
try:
argspec=pydoc.getdoc(f)
exceptNameError:
returnNone
s=_getpydocspec_re.search(argspec)
ifsisNone:
returnNone
ifnothasattr_safe(f,"__name__")ors.groups()[0]!=f.__name__:
returnNone
args= []
defaults= []
varargs=varkwargs=None
kwonly_args= []
kwonly_defaults= {}
forargins.group(2).split(","):
arg=arg.strip()
ifarg.startswith("**"):
varkwargs=arg[2:]
elifarg.startswith("*"):
varargs=arg[1:]
elifarg=="...":
# At least print denotes "..." as separator between varargs and kwonly args.
varargs=""
else:
arg,_,default=arg.partition("=")
ifvarargsisnotNone:
kwonly_args.append(arg)
ifdefault:
kwonly_defaults[arg]=_Repr(default)
else:
args.append(arg)
ifdefault:
defaults.append(_Repr(default))
returnArgSpec(
args,varargs,varkwargs,defaults,kwonly_args,kwonly_defaults,None
)
defgetfuncprops(func:str,f:Callable)->Optional[FuncProps]:
# Check if it's a real bound method or if it's implicitly calling __init__
# (i.e. FooClass(...) and not FooClass.__init__(...) -- the former would
# not take 'self', the latter would:
try:
func_name=getattr(f,"__name__",None)
except:
# if calling foo.__name__ would result in an error
func_name=None
try:
is_bound_method= (
(inspect.ismethod(f)andf.__self__isnotNone)
or (func_name=="__init__"andnotfunc.endswith(".__init__"))
or (func_name=="__new__"andnotfunc.endswith(".__new__"))
)
except:
# if f is a method from a xmlrpclib.Server instance, func_name ==
# '__init__' throws xmlrpclib.Fault (see #202)
returnNone
try:
argspec=_get_argspec_from_signature(f)
try:
argspec=_fix_default_values(f,argspec)
exceptKeyErrorasex:
# Parsing of the source failed. If f has a __signature__, we trust it.
ifnothasattr(f,"__signature__"):
raiseex
fprops=FuncProps(func,argspec,is_bound_method)
except (TypeError,KeyError,ValueError):
argspec_pydoc=_getpydocspec(f)
ifargspec_pydocisNone:
returnNone
ifinspect.ismethoddescriptor(f):
argspec_pydoc.args.insert(0,"obj")
fprops=FuncProps(func,argspec_pydoc,is_bound_method)
returnfprops
defis_eval_safe_name(string:str)->bool:
returnall(
part.isidentifier()andnotkeyword.iskeyword(part)
forpartinstring.split(".")
)
def_get_argspec_from_signature(f:Callable)->ArgSpec:
"""Get callable signature from inspect.signature in argspec format.
inspect.signature is a Python 3 only function that returns the signature of
a function. Its advantage over inspect.getfullargspec is that it returns
the signature of a decorated function, if the wrapper function itself is
decorated with functools.wraps.
"""
args= []
varargs=None
varkwargs=None
defaults= []
kwonly= []
kwonly_defaults= {}
annotations= {}
# We use signature here instead of getfullargspec as the latter also returns
# self and cls (for class methods).
signature=inspect.signature(f)
forparameterinsignature.parameters.values():
ifparameter.annotationisnotparameter.empty:
annotations[parameter.name]=parameter.annotation
ifparameter.kind==inspect.Parameter.POSITIONAL_OR_KEYWORD:
args.append(parameter.name)
ifparameter.defaultisnotparameter.empty:
defaults.append(parameter.default)
elifparameter.kind==inspect.Parameter.POSITIONAL_ONLY:
args.append(parameter.name)
elifparameter.kind==inspect.Parameter.VAR_POSITIONAL:
varargs=parameter.name
elifparameter.kind==inspect.Parameter.KEYWORD_ONLY:
kwonly.append(parameter.name)
kwonly_defaults[parameter.name]=parameter.default
elifparameter.kind==inspect.Parameter.VAR_KEYWORD:
varkwargs=parameter.name
returnArgSpec(
args,
varargs,
varkwargs,
defaultsifdefaultselseNone,
kwonly,
kwonly_defaultsifkwonly_defaultselseNone,
annotationsifannotationselseNone,
)
_get_encoding_line_re=LazyReCompile(r"^.*coding[:=]\s*([-\w.]+).*$")
defget_encoding(obj)->str:
"""Try to obtain encoding information of the source of an object."""
forlineininspect.findsource(obj)[0][:2]:
m=_get_encoding_line_re.search(line)
ifm:
returnm.group(1)
return"utf8"
defget_encoding_file(fname:str)->str:
"""Try to obtain encoding information from a Python source file."""
withopen(fname,encoding="ascii",errors="ignore")asf:
for_inrange(2):
line=f.readline()
match=_get_encoding_line_re.search(line)
ifmatch:
returnmatch.group(1)
return"utf8"
defgetattr_safe(obj:Any,name:str)->Any:
"""Side effect free getattr (calls getattr_static)."""
result=inspect.getattr_static(obj,name)
# Slots are a MemberDescriptorType
ifisinstance(result,MemberDescriptorType):
result=getattr(obj,name)
# classmethods are safe to access (see #966)
ifisinstance(result, (classmethod,staticmethod)):
result=result.__get__(obj,obj)
returnresult
defhasattr_safe(obj:Any,name:str)->bool:
try:
getattr_safe(obj,name)
returnTrue
exceptAttributeError:
returnFalse