func_inspect.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. """
  2. My own variation on function-specific inspect-like features.
  3. """
  4. # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
  5. # Copyright (c) 2009 Gael Varoquaux
  6. # License: BSD Style, 3 clauses.
  7. import collections
  8. import inspect
  9. import os
  10. import re
  11. import warnings
  12. from itertools import islice
  13. from tokenize import open as open_py_source
  14. from .logger import pformat
  15. full_argspec_fields = (
  16. "args varargs varkw defaults kwonlyargs kwonlydefaults annotations"
  17. )
  18. full_argspec_type = collections.namedtuple("FullArgSpec", full_argspec_fields)
  19. def get_func_code(func):
  20. """Attempts to retrieve a reliable function code hash.
  21. The reason we don't use inspect.getsource is that it caches the
  22. source, whereas we want this to be modified on the fly when the
  23. function is modified.
  24. Returns
  25. -------
  26. func_code: string
  27. The function code
  28. source_file: string
  29. The path to the file in which the function is defined.
  30. first_line: int
  31. The first line of the code in the source file.
  32. Notes
  33. ------
  34. This function does a bit more magic than inspect, and is thus
  35. more robust.
  36. """
  37. source_file = None
  38. try:
  39. code = func.__code__
  40. source_file = code.co_filename
  41. if not os.path.exists(source_file):
  42. # Use inspect for lambda functions and functions defined in an
  43. # interactive shell, or in doctests
  44. source_code = "".join(inspect.getsourcelines(func)[0])
  45. line_no = 1
  46. if source_file.startswith("<doctest "):
  47. source_file, line_no = re.match(
  48. r"\<doctest (.*\.rst)\[(.*)\]\>", source_file
  49. ).groups()
  50. line_no = int(line_no)
  51. source_file = "<doctest %s>" % source_file
  52. return source_code, source_file, line_no
  53. # Try to retrieve the source code.
  54. with open_py_source(source_file) as source_file_obj:
  55. first_line = code.co_firstlineno
  56. # All the lines after the function definition:
  57. source_lines = list(islice(source_file_obj, first_line - 1, None))
  58. return "".join(inspect.getblock(source_lines)), source_file, first_line
  59. except: # noqa: E722
  60. # If the source code fails, we use the hash. This is fragile and
  61. # might change from one session to another.
  62. if hasattr(func, "__code__"):
  63. # Python 3.X
  64. return str(func.__code__.__hash__()), source_file, -1
  65. else:
  66. # Weird objects like numpy ufunc don't have __code__
  67. # This is fragile, as quite often the id of the object is
  68. # in the repr, so it might not persist across sessions,
  69. # however it will work for ufuncs.
  70. return repr(func), source_file, -1
  71. def _clean_win_chars(string):
  72. """Windows cannot encode some characters in filename."""
  73. import urllib
  74. if hasattr(urllib, "quote"):
  75. quote = urllib.quote
  76. else:
  77. # In Python 3, quote is elsewhere
  78. import urllib.parse
  79. quote = urllib.parse.quote
  80. for char in ("<", ">", "!", ":", "\\"):
  81. string = string.replace(char, quote(char))
  82. return string
  83. def get_func_name(func, resolv_alias=True, win_characters=True):
  84. """Return the function import path (as a list of module names), and
  85. a name for the function.
  86. Parameters
  87. ----------
  88. func: callable
  89. The func to inspect
  90. resolv_alias: boolean, optional
  91. If true, possible local aliases are indicated.
  92. win_characters: boolean, optional
  93. If true, substitute special characters using urllib.quote
  94. This is useful in Windows, as it cannot encode some filenames
  95. """
  96. if hasattr(func, "__module__"):
  97. module = func.__module__
  98. else:
  99. try:
  100. module = inspect.getmodule(func)
  101. except TypeError:
  102. if hasattr(func, "__class__"):
  103. module = func.__class__.__module__
  104. else:
  105. module = "unknown"
  106. if module is None:
  107. # Happens in doctests, eg
  108. module = ""
  109. if module == "__main__":
  110. try:
  111. filename = os.path.abspath(inspect.getsourcefile(func))
  112. except: # noqa: E722
  113. filename = None
  114. if filename is not None:
  115. # mangling of full path to filename
  116. parts = filename.split(os.sep)
  117. if parts[-1].startswith("<ipython-input"):
  118. # We're in a IPython (or notebook) session. parts[-1] comes
  119. # from func.__code__.co_filename and is of the form
  120. # <ipython-input-N-XYZ>, where:
  121. # - N is the cell number where the function was defined
  122. # - XYZ is a hash representing the function's code (and name).
  123. # It will be consistent across sessions and kernel restarts,
  124. # and will change if the function's code/name changes
  125. # We remove N so that cache is properly hit if the cell where
  126. # the func is defined is re-exectuted.
  127. # The XYZ hash should avoid collisions between functions with
  128. # the same name, both within the same notebook but also across
  129. # notebooks
  130. split = parts[-1].split("-")
  131. parts[-1] = "-".join(split[:2] + split[3:])
  132. elif len(parts) > 2 and parts[-2].startswith("ipykernel_"):
  133. # In a notebook session (ipykernel). Filename seems to be 'xyz'
  134. # of above. parts[-2] has the structure ipykernel_XXXXXX where
  135. # XXXXXX is a six-digit number identifying the current run (?).
  136. # If we split it off, the function again has the same
  137. # identifier across runs.
  138. parts[-2] = "ipykernel"
  139. filename = "-".join(parts)
  140. if filename.endswith(".py"):
  141. filename = filename[:-3]
  142. module = module + "-" + filename
  143. module = module.split(".")
  144. if hasattr(func, "func_name"):
  145. name = func.func_name
  146. elif hasattr(func, "__name__"):
  147. name = func.__name__
  148. else:
  149. name = "unknown"
  150. # Hack to detect functions not defined at the module-level
  151. if resolv_alias:
  152. # TODO: Maybe add a warning here?
  153. if hasattr(func, "func_globals") and name in func.func_globals:
  154. if func.func_globals[name] is not func:
  155. name = "%s-alias" % name
  156. if hasattr(func, "__qualname__") and func.__qualname__ != name:
  157. # Extend the module name in case of nested functions to avoid
  158. # (module, name) collisions
  159. module.extend(func.__qualname__.split(".")[:-1])
  160. if inspect.ismethod(func):
  161. # We need to add the name of the class
  162. if hasattr(func, "im_class"):
  163. klass = func.im_class
  164. module.append(klass.__name__)
  165. if os.name == "nt" and win_characters:
  166. # Windows can't encode certain characters in filenames
  167. name = _clean_win_chars(name)
  168. module = [_clean_win_chars(s) for s in module]
  169. return module, name
  170. def _signature_str(function_name, arg_sig):
  171. """Helper function to output a function signature"""
  172. return "{}{}".format(function_name, arg_sig)
  173. def _function_called_str(function_name, args, kwargs):
  174. """Helper function to output a function call"""
  175. template_str = "{0}({1}, {2})"
  176. args_str = repr(args)[1:-1]
  177. kwargs_str = ", ".join("%s=%s" % (k, v) for k, v in kwargs.items())
  178. return template_str.format(function_name, args_str, kwargs_str)
  179. def filter_args(func, ignore_lst, args=(), kwargs=dict()):
  180. """Filters the given args and kwargs using a list of arguments to
  181. ignore, and a function specification.
  182. Parameters
  183. ----------
  184. func: callable
  185. Function giving the argument specification
  186. ignore_lst: list of strings
  187. List of arguments to ignore (either a name of an argument
  188. in the function spec, or '*', or '**')
  189. *args: list
  190. Positional arguments passed to the function.
  191. **kwargs: dict
  192. Keyword arguments passed to the function
  193. Returns
  194. -------
  195. filtered_args: list
  196. List of filtered positional and keyword arguments.
  197. """
  198. args = list(args)
  199. if isinstance(ignore_lst, str):
  200. # Catch a common mistake
  201. raise ValueError(
  202. "ignore_lst must be a list of parameters to ignore "
  203. "%s (type %s) was given" % (ignore_lst, type(ignore_lst))
  204. )
  205. # Special case for functools.partial objects
  206. if not inspect.ismethod(func) and not inspect.isfunction(func):
  207. if ignore_lst:
  208. warnings.warn(
  209. "Cannot inspect object %s, ignore list will not work." % func,
  210. stacklevel=2,
  211. )
  212. return {"*": args, "**": kwargs}
  213. arg_sig = inspect.signature(func)
  214. arg_names = []
  215. arg_defaults = []
  216. arg_kwonlyargs = []
  217. arg_varargs = None
  218. arg_varkw = None
  219. for param in arg_sig.parameters.values():
  220. if param.kind is param.POSITIONAL_OR_KEYWORD:
  221. arg_names.append(param.name)
  222. elif param.kind is param.KEYWORD_ONLY:
  223. arg_names.append(param.name)
  224. arg_kwonlyargs.append(param.name)
  225. elif param.kind is param.VAR_POSITIONAL:
  226. arg_varargs = param.name
  227. elif param.kind is param.VAR_KEYWORD:
  228. arg_varkw = param.name
  229. if param.default is not param.empty:
  230. arg_defaults.append(param.default)
  231. if inspect.ismethod(func):
  232. # First argument is 'self', it has been removed by Python
  233. # we need to add it back:
  234. args = [
  235. func.__self__,
  236. ] + args
  237. # func is an instance method, inspect.signature(func) does not
  238. # include self, we need to fetch it from the class method, i.e
  239. # func.__func__
  240. class_method_sig = inspect.signature(func.__func__)
  241. self_name = next(iter(class_method_sig.parameters))
  242. arg_names = [self_name] + arg_names
  243. # XXX: Maybe I need an inspect.isbuiltin to detect C-level methods, such
  244. # as on ndarrays.
  245. _, name = get_func_name(func, resolv_alias=False)
  246. arg_dict = dict()
  247. arg_position = -1
  248. for arg_position, arg_name in enumerate(arg_names):
  249. if arg_position < len(args):
  250. # Positional argument or keyword argument given as positional
  251. if arg_name not in arg_kwonlyargs:
  252. arg_dict[arg_name] = args[arg_position]
  253. else:
  254. raise ValueError(
  255. "Keyword-only parameter '%s' was passed as "
  256. "positional parameter for %s:\n"
  257. " %s was called."
  258. % (
  259. arg_name,
  260. _signature_str(name, arg_sig),
  261. _function_called_str(name, args, kwargs),
  262. )
  263. )
  264. else:
  265. position = arg_position - len(arg_names)
  266. if arg_name in kwargs:
  267. arg_dict[arg_name] = kwargs[arg_name]
  268. else:
  269. try:
  270. arg_dict[arg_name] = arg_defaults[position]
  271. except (IndexError, KeyError) as e:
  272. # Missing argument
  273. raise ValueError(
  274. "Wrong number of arguments for %s:\n"
  275. " %s was called."
  276. % (
  277. _signature_str(name, arg_sig),
  278. _function_called_str(name, args, kwargs),
  279. )
  280. ) from e
  281. varkwargs = dict()
  282. for arg_name, arg_value in sorted(kwargs.items()):
  283. if arg_name in arg_dict:
  284. arg_dict[arg_name] = arg_value
  285. elif arg_varkw is not None:
  286. varkwargs[arg_name] = arg_value
  287. else:
  288. raise TypeError(
  289. "Ignore list for %s() contains an unexpected "
  290. "keyword argument '%s'" % (name, arg_name)
  291. )
  292. if arg_varkw is not None:
  293. arg_dict["**"] = varkwargs
  294. if arg_varargs is not None:
  295. varargs = args[arg_position + 1 :]
  296. arg_dict["*"] = varargs
  297. # Now remove the arguments to be ignored
  298. for item in ignore_lst:
  299. if item in arg_dict:
  300. arg_dict.pop(item)
  301. else:
  302. raise ValueError(
  303. "Ignore list: argument '%s' is not defined for "
  304. "function %s" % (item, _signature_str(name, arg_sig))
  305. )
  306. # XXX: Return a sorted list of pairs?
  307. return arg_dict
  308. def _format_arg(arg):
  309. formatted_arg = pformat(arg, indent=2)
  310. if len(formatted_arg) > 1500:
  311. formatted_arg = "%s..." % formatted_arg[:700]
  312. return formatted_arg
  313. def format_signature(func, *args, **kwargs):
  314. # XXX: Should this use inspect.formatargvalues/formatargspec?
  315. module, name = get_func_name(func)
  316. module = [m for m in module if m]
  317. if module:
  318. module.append(name)
  319. module_path = ".".join(module)
  320. else:
  321. module_path = name
  322. arg_str = list()
  323. previous_length = 0
  324. for arg in args:
  325. formatted_arg = _format_arg(arg)
  326. if previous_length > 80:
  327. formatted_arg = "\n%s" % formatted_arg
  328. previous_length = len(formatted_arg)
  329. arg_str.append(formatted_arg)
  330. arg_str.extend(["%s=%s" % (v, _format_arg(i)) for v, i in kwargs.items()])
  331. arg_str = ", ".join(arg_str)
  332. signature = "%s(%s)" % (name, arg_str)
  333. return module_path, signature
  334. def format_call(func, args, kwargs, object_name="Memory"):
  335. """Returns a nicely formatted statement displaying the function
  336. call with the given arguments.
  337. """
  338. path, signature = format_signature(func, *args, **kwargs)
  339. msg = "%s\n[%s] Calling %s...\n%s" % (80 * "_", object_name, path, signature)
  340. return msg
  341. # XXX: Not using logging framework
  342. # self.debug(msg)