getargspec.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. """
  3. getargspec excerpted from:
  4. sphinx.util.inspect
  5. ~~~~~~~~~~~~~~~~~~~
  6. Helpers for inspecting Python modules.
  7. :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
  8. :license: BSD, see LICENSE for details.
  9. """
  10. import inspect
  11. from six import PY3
  12. # Unmodified from sphinx below this line
  13. if PY3:
  14. from functools import partial
  15. def getargspec(func):
  16. """Like inspect.getargspec but supports functools.partial as well."""
  17. if inspect.ismethod(func):
  18. func = func.__func__
  19. if type(func) is partial:
  20. orig_func = func.func
  21. argspec = getargspec(orig_func)
  22. args = list(argspec[0])
  23. defaults = list(argspec[3] or ())
  24. kwoargs = list(argspec[4])
  25. kwodefs = dict(argspec[5] or {})
  26. if func.args:
  27. args = args[len(func.args):]
  28. for arg in func.keywords or ():
  29. try:
  30. i = args.index(arg) - len(args)
  31. del args[i]
  32. try:
  33. del defaults[i]
  34. except IndexError:
  35. pass
  36. except ValueError: # must be a kwonly arg
  37. i = kwoargs.index(arg)
  38. del kwoargs[i]
  39. del kwodefs[arg]
  40. return inspect.FullArgSpec(args, argspec[1], argspec[2],
  41. tuple(defaults), kwoargs,
  42. kwodefs, argspec[6])
  43. while hasattr(func, '__wrapped__'):
  44. func = func.__wrapped__
  45. if not inspect.isfunction(func):
  46. raise TypeError('%r is not a Python function' % func)
  47. return inspect.getfullargspec(func)
  48. else: # 2.6, 2.7
  49. from functools import partial
  50. def getargspec(func):
  51. """Like inspect.getargspec but supports functools.partial as well."""
  52. if inspect.ismethod(func):
  53. func = func.__func__
  54. parts = 0, ()
  55. if type(func) is partial:
  56. keywords = func.keywords
  57. if keywords is None:
  58. keywords = {}
  59. parts = len(func.args), keywords.keys()
  60. func = func.func
  61. if not inspect.isfunction(func):
  62. raise TypeError('%r is not a Python function' % func)
  63. args, varargs, varkw = inspect.getargs(func.__code__)
  64. func_defaults = func.__defaults__
  65. if func_defaults is None:
  66. func_defaults = []
  67. else:
  68. func_defaults = list(func_defaults)
  69. if parts[0]:
  70. args = args[parts[0]:]
  71. if parts[1]:
  72. for arg in parts[1]:
  73. i = args.index(arg) - len(args)
  74. del args[i]
  75. try:
  76. del func_defaults[i]
  77. except IndexError:
  78. pass
  79. return inspect.ArgSpec(args, varargs, varkw, func_defaults)