overrides.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. """Implementation of __array_function__ overrides from NEP-18."""
  2. import collections
  3. import functools
  4. from .._utils import set_module
  5. from .._utils._inspect import getargspec
  6. from numpy._core._multiarray_umath import (
  7. add_docstring, _get_implementing_args, _ArrayFunctionDispatcher)
  8. ARRAY_FUNCTIONS = set()
  9. array_function_like_doc = (
  10. """like : array_like, optional
  11. Reference object to allow the creation of arrays which are not
  12. NumPy arrays. If an array-like passed in as ``like`` supports
  13. the ``__array_function__`` protocol, the result will be defined
  14. by it. In this case, it ensures the creation of an array object
  15. compatible with that passed in via this argument."""
  16. )
  17. def get_array_function_like_doc(public_api, docstring_template=""):
  18. ARRAY_FUNCTIONS.add(public_api)
  19. docstring = public_api.__doc__ or docstring_template
  20. return docstring.replace("${ARRAY_FUNCTION_LIKE}", array_function_like_doc)
  21. def finalize_array_function_like(public_api):
  22. public_api.__doc__ = get_array_function_like_doc(public_api)
  23. return public_api
  24. add_docstring(
  25. _ArrayFunctionDispatcher,
  26. """
  27. Class to wrap functions with checks for __array_function__ overrides.
  28. All arguments are required, and can only be passed by position.
  29. Parameters
  30. ----------
  31. dispatcher : function or None
  32. The dispatcher function that returns a single sequence-like object
  33. of all arguments relevant. It must have the same signature (except
  34. the default values) as the actual implementation.
  35. If ``None``, this is a ``like=`` dispatcher and the
  36. ``_ArrayFunctionDispatcher`` must be called with ``like`` as the
  37. first (additional and positional) argument.
  38. implementation : function
  39. Function that implements the operation on NumPy arrays without
  40. overrides. Arguments passed calling the ``_ArrayFunctionDispatcher``
  41. will be forwarded to this (and the ``dispatcher``) as if using
  42. ``*args, **kwargs``.
  43. Attributes
  44. ----------
  45. _implementation : function
  46. The original implementation passed in.
  47. """)
  48. # exposed for testing purposes; used internally by _ArrayFunctionDispatcher
  49. add_docstring(
  50. _get_implementing_args,
  51. """
  52. Collect arguments on which to call __array_function__.
  53. Parameters
  54. ----------
  55. relevant_args : iterable of array-like
  56. Iterable of possibly array-like arguments to check for
  57. __array_function__ methods.
  58. Returns
  59. -------
  60. Sequence of arguments with __array_function__ methods, in the order in
  61. which they should be called.
  62. """)
  63. ArgSpec = collections.namedtuple('ArgSpec', 'args varargs keywords defaults')
  64. def verify_matching_signatures(implementation, dispatcher):
  65. """Verify that a dispatcher function has the right signature."""
  66. implementation_spec = ArgSpec(*getargspec(implementation))
  67. dispatcher_spec = ArgSpec(*getargspec(dispatcher))
  68. if (implementation_spec.args != dispatcher_spec.args or
  69. implementation_spec.varargs != dispatcher_spec.varargs or
  70. implementation_spec.keywords != dispatcher_spec.keywords or
  71. (bool(implementation_spec.defaults) !=
  72. bool(dispatcher_spec.defaults)) or
  73. (implementation_spec.defaults is not None and
  74. len(implementation_spec.defaults) !=
  75. len(dispatcher_spec.defaults))):
  76. raise RuntimeError('implementation and dispatcher for %s have '
  77. 'different function signatures' % implementation)
  78. if implementation_spec.defaults is not None:
  79. if dispatcher_spec.defaults != (None,) * len(dispatcher_spec.defaults):
  80. raise RuntimeError('dispatcher functions can only use None for '
  81. 'default argument values')
  82. def array_function_dispatch(dispatcher=None, module=None, verify=True,
  83. docs_from_dispatcher=False):
  84. """Decorator for adding dispatch with the __array_function__ protocol.
  85. See NEP-18 for example usage.
  86. Parameters
  87. ----------
  88. dispatcher : callable or None
  89. Function that when called like ``dispatcher(*args, **kwargs)`` with
  90. arguments from the NumPy function call returns an iterable of
  91. array-like arguments to check for ``__array_function__``.
  92. If `None`, the first argument is used as the single `like=` argument
  93. and not passed on. A function implementing `like=` must call its
  94. dispatcher with `like` as the first non-keyword argument.
  95. module : str, optional
  96. __module__ attribute to set on new function, e.g., ``module='numpy'``.
  97. By default, module is copied from the decorated function.
  98. verify : bool, optional
  99. If True, verify the that the signature of the dispatcher and decorated
  100. function signatures match exactly: all required and optional arguments
  101. should appear in order with the same names, but the default values for
  102. all optional arguments should be ``None``. Only disable verification
  103. if the dispatcher's signature needs to deviate for some particular
  104. reason, e.g., because the function has a signature like
  105. ``func(*args, **kwargs)``.
  106. docs_from_dispatcher : bool, optional
  107. If True, copy docs from the dispatcher function onto the dispatched
  108. function, rather than from the implementation. This is useful for
  109. functions defined in C, which otherwise don't have docstrings.
  110. Returns
  111. -------
  112. Function suitable for decorating the implementation of a NumPy function.
  113. """
  114. def decorator(implementation):
  115. if verify:
  116. if dispatcher is not None:
  117. verify_matching_signatures(implementation, dispatcher)
  118. else:
  119. # Using __code__ directly similar to verify_matching_signature
  120. co = implementation.__code__
  121. last_arg = co.co_argcount + co.co_kwonlyargcount - 1
  122. last_arg = co.co_varnames[last_arg]
  123. if last_arg != "like" or co.co_kwonlyargcount == 0:
  124. raise RuntimeError(
  125. "__array_function__ expects `like=` to be the last "
  126. "argument and a keyword-only argument. "
  127. f"{implementation} does not seem to comply.")
  128. if docs_from_dispatcher:
  129. add_docstring(implementation, dispatcher.__doc__)
  130. public_api = _ArrayFunctionDispatcher(dispatcher, implementation)
  131. public_api = functools.wraps(implementation)(public_api)
  132. if module is not None:
  133. public_api.__module__ = module
  134. ARRAY_FUNCTIONS.add(public_api)
  135. return public_api
  136. return decorator
  137. def array_function_from_dispatcher(
  138. implementation, module=None, verify=True, docs_from_dispatcher=True):
  139. """Like array_function_dispatcher, but with function arguments flipped."""
  140. def decorator(dispatcher):
  141. return array_function_dispatch(
  142. dispatcher, module, verify=verify,
  143. docs_from_dispatcher=docs_from_dispatcher)(implementation)
  144. return decorator