_inspect.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. """Subset of inspect module from upstream python
  2. We use this instead of upstream because upstream inspect is slow to import, and
  3. significantly contributes to numpy import times. Importing this copy has almost
  4. no overhead.
  5. """
  6. import types
  7. __all__ = ['getargspec', 'formatargspec']
  8. # ----------------------------------------------------------- type-checking
  9. def ismethod(object):
  10. """Return true if the object is an instance method.
  11. Instance method objects provide these attributes:
  12. __doc__ documentation string
  13. __name__ name with which this method was defined
  14. im_class class object in which this method belongs
  15. im_func function object containing implementation of method
  16. im_self instance to which this method is bound, or None
  17. """
  18. return isinstance(object, types.MethodType)
  19. def isfunction(object):
  20. """Return true if the object is a user-defined function.
  21. Function objects provide these attributes:
  22. __doc__ documentation string
  23. __name__ name with which this function was defined
  24. func_code code object containing compiled function bytecode
  25. func_defaults tuple of any default values for arguments
  26. func_doc (same as __doc__)
  27. func_globals global namespace in which this function was defined
  28. func_name (same as __name__)
  29. """
  30. return isinstance(object, types.FunctionType)
  31. def iscode(object):
  32. """Return true if the object is a code object.
  33. Code objects provide these attributes:
  34. co_argcount number of arguments (not including * or ** args)
  35. co_code string of raw compiled bytecode
  36. co_consts tuple of constants used in the bytecode
  37. co_filename name of file in which this code object was created
  38. co_firstlineno number of first line in Python source code
  39. co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
  40. co_lnotab encoded mapping of line numbers to bytecode indices
  41. co_name name with which this code object was defined
  42. co_names tuple of names of local variables
  43. co_nlocals number of local variables
  44. co_stacksize virtual machine stack space required
  45. co_varnames tuple of names of arguments and local variables
  46. """
  47. return isinstance(object, types.CodeType)
  48. # ------------------------------------------------ argument list extraction
  49. # These constants are from Python's compile.h.
  50. CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
  51. def getargs(co):
  52. """Get information about the arguments accepted by a code object.
  53. Three things are returned: (args, varargs, varkw), where 'args' is
  54. a list of argument names (possibly containing nested lists), and
  55. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  56. """
  57. if not iscode(co):
  58. raise TypeError('arg is not a code object')
  59. nargs = co.co_argcount
  60. names = co.co_varnames
  61. args = list(names[:nargs])
  62. # The following acrobatics are for anonymous (tuple) arguments.
  63. # Which we do not need to support, so remove to avoid importing
  64. # the dis module.
  65. for i in range(nargs):
  66. if args[i][:1] in ['', '.']:
  67. raise TypeError("tuple function arguments are not supported")
  68. varargs = None
  69. if co.co_flags & CO_VARARGS:
  70. varargs = co.co_varnames[nargs]
  71. nargs = nargs + 1
  72. varkw = None
  73. if co.co_flags & CO_VARKEYWORDS:
  74. varkw = co.co_varnames[nargs]
  75. return args, varargs, varkw
  76. def getargspec(func):
  77. """Get the names and default values of a function's arguments.
  78. A tuple of four things is returned: (args, varargs, varkw, defaults).
  79. 'args' is a list of the argument names (it may contain nested lists).
  80. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  81. 'defaults' is an n-tuple of the default values of the last n arguments.
  82. """
  83. if ismethod(func):
  84. func = func.__func__
  85. if not isfunction(func):
  86. raise TypeError('arg is not a Python function')
  87. args, varargs, varkw = getargs(func.__code__)
  88. return args, varargs, varkw, func.__defaults__
  89. def getargvalues(frame):
  90. """Get information about arguments passed into a particular frame.
  91. A tuple of four things is returned: (args, varargs, varkw, locals).
  92. 'args' is a list of the argument names (it may contain nested lists).
  93. 'varargs' and 'varkw' are the names of the * and ** arguments or None.
  94. 'locals' is the locals dictionary of the given frame.
  95. """
  96. args, varargs, varkw = getargs(frame.f_code)
  97. return args, varargs, varkw, frame.f_locals
  98. def joinseq(seq):
  99. if len(seq) == 1:
  100. return '(' + seq[0] + ',)'
  101. else:
  102. return '(' + ', '.join(seq) + ')'
  103. def strseq(object, convert, join=joinseq):
  104. """Recursively walk a sequence, stringifying each element.
  105. """
  106. if type(object) in [list, tuple]:
  107. return join([strseq(_o, convert, join) for _o in object])
  108. else:
  109. return convert(object)
  110. def formatargspec(args, varargs=None, varkw=None, defaults=None,
  111. formatarg=str,
  112. formatvarargs=lambda name: '*' + name,
  113. formatvarkw=lambda name: '**' + name,
  114. formatvalue=lambda value: '=' + repr(value),
  115. join=joinseq):
  116. """Format an argument spec from the 4 values returned by getargspec.
  117. The first four arguments are (args, varargs, varkw, defaults). The
  118. other four arguments are the corresponding optional formatting functions
  119. that are called to turn names and values into strings. The ninth
  120. argument is an optional function to format the sequence of arguments.
  121. """
  122. specs = []
  123. if defaults:
  124. firstdefault = len(args) - len(defaults)
  125. for i in range(len(args)):
  126. spec = strseq(args[i], formatarg, join)
  127. if defaults and i >= firstdefault:
  128. spec = spec + formatvalue(defaults[i - firstdefault])
  129. specs.append(spec)
  130. if varargs is not None:
  131. specs.append(formatvarargs(varargs))
  132. if varkw is not None:
  133. specs.append(formatvarkw(varkw))
  134. return '(' + ', '.join(specs) + ')'
  135. def formatargvalues(args, varargs, varkw, locals,
  136. formatarg=str,
  137. formatvarargs=lambda name: '*' + name,
  138. formatvarkw=lambda name: '**' + name,
  139. formatvalue=lambda value: '=' + repr(value),
  140. join=joinseq):
  141. """Format an argument spec from the 4 values returned by getargvalues.
  142. The first four arguments are (args, varargs, varkw, locals). The
  143. next four arguments are the corresponding optional formatting functions
  144. that are called to turn names and values into strings. The ninth
  145. argument is an optional function to format the sequence of arguments.
  146. """
  147. def convert(name, locals=locals,
  148. formatarg=formatarg, formatvalue=formatvalue):
  149. return formatarg(name) + formatvalue(locals[name])
  150. specs = [strseq(arg, convert, join) for arg in args]
  151. if varargs:
  152. specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
  153. if varkw:
  154. specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
  155. return '(' + ', '.join(specs) + ')'