subclassing.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. """=============================
  2. Subclassing ndarray in python
  3. =============================
  4. Introduction
  5. ------------
  6. Subclassing ndarray is relatively simple, but it has some complications
  7. compared to other Python objects. On this page we explain the machinery
  8. that allows you to subclass ndarray, and the implications for
  9. implementing a subclass.
  10. ndarrays and object creation
  11. ============================
  12. Subclassing ndarray is complicated by the fact that new instances of
  13. ndarray classes can come about in three different ways. These are:
  14. #. Explicit constructor call - as in ``MySubClass(params)``. This is
  15. the usual route to Python instance creation.
  16. #. View casting - casting an existing ndarray as a given subclass
  17. #. New from template - creating a new instance from a template
  18. instance. Examples include returning slices from a subclassed array,
  19. creating return types from ufuncs, and copying arrays. See
  20. :ref:`new-from-template` for more details
  21. The last two are characteristics of ndarrays - in order to support
  22. things like array slicing. The complications of subclassing ndarray are
  23. due to the mechanisms numpy has to support these latter two routes of
  24. instance creation.
  25. .. _view-casting:
  26. View casting
  27. ------------
  28. *View casting* is the standard ndarray mechanism by which you take an
  29. ndarray of any subclass, and return a view of the array as another
  30. (specified) subclass:
  31. >>> import numpy as np
  32. >>> # create a completely useless ndarray subclass
  33. >>> class C(np.ndarray): pass
  34. >>> # create a standard ndarray
  35. >>> arr = np.zeros((3,))
  36. >>> # take a view of it, as our useless subclass
  37. >>> c_arr = arr.view(C)
  38. >>> type(c_arr)
  39. <class 'C'>
  40. .. _new-from-template:
  41. Creating new from template
  42. --------------------------
  43. New instances of an ndarray subclass can also come about by a very
  44. similar mechanism to :ref:`view-casting`, when numpy finds it needs to
  45. create a new instance from a template instance. The most obvious place
  46. this has to happen is when you are taking slices of subclassed arrays.
  47. For example:
  48. >>> v = c_arr[1:]
  49. >>> type(v) # the view is of type 'C'
  50. <class 'C'>
  51. >>> v is c_arr # but it's a new instance
  52. False
  53. The slice is a *view* onto the original ``c_arr`` data. So, when we
  54. take a view from the ndarray, we return a new ndarray, of the same
  55. class, that points to the data in the original.
  56. There are other points in the use of ndarrays where we need such views,
  57. such as copying arrays (``c_arr.copy()``), creating ufunc output arrays
  58. (see also :ref:`array-wrap`), and reducing methods (like
  59. ``c_arr.mean()``).
  60. Relationship of view casting and new-from-template
  61. --------------------------------------------------
  62. These paths both use the same machinery. We make the distinction here,
  63. because they result in different input to your methods. Specifically,
  64. :ref:`view-casting` means you have created a new instance of your array
  65. type from any potential subclass of ndarray. :ref:`new-from-template`
  66. means you have created a new instance of your class from a pre-existing
  67. instance, allowing you - for example - to copy across attributes that
  68. are particular to your subclass.
  69. Implications for subclassing
  70. ----------------------------
  71. If we subclass ndarray, we need to deal not only with explicit
  72. construction of our array type, but also :ref:`view-casting` or
  73. :ref:`new-from-template`. NumPy has the machinery to do this, and this
  74. machinery that makes subclassing slightly non-standard.
  75. There are two aspects to the machinery that ndarray uses to support
  76. views and new-from-template in subclasses.
  77. The first is the use of the ``ndarray.__new__`` method for the main work
  78. of object initialization, rather then the more usual ``__init__``
  79. method. The second is the use of the ``__array_finalize__`` method to
  80. allow subclasses to clean up after the creation of views and new
  81. instances from templates.
  82. A brief Python primer on ``__new__`` and ``__init__``
  83. =====================================================
  84. ``__new__`` is a standard Python method, and, if present, is called
  85. before ``__init__`` when we create a class instance. See the `python
  86. __new__ documentation
  87. <https://docs.python.org/reference/datamodel.html#object.__new__>`_ for more detail.
  88. For example, consider the following Python code:
  89. .. testcode::
  90. class C:
  91. def __new__(cls, *args):
  92. print('Cls in __new__:', cls)
  93. print('Args in __new__:', args)
  94. # The `object` type __new__ method takes a single argument.
  95. return object.__new__(cls)
  96. def __init__(self, *args):
  97. print('type(self) in __init__:', type(self))
  98. print('Args in __init__:', args)
  99. meaning that we get:
  100. >>> c = C('hello')
  101. Cls in __new__: <class 'C'>
  102. Args in __new__: ('hello',)
  103. type(self) in __init__: <class 'C'>
  104. Args in __init__: ('hello',)
  105. When we call ``C('hello')``, the ``__new__`` method gets its own class
  106. as first argument, and the passed argument, which is the string
  107. ``'hello'``. After python calls ``__new__``, it usually (see below)
  108. calls our ``__init__`` method, with the output of ``__new__`` as the
  109. first argument (now a class instance), and the passed arguments
  110. following.
  111. As you can see, the object can be initialized in the ``__new__``
  112. method or the ``__init__`` method, or both, and in fact ndarray does
  113. not have an ``__init__`` method, because all the initialization is
  114. done in the ``__new__`` method.
  115. Why use ``__new__`` rather than just the usual ``__init__``? Because
  116. in some cases, as for ndarray, we want to be able to return an object
  117. of some other class. Consider the following:
  118. .. testcode::
  119. class D(C):
  120. def __new__(cls, *args):
  121. print('D cls is:', cls)
  122. print('D args in __new__:', args)
  123. return C.__new__(C, *args)
  124. def __init__(self, *args):
  125. # we never get here
  126. print('In D __init__')
  127. meaning that:
  128. >>> obj = D('hello')
  129. D cls is: <class 'D'>
  130. D args in __new__: ('hello',)
  131. Cls in __new__: <class 'C'>
  132. Args in __new__: ('hello',)
  133. >>> type(obj)
  134. <class 'C'>
  135. The definition of ``C`` is the same as before, but for ``D``, the
  136. ``__new__`` method returns an instance of class ``C`` rather than
  137. ``D``. Note that the ``__init__`` method of ``D`` does not get
  138. called. In general, when the ``__new__`` method returns an object of
  139. class other than the class in which it is defined, the ``__init__``
  140. method of that class is not called.
  141. This is how subclasses of the ndarray class are able to return views
  142. that preserve the class type. When taking a view, the standard
  143. ndarray machinery creates the new ndarray object with something
  144. like::
  145. obj = ndarray.__new__(subtype, shape, ...
  146. where ``subdtype`` is the subclass. Thus the returned view is of the
  147. same class as the subclass, rather than being of class ``ndarray``.
  148. That solves the problem of returning views of the same type, but now
  149. we have a new problem. The machinery of ndarray can set the class
  150. this way, in its standard methods for taking views, but the ndarray
  151. ``__new__`` method knows nothing of what we have done in our own
  152. ``__new__`` method in order to set attributes, and so on. (Aside -
  153. why not call ``obj = subdtype.__new__(...`` then? Because we may not
  154. have a ``__new__`` method with the same call signature).
  155. The role of ``__array_finalize__``
  156. ==================================
  157. ``__array_finalize__`` is the mechanism that numpy provides to allow
  158. subclasses to handle the various ways that new instances get created.
  159. Remember that subclass instances can come about in these three ways:
  160. #. explicit constructor call (``obj = MySubClass(params)``). This will
  161. call the usual sequence of ``MySubClass.__new__`` then (if it exists)
  162. ``MySubClass.__init__``.
  163. #. :ref:`view-casting`
  164. #. :ref:`new-from-template`
  165. Our ``MySubClass.__new__`` method only gets called in the case of the
  166. explicit constructor call, so we can't rely on ``MySubClass.__new__`` or
  167. ``MySubClass.__init__`` to deal with the view casting and
  168. new-from-template. It turns out that ``MySubClass.__array_finalize__``
  169. *does* get called for all three methods of object creation, so this is
  170. where our object creation housekeeping usually goes.
  171. * For the explicit constructor call, our subclass will need to create a
  172. new ndarray instance of its own class. In practice this means that
  173. we, the authors of the code, will need to make a call to
  174. ``ndarray.__new__(MySubClass,...)``, a class-hierarchy prepared call to
  175. ``super(MySubClass, cls).__new__(cls, ...)``, or do view casting of an
  176. existing array (see below)
  177. * For view casting and new-from-template, the equivalent of
  178. ``ndarray.__new__(MySubClass,...`` is called, at the C level.
  179. The arguments that ``__array_finalize__`` receives differ for the three
  180. methods of instance creation above.
  181. The following code allows us to look at the call sequences and arguments:
  182. .. testcode::
  183. import numpy as np
  184. class C(np.ndarray):
  185. def __new__(cls, *args, **kwargs):
  186. print('In __new__ with class %s' % cls)
  187. return super(C, cls).__new__(cls, *args, **kwargs)
  188. def __init__(self, *args, **kwargs):
  189. # in practice you probably will not need or want an __init__
  190. # method for your subclass
  191. print('In __init__ with class %s' % self.__class__)
  192. def __array_finalize__(self, obj):
  193. print('In array_finalize:')
  194. print(' self type is %s' % type(self))
  195. print(' obj type is %s' % type(obj))
  196. Now:
  197. >>> # Explicit constructor
  198. >>> c = C((10,))
  199. In __new__ with class <class 'C'>
  200. In array_finalize:
  201. self type is <class 'C'>
  202. obj type is <type 'NoneType'>
  203. In __init__ with class <class 'C'>
  204. >>> # View casting
  205. >>> a = np.arange(10)
  206. >>> cast_a = a.view(C)
  207. In array_finalize:
  208. self type is <class 'C'>
  209. obj type is <type 'numpy.ndarray'>
  210. >>> # Slicing (example of new-from-template)
  211. >>> cv = c[:1]
  212. In array_finalize:
  213. self type is <class 'C'>
  214. obj type is <class 'C'>
  215. The signature of ``__array_finalize__`` is::
  216. def __array_finalize__(self, obj):
  217. One sees that the ``super`` call, which goes to
  218. ``ndarray.__new__``, passes ``__array_finalize__`` the new object, of our
  219. own class (``self``) as well as the object from which the view has been
  220. taken (``obj``). As you can see from the output above, the ``self`` is
  221. always a newly created instance of our subclass, and the type of ``obj``
  222. differs for the three instance creation methods:
  223. * When called from the explicit constructor, ``obj`` is ``None``
  224. * When called from view casting, ``obj`` can be an instance of any
  225. subclass of ndarray, including our own.
  226. * When called in new-from-template, ``obj`` is another instance of our
  227. own subclass, that we might use to update the new ``self`` instance.
  228. Because ``__array_finalize__`` is the only method that always sees new
  229. instances being created, it is the sensible place to fill in instance
  230. defaults for new object attributes, among other tasks.
  231. This may be clearer with an example.
  232. Simple example - adding an extra attribute to ndarray
  233. -----------------------------------------------------
  234. .. testcode::
  235. import numpy as np
  236. class InfoArray(np.ndarray):
  237. def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
  238. strides=None, order=None, info=None):
  239. # Create the ndarray instance of our type, given the usual
  240. # ndarray input arguments. This will call the standard
  241. # ndarray constructor, but return an object of our type.
  242. # It also triggers a call to InfoArray.__array_finalize__
  243. obj = super(InfoArray, subtype).__new__(subtype, shape, dtype,
  244. buffer, offset, strides,
  245. order)
  246. # set the new 'info' attribute to the value passed
  247. obj.info = info
  248. # Finally, we must return the newly created object:
  249. return obj
  250. def __array_finalize__(self, obj):
  251. # ``self`` is a new object resulting from
  252. # ndarray.__new__(InfoArray, ...), therefore it only has
  253. # attributes that the ndarray.__new__ constructor gave it -
  254. # i.e. those of a standard ndarray.
  255. #
  256. # We could have got to the ndarray.__new__ call in 3 ways:
  257. # From an explicit constructor - e.g. InfoArray():
  258. # obj is None
  259. # (we're in the middle of the InfoArray.__new__
  260. # constructor, and self.info will be set when we return to
  261. # InfoArray.__new__)
  262. if obj is None: return
  263. # From view casting - e.g arr.view(InfoArray):
  264. # obj is arr
  265. # (type(obj) can be InfoArray)
  266. # From new-from-template - e.g infoarr[:3]
  267. # type(obj) is InfoArray
  268. #
  269. # Note that it is here, rather than in the __new__ method,
  270. # that we set the default value for 'info', because this
  271. # method sees all creation of default objects - with the
  272. # InfoArray.__new__ constructor, but also with
  273. # arr.view(InfoArray).
  274. self.info = getattr(obj, 'info', None)
  275. # We do not need to return anything
  276. Using the object looks like this:
  277. >>> obj = InfoArray(shape=(3,)) # explicit constructor
  278. >>> type(obj)
  279. <class 'InfoArray'>
  280. >>> obj.info is None
  281. True
  282. >>> obj = InfoArray(shape=(3,), info='information')
  283. >>> obj.info
  284. 'information'
  285. >>> v = obj[1:] # new-from-template - here - slicing
  286. >>> type(v)
  287. <class 'InfoArray'>
  288. >>> v.info
  289. 'information'
  290. >>> arr = np.arange(10)
  291. >>> cast_arr = arr.view(InfoArray) # view casting
  292. >>> type(cast_arr)
  293. <class 'InfoArray'>
  294. >>> cast_arr.info is None
  295. True
  296. This class isn't very useful, because it has the same constructor as the
  297. bare ndarray object, including passing in buffers and shapes and so on.
  298. We would probably prefer the constructor to be able to take an already
  299. formed ndarray from the usual numpy calls to ``np.array`` and return an
  300. object.
  301. Slightly more realistic example - attribute added to existing array
  302. -------------------------------------------------------------------
  303. Here is a class that takes a standard ndarray that already exists, casts
  304. as our type, and adds an extra attribute.
  305. .. testcode::
  306. import numpy as np
  307. class RealisticInfoArray(np.ndarray):
  308. def __new__(cls, input_array, info=None):
  309. # Input array is an already formed ndarray instance
  310. # We first cast to be our class type
  311. obj = np.asarray(input_array).view(cls)
  312. # add the new attribute to the created instance
  313. obj.info = info
  314. # Finally, we must return the newly created object:
  315. return obj
  316. def __array_finalize__(self, obj):
  317. # see InfoArray.__array_finalize__ for comments
  318. if obj is None: return
  319. self.info = getattr(obj, 'info', None)
  320. So:
  321. >>> arr = np.arange(5)
  322. >>> obj = RealisticInfoArray(arr, info='information')
  323. >>> type(obj)
  324. <class 'RealisticInfoArray'>
  325. >>> obj.info
  326. 'information'
  327. >>> v = obj[1:]
  328. >>> type(v)
  329. <class 'RealisticInfoArray'>
  330. >>> v.info
  331. 'information'
  332. .. _array-ufunc:
  333. ``__array_ufunc__`` for ufuncs
  334. ------------------------------
  335. .. versionadded:: 1.13
  336. A subclass can override what happens when executing numpy ufuncs on it by
  337. overriding the default ``ndarray.__array_ufunc__`` method. This method is
  338. executed *instead* of the ufunc and should return either the result of the
  339. operation, or :obj:`NotImplemented` if the operation requested is not
  340. implemented.
  341. The signature of ``__array_ufunc__`` is::
  342. def __array_ufunc__(ufunc, method, *inputs, **kwargs):
  343. - *ufunc* is the ufunc object that was called.
  344. - *method* is a string indicating how the Ufunc was called, either
  345. ``"__call__"`` to indicate it was called directly, or one of its
  346. :ref:`methods<ufuncs.methods>`: ``"reduce"``, ``"accumulate"``,
  347. ``"reduceat"``, ``"outer"``, or ``"at"``.
  348. - *inputs* is a tuple of the input arguments to the ``ufunc``
  349. - *kwargs* contains any optional or keyword arguments passed to the
  350. function. This includes any ``out`` arguments, which are always
  351. contained in a tuple.
  352. A typical implementation would convert any inputs or outputs that are
  353. instances of one's own class, pass everything on to a superclass using
  354. ``super()``, and finally return the results after possible
  355. back-conversion. An example, taken from the test case
  356. ``test_ufunc_override_with_super`` in ``core/tests/test_umath.py``, is the
  357. following.
  358. .. testcode::
  359. input numpy as np
  360. class A(np.ndarray):
  361. def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs):
  362. args = []
  363. in_no = []
  364. for i, input_ in enumerate(inputs):
  365. if isinstance(input_, A):
  366. in_no.append(i)
  367. args.append(input_.view(np.ndarray))
  368. else:
  369. args.append(input_)
  370. outputs = out
  371. out_no = []
  372. if outputs:
  373. out_args = []
  374. for j, output in enumerate(outputs):
  375. if isinstance(output, A):
  376. out_no.append(j)
  377. out_args.append(output.view(np.ndarray))
  378. else:
  379. out_args.append(output)
  380. kwargs['out'] = tuple(out_args)
  381. else:
  382. outputs = (None,) * ufunc.nout
  383. info = {}
  384. if in_no:
  385. info['inputs'] = in_no
  386. if out_no:
  387. info['outputs'] = out_no
  388. results = super(A, self).__array_ufunc__(ufunc, method,
  389. *args, **kwargs)
  390. if results is NotImplemented:
  391. return NotImplemented
  392. if method == 'at':
  393. if isinstance(inputs[0], A):
  394. inputs[0].info = info
  395. return
  396. if ufunc.nout == 1:
  397. results = (results,)
  398. results = tuple((np.asarray(result).view(A)
  399. if output is None else output)
  400. for result, output in zip(results, outputs))
  401. if results and isinstance(results[0], A):
  402. results[0].info = info
  403. return results[0] if len(results) == 1 else results
  404. So, this class does not actually do anything interesting: it just
  405. converts any instances of its own to regular ndarray (otherwise, we'd
  406. get infinite recursion!), and adds an ``info`` dictionary that tells
  407. which inputs and outputs it converted. Hence, e.g.,
  408. >>> a = np.arange(5.).view(A)
  409. >>> b = np.sin(a)
  410. >>> b.info
  411. {'inputs': [0]}
  412. >>> b = np.sin(np.arange(5.), out=(a,))
  413. >>> b.info
  414. {'outputs': [0]}
  415. >>> a = np.arange(5.).view(A)
  416. >>> b = np.ones(1).view(A)
  417. >>> c = a + b
  418. >>> c.info
  419. {'inputs': [0, 1]}
  420. >>> a += b
  421. >>> a.info
  422. {'inputs': [0, 1], 'outputs': [0]}
  423. Note that another approach would be to to use ``getattr(ufunc,
  424. methods)(*inputs, **kwargs)`` instead of the ``super`` call. For this example,
  425. the result would be identical, but there is a difference if another operand
  426. also defines ``__array_ufunc__``. E.g., lets assume that we evalulate
  427. ``np.add(a, b)``, where ``b`` is an instance of another class ``B`` that has
  428. an override. If you use ``super`` as in the example,
  429. ``ndarray.__array_ufunc__`` will notice that ``b`` has an override, which
  430. means it cannot evaluate the result itself. Thus, it will return
  431. `NotImplemented` and so will our class ``A``. Then, control will be passed
  432. over to ``b``, which either knows how to deal with us and produces a result,
  433. or does not and returns `NotImplemented`, raising a ``TypeError``.
  434. If instead, we replace our ``super`` call with ``getattr(ufunc, method)``, we
  435. effectively do ``np.add(a.view(np.ndarray), b)``. Again, ``B.__array_ufunc__``
  436. will be called, but now it sees an ``ndarray`` as the other argument. Likely,
  437. it will know how to handle this, and return a new instance of the ``B`` class
  438. to us. Our example class is not set up to handle this, but it might well be
  439. the best approach if, e.g., one were to re-implement ``MaskedArray`` using
  440. ``__array_ufunc__``.
  441. As a final note: if the ``super`` route is suited to a given class, an
  442. advantage of using it is that it helps in constructing class hierarchies.
  443. E.g., suppose that our other class ``B`` also used the ``super`` in its
  444. ``__array_ufunc__`` implementation, and we created a class ``C`` that depended
  445. on both, i.e., ``class C(A, B)`` (with, for simplicity, not another
  446. ``__array_ufunc__`` override). Then any ufunc on an instance of ``C`` would
  447. pass on to ``A.__array_ufunc__``, the ``super`` call in ``A`` would go to
  448. ``B.__array_ufunc__``, and the ``super`` call in ``B`` would go to
  449. ``ndarray.__array_ufunc__``, thus allowing ``A`` and ``B`` to collaborate.
  450. .. _array-wrap:
  451. ``__array_wrap__`` for ufuncs and other functions
  452. -------------------------------------------------
  453. Prior to numpy 1.13, the behaviour of ufuncs could only be tuned using
  454. ``__array_wrap__`` and ``__array_prepare__``. These two allowed one to
  455. change the output type of a ufunc, but, in contrast to
  456. ``__array_ufunc__``, did not allow one to make any changes to the inputs.
  457. It is hoped to eventually deprecate these, but ``__array_wrap__`` is also
  458. used by other numpy functions and methods, such as ``squeeze``, so at the
  459. present time is still needed for full functionality.
  460. Conceptually, ``__array_wrap__`` "wraps up the action" in the sense of
  461. allowing a subclass to set the type of the return value and update
  462. attributes and metadata. Let's show how this works with an example. First
  463. we return to the simpler example subclass, but with a different name and
  464. some print statements:
  465. .. testcode::
  466. import numpy as np
  467. class MySubClass(np.ndarray):
  468. def __new__(cls, input_array, info=None):
  469. obj = np.asarray(input_array).view(cls)
  470. obj.info = info
  471. return obj
  472. def __array_finalize__(self, obj):
  473. print('In __array_finalize__:')
  474. print(' self is %s' % repr(self))
  475. print(' obj is %s' % repr(obj))
  476. if obj is None: return
  477. self.info = getattr(obj, 'info', None)
  478. def __array_wrap__(self, out_arr, context=None):
  479. print('In __array_wrap__:')
  480. print(' self is %s' % repr(self))
  481. print(' arr is %s' % repr(out_arr))
  482. # then just call the parent
  483. return super(MySubClass, self).__array_wrap__(self, out_arr, context)
  484. We run a ufunc on an instance of our new array:
  485. >>> obj = MySubClass(np.arange(5), info='spam')
  486. In __array_finalize__:
  487. self is MySubClass([0, 1, 2, 3, 4])
  488. obj is array([0, 1, 2, 3, 4])
  489. >>> arr2 = np.arange(5)+1
  490. >>> ret = np.add(arr2, obj)
  491. In __array_wrap__:
  492. self is MySubClass([0, 1, 2, 3, 4])
  493. arr is array([1, 3, 5, 7, 9])
  494. In __array_finalize__:
  495. self is MySubClass([1, 3, 5, 7, 9])
  496. obj is MySubClass([0, 1, 2, 3, 4])
  497. >>> ret
  498. MySubClass([1, 3, 5, 7, 9])
  499. >>> ret.info
  500. 'spam'
  501. Note that the ufunc (``np.add``) has called the ``__array_wrap__`` method
  502. with arguments ``self`` as ``obj``, and ``out_arr`` as the (ndarray) result
  503. of the addition. In turn, the default ``__array_wrap__``
  504. (``ndarray.__array_wrap__``) has cast the result to class ``MySubClass``,
  505. and called ``__array_finalize__`` - hence the copying of the ``info``
  506. attribute. This has all happened at the C level.
  507. But, we could do anything we wanted:
  508. .. testcode::
  509. class SillySubClass(np.ndarray):
  510. def __array_wrap__(self, arr, context=None):
  511. return 'I lost your data'
  512. >>> arr1 = np.arange(5)
  513. >>> obj = arr1.view(SillySubClass)
  514. >>> arr2 = np.arange(5)
  515. >>> ret = np.multiply(obj, arr2)
  516. >>> ret
  517. 'I lost your data'
  518. So, by defining a specific ``__array_wrap__`` method for our subclass,
  519. we can tweak the output from ufuncs. The ``__array_wrap__`` method
  520. requires ``self``, then an argument - which is the result of the ufunc -
  521. and an optional parameter *context*. This parameter is returned by
  522. ufuncs as a 3-element tuple: (name of the ufunc, arguments of the ufunc,
  523. domain of the ufunc), but is not set by other numpy functions. Though,
  524. as seen above, it is possible to do otherwise, ``__array_wrap__`` should
  525. return an instance of its containing class. See the masked array
  526. subclass for an implementation.
  527. In addition to ``__array_wrap__``, which is called on the way out of the
  528. ufunc, there is also an ``__array_prepare__`` method which is called on
  529. the way into the ufunc, after the output arrays are created but before any
  530. computation has been performed. The default implementation does nothing
  531. but pass through the array. ``__array_prepare__`` should not attempt to
  532. access the array data or resize the array, it is intended for setting the
  533. output array type, updating attributes and metadata, and performing any
  534. checks based on the input that may be desired before computation begins.
  535. Like ``__array_wrap__``, ``__array_prepare__`` must return an ndarray or
  536. subclass thereof or raise an error.
  537. Extra gotchas - custom ``__del__`` methods and ndarray.base
  538. -----------------------------------------------------------
  539. One of the problems that ndarray solves is keeping track of memory
  540. ownership of ndarrays and their views. Consider the case where we have
  541. created an ndarray, ``arr`` and have taken a slice with ``v = arr[1:]``.
  542. The two objects are looking at the same memory. NumPy keeps track of
  543. where the data came from for a particular array or view, with the
  544. ``base`` attribute:
  545. >>> # A normal ndarray, that owns its own data
  546. >>> arr = np.zeros((4,))
  547. >>> # In this case, base is None
  548. >>> arr.base is None
  549. True
  550. >>> # We take a view
  551. >>> v1 = arr[1:]
  552. >>> # base now points to the array that it derived from
  553. >>> v1.base is arr
  554. True
  555. >>> # Take a view of a view
  556. >>> v2 = v1[1:]
  557. >>> # base points to the view it derived from
  558. >>> v2.base is v1
  559. True
  560. In general, if the array owns its own memory, as for ``arr`` in this
  561. case, then ``arr.base`` will be None - there are some exceptions to this
  562. - see the numpy book for more details.
  563. The ``base`` attribute is useful in being able to tell whether we have
  564. a view or the original array. This in turn can be useful if we need
  565. to know whether or not to do some specific cleanup when the subclassed
  566. array is deleted. For example, we may only want to do the cleanup if
  567. the original array is deleted, but not the views. For an example of
  568. how this can work, have a look at the ``memmap`` class in
  569. ``numpy.core``.
  570. Subclassing and Downstream Compatibility
  571. ----------------------------------------
  572. When sub-classing ``ndarray`` or creating duck-types that mimic the ``ndarray``
  573. interface, it is your responsibility to decide how aligned your APIs will be
  574. with those of numpy. For convenience, many numpy functions that have a corresponding
  575. ``ndarray`` method (e.g., ``sum``, ``mean``, ``take``, ``reshape``) work by checking
  576. if the first argument to a function has a method of the same name. If it exists, the
  577. method is called instead of coercing the arguments to a numpy array.
  578. For example, if you want your sub-class or duck-type to be compatible with
  579. numpy's ``sum`` function, the method signature for this object's ``sum`` method
  580. should be the following:
  581. .. testcode::
  582. def sum(self, axis=None, dtype=None, out=None, keepdims=False):
  583. ...
  584. This is the exact same method signature for ``np.sum``, so now if a user calls
  585. ``np.sum`` on this object, numpy will call the object's own ``sum`` method and
  586. pass in these arguments enumerated above in the signature, and no errors will
  587. be raised because the signatures are completely compatible with each other.
  588. If, however, you decide to deviate from this signature and do something like this:
  589. .. testcode::
  590. def sum(self, axis=None, dtype=None):
  591. ...
  592. This object is no longer compatible with ``np.sum`` because if you call ``np.sum``,
  593. it will pass in unexpected arguments ``out`` and ``keepdims``, causing a TypeError
  594. to be raised.
  595. If you wish to maintain compatibility with numpy and its subsequent versions (which
  596. might add new keyword arguments) but do not want to surface all of numpy's arguments,
  597. your function's signature should accept ``**kwargs``. For example:
  598. .. testcode::
  599. def sum(self, axis=None, dtype=None, **unused_kwargs):
  600. ...
  601. This object is now compatible with ``np.sum`` again because any extraneous arguments
  602. (i.e. keywords that are not ``axis`` or ``dtype``) will be hidden away in the
  603. ``**unused_kwargs`` parameter.
  604. """