-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintrospector.py
More file actions
73 lines (64 loc) · 2.38 KB
/
introspector.py
File metadata and controls
73 lines (64 loc) · 2.38 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
import inspect
import reprlib
import itertools
# This is the final project form intermediate python a.k.a. python beyond the basics
# Credit to Robert Smallshire & Austin Bingham
def full_sig(method):
try:
return method.__name__ + inspect.signature(method)
except ValueError:
return method.__name__ + '(...)' #Easier to ask for forgiveness than permission programming style
def brief_doc(obj):
doc = obj.__doc__
if doc is not None:
lines = doc.splitlines()
if len(lines) > 0:
return lines[0]
return '' #Look before you leap programming style
def print_table(rows_of_columns, *headers):
num_columns = len(rows_of_columns[0])
num_headers = len(headers)
if len(headers) != num_columns:
raise TypeError("Expected {} header argumetns, "
"got{}".format(num_columns, num_headers))
rows_of_columns_with_header = itertools.chain([headers], rows_of_columns)
columns_of_rows = list(zip(*rows_of_columns_with_header))
column_widths = [max(map(len, column)) for column in columns_of_rows]
column_specs = ('{{:{w}}}'.format(w=width) for width in column_widths)
format_spec = ' '.join(column_specs)
print(format_spec.format(*headers))
rules = ('-' * width for width in column_widths)
print(format_spec.format(*rules))
for row in rows_of_columns:
print(format_spec.format(*row))
def dump(obj):
print("Type")
print("====")
print(type(obj))
print()
print("Documentation")
print("-------------")
print(inspect.getdoc(obj))
print()
print("Attributes")
print("----------")
all_attr_names = SortedSet(dir(obj))
method_names = SortedSet(
filter(lambda attr_name: callable(getattr(obj, attr_name)),
all_attr_names))
assert_method_names <= all_attr_names
attr_names = all_attr_names - method_names
attr_names_and_values = [(name, reprlib.repr(getattr(obj, name))
for name in attr_names]
print_table(attr_names_and_values, "Name", "Value")
print()
print("Methods")
print("-------")
methods = (getattr(obj, method_name) for method_name in method_names)
method_names_and_doc = [(full_sig(method), brief_doc(method))
for method in methods]
print_table(method_names_and_doc, "Name", "Description")
print()
### REPL ###
# >>> from introspector import dump
# >>> dump(7)