overrides.py 6.9 KB

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