-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathinspector.py
541 lines (443 loc) · 18.9 KB
/
inspector.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import inspect
import re
import sys
import typing
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Type, Union
import torch
from torch import Tensor
class Parameter(NamedTuple):
name: str
type: Type
type_repr: str
default: Any
class Signature(NamedTuple):
param_dict: Dict[str, Parameter]
return_type: Type
return_type_repr: str
class Inspector:
r"""Inspects a given class and collects information about its instance
methods.
Args:
cls (Type): The class to inspect.
"""
def __init__(self, cls: Type):
self._cls = cls
self._signature_dict: Dict[str, Signature] = {}
self._source_dict: Dict[str, str] = {}
def _get_modules(self, cls: Type) -> List[str]:
from torch_geometric.nn import MessagePassing
modules: List[str] = []
for base_cls in cls.__bases__:
if base_cls not in {object, torch.nn.Module, MessagePassing}:
modules.extend(self._get_modules(base_cls))
modules.append(cls.__module__)
return modules
@property
def _modules(self) -> List[str]:
return self._get_modules(self._cls)
@property
def _globals(self) -> Dict[str, Any]:
out: Dict[str, Any] = {}
for module in self._modules:
out.update(sys.modules[module].__dict__)
return out
def __repr__(self) -> str:
return f'{self.__class__.__name__}({self._cls.__name__})'
def eval_type(self, value: Any) -> Type:
r"""Returns the type hint of a string."""
return eval_type(value, self._globals)
def type_repr(self, obj: Any) -> str:
r"""Returns the type hint representation of an object."""
return type_repr(obj, self._globals)
def implements(self, func_name: str) -> bool:
r"""Returns :obj:`True` in case the inspected class implements the
:obj:`func_name` method.
Args:
func_name (str): The function name to check for existence.
"""
func = getattr(self._cls, func_name, None)
if not callable(func):
return False
return not getattr(func, '__isabstractmethod__', False)
# Inspecting Method Signatures ############################################
def inspect_signature(
self,
func: Union[Callable, str],
exclude: Optional[List[Union[str, int]]] = None,
) -> Signature:
r"""Inspects the function signature of :obj:`func` and returns a tuple
of parameter types and return type.
Args:
func (callabel or str): The function.
exclude (list[int or str]): A list of parameters to exclude, either
given by their name or index. (default: :obj:`None`)
"""
if isinstance(func, str):
func = getattr(self._cls, func)
assert callable(func)
if func.__name__ in self._signature_dict:
return self._signature_dict[func.__name__]
signature = inspect.signature(func)
params = [p for p in signature.parameters.values() if p.name != 'self']
param_dict: Dict[str, Parameter] = {}
for i, param in enumerate(params):
if exclude is not None and (i in exclude or param.name in exclude):
continue
param_type = param.annotation
# Mimic TorchScript to auto-infer `Tensor` on non-present types:
param_type = Tensor if param_type is inspect._empty else param_type
param_dict[param.name] = Parameter(
name=param.name,
type=self.eval_type(param_type),
type_repr=self.type_repr(param_type),
default=param.default,
)
return_type = signature.return_annotation
# Mimic TorchScript to auto-infer `Tensor` on non-present types:
return_type = Tensor if return_type is inspect._empty else return_type
self._signature_dict[func.__name__] = Signature(
param_dict=param_dict,
return_type=self.eval_type(return_type),
return_type_repr=self.type_repr(return_type),
)
return self._signature_dict[func.__name__]
def get_signature(
self,
func: Union[Callable, str],
exclude: Optional[List[str]] = None,
) -> Signature:
r"""Returns the function signature of the inspected function
:obj:`func`.
Args:
func (callabel or str): The function.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
func_name = func if isinstance(func, str) else func.__name__
signature = self._signature_dict.get(func_name)
if signature is None:
raise IndexError(f"Could not access signature for function "
f"'{func_name}'. Did you forget to inspect it?")
if exclude is None:
return signature
param_dict = {
name: param
for name, param in signature.param_dict.items()
if name not in exclude
}
return Signature(
param_dict=param_dict,
return_type=signature.return_type,
return_type_repr=signature.return_type_repr,
)
def remove_signature(
self,
func: Union[Callable, str],
) -> Optional[Signature]:
r"""Removes the inspected function signature :obj:`func`.
Args:
func (callabel or str): The function.
"""
func_name = func if isinstance(func, str) else func.__name__
return self._signature_dict.pop(func_name, None)
def get_param_dict(
self,
func: Union[Callable, str],
exclude: Optional[List[str]] = None,
) -> Dict[str, Parameter]:
r"""Returns the parameters of the inspected function :obj:`func`.
Args:
func (str or callable): The function.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
return self.get_signature(func, exclude).param_dict
def get_params(
self,
func: Union[Callable, str],
exclude: Optional[List[str]] = None,
) -> List[Parameter]:
r"""Returns the parameters of the inspected function :obj:`func`.
Args:
func (str or callable): The function.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
return list(self.get_param_dict(func, exclude).values())
def get_flat_param_dict(
self,
funcs: List[Union[Callable, str]],
exclude: Optional[List[str]] = None,
) -> Dict[str, Parameter]:
r"""Returns the union of parameters of all inspected functions in
:obj:`funcs`.
Args:
funcs (list[str or callable]): The functions.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
param_dict: Dict[str, Parameter] = {}
for func in funcs:
params = self.get_params(func, exclude)
for param in params:
expected = param_dict.get(param.name)
if expected is not None and param.type != expected.type:
raise ValueError(f"Found inconsistent types for argument "
f"'{param.name}'. Expected type "
f"'{expected.type}' but found type "
f"'{param.type}'.")
if expected is not None and param.default != expected.default:
if (param.default is not inspect._empty
and expected.default is not inspect._empty):
raise ValueError(f"Found inconsistent defaults for "
f"argument '{param.name}'. Expected "
f"'{expected.default}' but found "
f"'{param.default}'.")
default = expected.default
if default is inspect._empty:
default = param.default
param_dict[param.name] = Parameter(
name=param.name,
type=param.type,
type_repr=param.type_repr,
default=default,
)
if expected is None:
param_dict[param.name] = param
return param_dict
def get_flat_params(
self,
funcs: List[Union[Callable, str]],
exclude: Optional[List[str]] = None,
) -> List[Parameter]:
r"""Returns the union of parameters of all inspected functions in
:obj:`funcs`.
Args:
funcs (list[str or callable]): The functions.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
return list(self.get_flat_param_dict(funcs, exclude).values())
def get_param_names(
self,
func: Union[Callable, str],
exclude: Optional[List[str]] = None,
) -> List[str]:
r"""Returns the parameter names of the inspected function :obj:`func`.
Args:
func (str or callable): The function.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
return list(self.get_param_dict(func, exclude).keys())
def get_flat_param_names(
self,
funcs: List[Union[Callable, str]],
exclude: Optional[List[str]] = None,
) -> List[str]:
r"""Returns the union of parameter names of all inspected functions in
:obj:`funcs`.
Args:
funcs (list[str or callable]): The functions.
exclude (list[str], optional): The parameter names to exclude.
(default: :obj:`None`)
"""
return list(self.get_flat_param_dict(funcs, exclude).keys())
def collect_param_data(
self,
func: Union[Callable, str],
kwargs: Dict[str, Any],
) -> Dict[str, Any]:
r"""Collects the input data of the inspected function :obj:`func`
according to its function signature from a data blob.
Args:
func (callable or str): The function.
kwargs (dict[str, Any]): The data blob which may serve as inputs.
"""
out_dict: Dict[str, Any] = {}
for param in self.get_params(func):
if param.name not in kwargs:
if param.default is inspect._empty:
raise TypeError(f"Parameter '{param.name}' is required")
out_dict[param.name] = param.default
else:
out_dict[param.name] = kwargs[param.name]
return out_dict
# Inspecting Method Bodies ################################################
def get_source(self, cls: Optional[Type] = None) -> str:
r"""Returns the source code of :obj:`cls`."""
from torch_geometric.nn import MessagePassing
cls = cls or self._cls
if cls.__name__ in self._source_dict:
return self._source_dict[cls.__name__]
if cls in {object, torch.nn.Module, MessagePassing}:
return ''
source = inspect.getsource(cls)
self._source_dict[cls.__name__] = source
return source
def get_params_from_method_call(
self,
func: Union[Callable, str],
exclude: Optional[List[Union[int, str]]] = None,
) -> Dict[str, Parameter]:
r"""Parses a method call of :obj:`func` and returns its keyword
arguments.
.. note::
The method is required to be called via keyword arguments in case
type annotations are not found.
Args:
func (callable or str): The function.
exclude (list[int or str]): A list of parameters to exclude, either
given by their name or index. (default: :obj:`None`)
"""
func_name = func if isinstance(func, str) else func.__name__
param_dict: Dict[str, Parameter] = {}
# Three ways to specify the parameters of an unknown function header:
# 1. Defined as class attributes in `{func_name}_type`.
# 2. Defined via type annotations in `# {func_name}_type: (...)`.
# 3. Defined via parsing of the function call.
# (1) Find class attribute:
if hasattr(self._cls, f'{func_name}_type'):
type_dict = getattr(self._cls, f'{func_name}_type')
if not isinstance(type_dict, dict):
raise ValueError(f"'{func_name}_type' is expected to be a "
f"dictionary (got '{type(type_dict)}')")
for name, param_type in type_dict.items():
param_dict[name] = Parameter(
name=name,
type=self.eval_type(param_type),
type_repr=self.type_repr(param_type),
default=inspect._empty,
)
return param_dict
# (2) Find type annotation:
for cls in self._cls.__mro__:
source = self.get_source(cls)
match = find_parenthesis_content(source, f'{func_name}_type:')
if match is not None:
for arg in split(match, sep=','):
name_and_type_repr = re.split(r'\s*:\s*', arg)
if len(name_and_type_repr) != 2:
raise ValueError(f"Could not parse argument '{arg}' "
f"of '{func_name}_type' annotation")
name, type_repr = name_and_type_repr
param_dict[name] = Parameter(
name=name,
type=self.eval_type(type_repr),
type_repr=type_repr,
default=inspect._empty,
)
return param_dict
# (3) Parse the function call:
for cls in self._cls.__mro__:
source = self.get_source(cls)
source = remove_comments(source)
match = find_parenthesis_content(source, f'self.{func_name}')
if match is not None:
for i, kwarg in enumerate(split(match, sep=',')):
if ('=' not in kwarg and exclude is not None
and i in exclude):
continue
name_and_content = re.split(r'\s*=\s*', kwarg)
if len(name_and_content) != 2:
raise ValueError(f"Could not parse keyword argument "
f"'{kwarg}' in 'self.{func_name}()'")
name, _ = name_and_content
if exclude is not None and name in exclude:
continue
param_dict[name] = Parameter(
name=name,
type=Tensor,
type_repr=self.type_repr(Tensor),
default=inspect._empty,
)
return param_dict
return {} # (4) No function call found:
def eval_type(value: Any, _globals: Dict[str, Any]) -> Type:
r"""Returns the type hint of a string."""
if isinstance(value, str):
value = typing.ForwardRef(value)
return typing._eval_type(value, _globals, None) # type: ignore
def type_repr(obj: Any, _globals: Dict[str, Any]) -> str:
r"""Returns the type hint representation of an object."""
def _get_name(name: str, module: str) -> str:
return name if name in _globals else f'{module}.{name}'
if isinstance(obj, str):
return obj
if obj is type(None):
return 'None'
if obj is ...:
return '...'
if obj.__module__ == 'typing': # Special logic for `typing.*` types:
if not hasattr(obj, '_name'):
return repr(obj)
name = obj._name
if name is None: # In some cases, `_name` is not populated.
name = str(obj.__origin__).split('.')[-1]
args = getattr(obj, '__args__', None)
if args is None or len(args) == 0:
return _get_name(name, obj.__module__)
if all(isinstance(arg, typing.TypeVar) for arg in args):
return _get_name(name, obj.__module__)
# Convert `Union[*, None]` to `Optional[*]`.
# This is only necessary for old Python versions, e.g. 3.8.
# TODO Only convert to `Optional` if `Optional` is importable.
if (name == 'Union' and len(args) == 2
and any([arg is type(None) for arg in args])):
name = 'Optional'
if name == 'Optional': # Remove `None` from `Optional` arguments:
args = [arg for arg in obj.__args__ if arg is not type(None)]
args_repr = ', '.join([type_repr(arg, _globals) for arg in args])
return f'{_get_name(name, obj.__module__)}[{args_repr}]'
if obj.__module__ == 'builtins':
return obj.__qualname__
return _get_name(obj.__qualname__, obj.__module__)
def find_parenthesis_content(source: str, prefix: str) -> Optional[str]:
r"""Returns the content of :obj:`{prefix}.*(...)` within :obj:`source`."""
match = re.search(prefix, source)
if match is None:
return None
offset = source[match.start():].find('(')
if offset < 0:
return None
source = source[match.start() + offset:]
depth = 0
for end, char in enumerate(source):
if char == '(':
depth += 1
if char == ')':
depth -= 1
if depth == 0:
content = source[1:end]
# Properly handle line breaks and multiple white-spaces:
content = content.replace('\n', ' ')
content = content.replace('#', ' ')
content = re.sub(' +', ' ', content)
content = content.strip()
return content
return None
def split(content: str, sep: str) -> List[str]:
r"""Splits :obj:`content` based on :obj:`sep`.
:obj:`sep` inside parentheses or square brackets are ignored.
"""
assert len(sep) == 1
outs: List[str] = []
start = depth = 0
for end, char in enumerate(content):
if char == '[' or char == '(':
depth += 1
elif char == ']' or char == ')':
depth -= 1
elif char == sep and depth == 0:
outs.append(content[start:end].strip())
start = end + 1
if start != len(content): # Respect dangling `sep`:
outs.append(content[start:].strip())
return outs
def remove_comments(content: str) -> str:
content = re.sub(r'\s*#.*', '', content)
content = re.sub(re.compile(r'r"""(.*?)"""', re.DOTALL), '', content)
content = re.sub(re.compile(r'"""(.*?)"""', re.DOTALL), '', content)
content = re.sub(re.compile(r"r'''(.*?)'''", re.DOTALL), '', content)
content = re.sub(re.compile(r"'''(.*?)'''", re.DOTALL), '', content)
return content