forked from smontanaro/python-bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
help.py
52 lines (47 loc) · 1.51 KB
/
help.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
def help(x):
"""display an object's __doc__ attribute if it has one"""
try:
print "synopsis:", _prototype(x)
if hasattr(x, "__doc__") and x.__doc__ is not None:
print x.__doc__
except TypeError:
if hasattr(x, "__doc__") and x.__doc__ is not None:
print x.__doc__
else:
print "no docstring available"
# from .../Include/compile.h
_OPTIMIZED = 1
_NEWLOCALS = 2
_VARARGS = 4
_VARKEYWORDS = 8
def _prototype(x):
import types
if type(x) not in (types.FunctionType, types.LambdaType,
types.MethodType, types.UnboundMethodType):
raise TypeError, "not a function type"
if type(x) in (types.LambdaType, types.FunctionType):
func = x
elif type(x) in (types.MethodType, types.UnboundMethodType):
func = x.im_func
code = func.func_code
varargs = code.co_flags & _VARARGS
varkwds = code.co_flags & _VARKEYWORDS
args = list(code.co_varnames)
nargs = code.co_argcount
# decorate parameters with defaults
dvals = list(func.func_defaults)
i = nargs-1
while dvals and i >= 0:
args[i] = "%s=%s" % (args[i], `dvals.pop()`)
i = i - 1
# decorate varargs and varkeywords
if varargs:
args[nargs] = "*" + args[nargs]
nargs = nargs + 1
if varkwds:
args[nargs] = "**" + args[nargs]
nargs = nargs + 1
proto = ["%s(" % code.co_name]
proto.append(", ".join(args[:nargs]))
proto.append(")")
return "".join(proto)