-
Notifications
You must be signed in to change notification settings - Fork 6
/
nep-0013-ufunc-overrides.html
1351 lines (1147 loc) · 121 KB
/
nep-0013-ufunc-overrides.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en" data-content_root="./" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>NEP 13 — A mechanism for overriding Ufuncs — NumPy Enhancement Proposals</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "";
</script>
<!--
this give us a css class that will be invisible only if js is disabled
-->
<noscript>
<style>
.pst-js-only { display: none !important; }
</style>
</noscript>
<!-- Loaded before other Sphinx assets -->
<link href="_static/styles/theme.css?digest=26a4bc78f4c0ddb94549" rel="stylesheet" />
<link href="_static/styles/pydata-sphinx-theme.css?digest=26a4bc78f4c0ddb94549" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=fa44fd50" />
<!-- So that users can add custom icons -->
<script src="_static/scripts/fontawesome.js?digest=26a4bc78f4c0ddb94549"></script>
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="_static/scripts/bootstrap.js?digest=26a4bc78f4c0ddb94549" />
<link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=26a4bc78f4c0ddb94549" />
<script src="_static/documentation_options.js?v=7f41d439"></script>
<script src="_static/doctools.js?v=888ff710"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script>DOCUMENTATION_OPTIONS.pagename = 'nep-0013-ufunc-overrides';</script>
<link rel="icon" href="_static/favicon.ico"/>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="NEP 14 — Plan for dropping Python 2.7 support" href="nep-0014-dropping-python2.7-proposal.html" />
<link rel="prev" title="NEP 10 — Optimizing iterator/UFunc performance" href="nep-0010-new-iterator-ufunc.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
<meta name="docsearch:version" content="" />
<meta name="docbuild:last-update" content="Nov 29, 2024"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="">
<div id="pst-skip-link" class="skip-link d-print-none"><a href="#main-content">Skip to main content</a></div>
<div id="pst-scroll-pixel-helper"></div>
<button type="button" class="btn rounded-pill" id="pst-back-to-top">
<i class="fa-solid fa-arrow-up"></i>Back to top</button>
<dialog id="pst-search-dialog">
<form class="bd-search d-flex align-items-center"
action="search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
placeholder="Search the docs ..."
aria-label="Search the docs ..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form>
</dialog>
<div class="pst-async-banner-revealer d-none">
<aside id="bd-header-version-warning" class="d-none d-print-none" aria-label="Version warning"></aside>
</div>
<header class="bd-header navbar navbar-expand-lg bd-navbar d-print-none">
<div class="bd-header__inner bd-page-width">
<button class="pst-navbar-icon sidebar-toggle primary-toggle" aria-label="Site navigation">
<span class="fa-solid fa-bars"></span>
</button>
<div class="col-lg-3 navbar-header-items__start">
<div class="navbar-item">
<a class="navbar-brand logo" href="content.html">
<img src="_static/numpylogo.svg" class="logo__image only-light" alt="NumPy Enhancement Proposals - Home"/>
<img src="_static/numpylogo.svg" class="logo__image only-dark pst-js-only" alt="NumPy Enhancement Proposals - Home"/>
</a></div>
</div>
<div class="col-lg-9 navbar-header-items">
<div class="me-auto navbar-header-items__center">
<div class="navbar-item">
<nav>
<ul class="bd-navbar-elements navbar-nav">
<li class="nav-item current active">
<a class="nav-link nav-internal" href="index.html">
Index
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-internal" href="scope.html">
The Scope of NumPy
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-internal" href="roadmap.html">
Current roadmap
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-external" href="https://github.com/numpy/numpy/issues?q=is%3Aopen+is%3Aissue+label%3A%2223+-+Wish+List%22">
Wish list
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-external" href="https://github.com/numpy/numpy/issues?q=is%3Aopen+is%3Aissue+label%3A%2223+-+Wish+List%22">
Wishlist
</a>
</li>
</ul>
</nav></div>
</div>
<div class="navbar-header-items__end">
<div class="navbar-item navbar-persistent--container">
<button class="btn search-button-field search-button__button pst-js-only" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
<span class="search-button__default-text">Search</span>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd class="kbd-shortcut__modifier">K</kbd></span>
</button>
</div>
<div class="navbar-item">
<button class="btn btn-sm nav-link pst-navbar-icon theme-switch-button pst-js-only" aria-label="Color mode" data-bs-title="Color mode" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="theme-switch fa-solid fa-sun fa-lg" data-mode="light" title="Light"></i>
<i class="theme-switch fa-solid fa-moon fa-lg" data-mode="dark" title="Dark"></i>
<i class="theme-switch fa-solid fa-circle-half-stroke fa-lg" data-mode="auto" title="System Settings"></i>
</button></div>
<div class="navbar-item"><ul class="navbar-icon-links"
aria-label="Icon Links">
<li class="nav-item">
<a href="https://github.com/numpy/numpy" title="GitHub" class="nav-link pst-navbar-icon" rel="noopener" target="_blank" data-bs-toggle="tooltip" data-bs-placement="bottom"><i class="fa-brands fa-square-github fa-lg" aria-hidden="true"></i>
<span class="sr-only">GitHub</span></a>
</li>
</ul></div>
</div>
</div>
<div class="navbar-persistent--mobile">
<button class="btn search-button-field search-button__button pst-js-only" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
<span class="search-button__default-text">Search</span>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd class="kbd-shortcut__modifier">K</kbd></span>
</button>
</div>
<button class="pst-navbar-icon sidebar-toggle secondary-toggle" aria-label="On this page">
<span class="fa-solid fa-outdent"></span>
</button>
</div>
</header>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<dialog id="pst-primary-sidebar-modal"></dialog>
<div id="pst-primary-sidebar" class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
<div class="sidebar-header-items__center">
<div class="navbar-item">
<nav>
<ul class="bd-navbar-elements navbar-nav">
<li class="nav-item current active">
<a class="nav-link nav-internal" href="index.html">
Index
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-internal" href="scope.html">
The Scope of NumPy
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-internal" href="roadmap.html">
Current roadmap
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-external" href="https://github.com/numpy/numpy/issues?q=is%3Aopen+is%3Aissue+label%3A%2223+-+Wish+List%22">
Wish list
</a>
</li>
<li class="nav-item ">
<a class="nav-link nav-external" href="https://github.com/numpy/numpy/issues?q=is%3Aopen+is%3Aissue+label%3A%2223+-+Wish+List%22">
Wishlist
</a>
</li>
</ul>
</nav></div>
</div>
<div class="sidebar-header-items__end">
<div class="navbar-item">
<button class="btn btn-sm nav-link pst-navbar-icon theme-switch-button pst-js-only" aria-label="Color mode" data-bs-title="Color mode" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="theme-switch fa-solid fa-sun fa-lg" data-mode="light" title="Light"></i>
<i class="theme-switch fa-solid fa-moon fa-lg" data-mode="dark" title="Dark"></i>
<i class="theme-switch fa-solid fa-circle-half-stroke fa-lg" data-mode="auto" title="System Settings"></i>
</button></div>
<div class="navbar-item"><ul class="navbar-icon-links"
aria-label="Icon Links">
<li class="nav-item">
<a href="https://github.com/numpy/numpy" title="GitHub" class="nav-link pst-navbar-icon" rel="noopener" target="_blank" data-bs-toggle="tooltip" data-bs-placement="bottom"><i class="fa-brands fa-square-github fa-lg" aria-hidden="true"></i>
<span class="sr-only">GitHub</span></a>
</li>
</ul></div>
</div>
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<nav class="bd-docs-nav bd-links"
aria-label="Section Navigation">
<p class="bd-links__title" role="heading" aria-level="1">Section Navigation</p>
<div class="bd-toc-item navbar-nav"><ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="scope.html">The Scope of NumPy</a></li>
<li class="toctree-l1"><a class="reference internal" href="roadmap.html">Current roadmap</a></li>
<li class="toctree-l1"><a class="reference external" href="https://github.com/numpy/numpy/issues?q=is%3Aopen+is%3Aissue+label%3A%2223+-+Wish+List%22">Wish list</a></li>
</ul>
<ul class="current nav bd-sidenav">
<li class="toctree-l1 has-children"><a class="reference internal" href="meta.html">Meta-NEPs (NEPs about NEPs or active Processes)</a><details><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul>
<li class="toctree-l2"><a class="reference internal" href="nep-0000.html">NEP 0 — Purpose and process</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0023-backwards-compatibility.html">NEP 23 — Backwards compatibility and deprecation policy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0036-fair-play.html">NEP 36 — Fair play</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0045-c_style_guide.html">NEP 45 — C style guide</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0046-sponsorship-guidelines.html">NEP 46 — NumPy sponsorship guidelines</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0048-spending-project-funds.html">NEP 48 — Spending NumPy project funds</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-template.html">NEP X — Template and instructions</a></li>
</ul>
</details></li>
<li class="toctree-l1 has-children"><a class="reference internal" href="provisional.html">Provisional NEPs (provisionally accepted; interface may change)</a><details><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul class="simple">
</ul>
</details></li>
<li class="toctree-l1 has-children"><a class="reference internal" href="accepted.html">Accepted NEPs (implementation in progress)</a><details><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul>
<li class="toctree-l2"><a class="reference internal" href="nep-0041-improved-dtype-support.html">NEP 41 — First step towards a new datatype system</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0042-new-dtypes.html">NEP 42 — New and extensible DTypes</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0044-restructuring-numpy-docs.html">NEP 44 — Restructuring the NumPy documentation</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0051-scalar-representation.html">NEP 51 — Changing the representation of NumPy scalars</a></li>
</ul>
</details></li>
<li class="toctree-l1 has-children"><a class="reference internal" href="open.html">Open NEPs (under consideration)</a><details><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul>
<li class="toctree-l2"><a class="reference internal" href="nep-0043-extensible-ufuncs.html">NEP 43 — Enhancing the extensibility of UFuncs</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0053-c-abi-evolution.html">NEP 53 — Evolving the NumPy C-API for NumPy 2.0</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0054-simd-cpp-highway.html">NEP 54 — SIMD infrastructure evolution: adopting Google Highway when moving to C++?</a></li>
</ul>
</details></li>
<li class="toctree-l1 current active has-children"><a class="reference internal" href="finished.html">Finished NEPs</a><details open="open"><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="nep-0001-npy-format.html">NEP 1 — A simple file format for NumPy arrays</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0005-generalized-ufuncs.html">NEP 5 — Generalized universal functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0007-datetime-proposal.html">NEP 7 — A proposal for implementing some date/time types in NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0010-new-iterator-ufunc.html">NEP 10 — Optimizing iterator/UFunc performance</a></li>
<li class="toctree-l2 current active"><a class="current reference internal" href="#">NEP 13 — A mechanism for overriding Ufuncs</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0014-dropping-python2.7-proposal.html">NEP 14 — Plan for dropping Python 2.7 support</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0015-merge-multiarray-umath.html">NEP 15 — Merging multiarray and umath</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0018-array-function-protocol.html">NEP 18 — A dispatch mechanism for NumPy's high level array functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0019-rng-policy.html">NEP 19 — Random number generator policy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0020-gufunc-signature-enhancement.html">NEP 20 — Expansion of generalized universal function signatures</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0022-ndarray-duck-typing-overview.html">NEP 22 — Duck typing for NumPy arrays – high level overview</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0027-zero-rank-arrarys.html">NEP 27 — Zero rank arrays</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0028-website-redesign.html">NEP 28 — numpy.org website redesign</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0029-deprecation_policy.html">NEP 29 — Recommend Python and NumPy version support as a community policy standard</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0032-remove-financial-functions.html">NEP 32 — Remove the financial functions from NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0034-infer-dtype-is-object.html">NEP 34 — Disallow inferring ``dtype=object`` from sequences</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0035-array-creation-dispatch-with-array-function.html">NEP 35 — Array creation dispatching with __array_function__</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0038-SIMD-optimizations.html">NEP 38 — Using SIMD optimization instructions for performance</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0040-legacy-datatype-impl.html">NEP 40 — Legacy datatype implementation in NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0049.html">NEP 49 — Data allocation strategies</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0050-scalar-promotion.html">NEP 50 — Promotion rules for Python scalars</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0052-python-api-cleanup.html">NEP 52 — Python API cleanup for NumPy 2.0</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0055-string_dtype.html">NEP 55 — Add a UTF-8 variable-width string DType to NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0056-array-api-main-namespace.html">NEP 56 — Array API standard support in NumPy's main namespace</a></li>
</ul>
</details></li>
<li class="toctree-l1 has-children"><a class="reference internal" href="deferred.html">Deferred and Superseded NEPs</a><details><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul>
<li class="toctree-l2"><a class="reference internal" href="nep-0002-warnfix.html">NEP 2 — A proposal to build numpy without warning with a big set of warning flags</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0003-math_config_clean.html">NEP 3 — Cleaning the math configuration of numpy.core</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0004-datetime-proposal3.html">NEP 4 — A (third) proposal for implementing some date/time types in NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0006-newbugtracker.html">NEP 6 — Replacing Trac with a different bug tracker</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0008-groupby_additions.html">NEP 8 — A proposal for adding groupby functionality to NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0009-structured_array_extensions.html">NEP 9 — Structured array extensions</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0011-deferred-ufunc-evaluation.html">NEP 11 — Deferred UFunc evaluation</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0012-missing-data.html">NEP 12 — Missing data functionality in NumPy</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0021-advanced-indexing.html">NEP 21 — Simplified and explicit advanced indexing</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0024-missing-data-2.html">NEP 24 — Missing data functionality - alternative 1 to NEP 12</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0025-missing-data-3.html">NEP 25 — NA support via special dtypes</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0026-missing-data-summary.html">NEP 26 — Summary of missing data NEPs and discussion</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0030-duck-array-protocol.html">NEP 30 — Duck typing for NumPy arrays - implementation</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0031-uarray.html">NEP 31 — Context-local and global overrides of the NumPy API</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0037-array-module.html">NEP 37 — A dispatch protocol for NumPy-like modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0047-array-api-standard.html">NEP 47 — Adopting the array API standard</a></li>
</ul>
</details></li>
<li class="toctree-l1 has-children"><a class="reference internal" href="rejected.html">Rejected and Withdrawn NEPs</a><details><summary><span class="toctree-toggle" role="presentation"><i class="fa-solid fa-chevron-down"></i></span></summary><ul>
<li class="toctree-l2"><a class="reference internal" href="nep-0016-abstract-array.html">NEP 16 — An abstract base class for identifying "duck arrays"</a></li>
<li class="toctree-l2"><a class="reference internal" href="nep-0017-split-out-maskedarray.html">NEP 17 — Split out masked arrays</a></li>
</ul>
</details></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main" role="main">
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article d-print-none">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item">
<nav aria-label="Breadcrumb" class="d-print-none">
<ul class="bd-breadcrumbs">
<li class="breadcrumb-item breadcrumb-home">
<a href="content.html" class="nav-link" aria-label="Home">
<i class="fa-solid fa-home"></i>
</a>
</li>
<li class="breadcrumb-item"><a href="index.html" class="nav-link">Roadmap & NumPy enhancement proposals</a></li>
<li class="breadcrumb-item"><a href="finished.html" class="nav-link">Finished NEPs</a></li>
<li class="breadcrumb-item active" aria-current="page"><span class="ellipsis">NEP 13 — A mechanism for overriding Ufuncs</span></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article">
<section id="nep-13-a-mechanism-for-overriding-ufuncs">
<span id="nep13"></span><h1>NEP 13 — A mechanism for overriding Ufuncs<a class="headerlink" href="#nep-13-a-mechanism-for-overriding-ufuncs" title="Link to this heading">#</a></h1>
<dl class="field-list simple">
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>Blake Griffith</p>
</dd>
<dt class="field-even">Contact<span class="colon">:</span></dt>
<dd class="field-even"><p><a class="reference external" href="mailto:blake.g%40utexas.edu">blake<span>.</span>g<span>@</span>utexas<span>.</span>edu</a></p>
</dd>
<dt class="field-odd">Date<span class="colon">:</span></dt>
<dd class="field-odd"><p>2013-07-10</p>
</dd>
<dt class="field-even">Author<span class="colon">:</span></dt>
<dd class="field-even"><p>Pauli Virtanen</p>
</dd>
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>Nathaniel Smith</p>
</dd>
<dt class="field-even">Author<span class="colon">:</span></dt>
<dd class="field-even"><p>Marten van Kerkwijk</p>
</dd>
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>Stephan Hoyer</p>
</dd>
<dt class="field-even">Date<span class="colon">:</span></dt>
<dd class="field-even"><p>2017-03-31</p>
</dd>
<dt class="field-odd">Status<span class="colon">:</span></dt>
<dd class="field-odd"><p>Final</p>
</dd>
<dt class="field-even">Updated<span class="colon">:</span></dt>
<dd class="field-even"><p>2023-02-19</p>
</dd>
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>Roy Smart</p>
</dd>
</dl>
<section id="executive-summary">
<h2>Executive summary<a class="headerlink" href="#executive-summary" title="Link to this heading">#</a></h2>
<p>NumPy’s universal functions (ufuncs) currently have some limited
functionality for operating on user defined subclasses of
<a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> using <code class="docutils literal notranslate"><span class="pre">__array_prepare__</span></code> and <code class="docutils literal notranslate"><span class="pre">__array_wrap__</span></code>
<a class="footnote-reference brackets" href="#id5" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>, and there is little to no support for arbitrary
objects. e.g. SciPy’s sparse matrices <a class="footnote-reference brackets" href="#id6" id="id2" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a> <a class="footnote-reference brackets" href="#id7" id="id3" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a>.</p>
<p>Here we propose adding a mechanism to override ufuncs based on the ufunc
checking each of it’s arguments for a <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method.
On discovery of <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> the ufunc will hand off the
operation to the method.</p>
<p>This covers some of the same ground as Travis Oliphant’s proposal to
retro-fit NumPy with multi-methods <a class="footnote-reference brackets" href="#id8" id="id4" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a>, which would solve the same
problem. The mechanism here follows more closely the way Python enables
classes to override <code class="docutils literal notranslate"><span class="pre">__mul__</span></code> and other binary operations. It also
specifically addresses how binary operators and ufuncs should interact.
(Note that in earlier iterations, the override was called
<code class="docutils literal notranslate"><span class="pre">__numpy_ufunc__</span></code>. An implementation was made, but had not quite the
right behaviour, hence the change in name.)</p>
<p>The <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> as described below requires that any
corresponding Python binary operations (<code class="docutils literal notranslate"><span class="pre">__mul__</span></code> et al.) should be
implemented in a specific way and be compatible with NumPy’s ndarray
semantics. Objects that do not satisfy this cannot override any NumPy
ufuncs. We do not specify a future-compatible path by which this
requirement can be relaxed — any changes here require corresponding
changes in 3rd party code.</p>
<aside class="footnote-list brackets">
<aside class="footnote brackets" id="id5" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
<p><a class="reference external" href="http://docs.python.org/doc/numpy/user/basics.subclassing.html">http://docs.python.org/doc/numpy/user/basics.subclassing.html</a></p>
</aside>
<aside class="footnote brackets" id="id6" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id2">2</a><span class="fn-bracket">]</span></span>
<p><a class="github reference external" href="https://github.com/scipy/scipy/issues/2123">scipy/scipy#2123</a></p>
</aside>
<aside class="footnote brackets" id="id7" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id3">3</a><span class="fn-bracket">]</span></span>
<p><a class="github reference external" href="https://github.com/scipy/scipy/issues/1569">scipy/scipy#1569</a></p>
</aside>
<aside class="footnote brackets" id="id8" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id4">4</a><span class="fn-bracket">]</span></span>
<p><a class="reference external" href="https://technicaldiscovery.blogspot.com/2013/07/thoughts-after-scipy-2013-and-specific.html">https://technicaldiscovery.blogspot.com/2013/07/thoughts-after-scipy-2013-and-specific.html</a></p>
</aside>
</aside>
</section>
<section id="motivation">
<h2>Motivation<a class="headerlink" href="#motivation" title="Link to this heading">#</a></h2>
<p>The current machinery for dispatching Ufuncs is generally agreed to be
insufficient. There have been lengthy discussions and other proposed
solutions <a class="footnote-reference brackets" href="#id11" id="id9" role="doc-noteref"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></a>, <a class="footnote-reference brackets" href="#id12" id="id10" role="doc-noteref"><span class="fn-bracket">[</span>6<span class="fn-bracket">]</span></a>.</p>
<p>Using ufuncs with subclasses of <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> is limited to
<code class="docutils literal notranslate"><span class="pre">__array_prepare__</span></code> and <code class="docutils literal notranslate"><span class="pre">__array_wrap__</span></code> to prepare the output arguments,
but these don’t allow you to for example change the shape or the data of
the arguments. Trying to ufunc things that don’t subclass
<a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> is even more difficult, as the input arguments tend to
be cast to object arrays, which ends up producing surprising results.</p>
<p>Take this example of ufuncs interoperability with sparse matrices.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">In</span> <span class="p">[</span><span class="mi">1</span><span class="p">]:</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">scipy.sparse</span> <span class="k">as</span> <span class="nn">sp</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">))</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">))</span>
<span class="n">asp</span> <span class="o">=</span> <span class="n">sp</span><span class="o">.</span><span class="n">csr_matrix</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="n">bsp</span> <span class="o">=</span> <span class="n">sp</span><span class="o">.</span><span class="n">csr_matrix</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="n">In</span> <span class="p">[</span><span class="mi">2</span><span class="p">]:</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">2</span><span class="p">]:(</span><span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">]]),</span>
<span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span>
<span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span>
<span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]]))</span>
<span class="n">In</span> <span class="p">[</span><span class="mi">3</span><span class="p">]:</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span> <span class="c1"># The right answer</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">3</span><span class="p">]:</span> <span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span>
<span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span>
<span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]])</span>
<span class="n">In</span> <span class="p">[</span><span class="mi">4</span><span class="p">]:</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">asp</span><span class="p">,</span> <span class="n">bsp</span><span class="p">)</span><span class="o">.</span><span class="n">todense</span><span class="p">()</span> <span class="c1"># calls __mul__ which does matrix multi</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">4</span><span class="p">]:</span> <span class="n">matrix</span><span class="p">([[</span><span class="mi">16</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">8</span><span class="p">],</span>
<span class="p">[</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span>
<span class="p">[</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">]],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">int64</span><span class="p">)</span>
<span class="n">In</span> <span class="p">[</span><span class="mi">5</span><span class="p">]:</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">bsp</span><span class="p">)</span> <span class="c1"># Returns NotImplemented to user, bad!</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">5</span><span class="p">]:</span> <span class="bp">NotImplemented</span>
</pre></div>
</div>
<p>Returning <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> to user should not happen. Moreover:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">In</span> <span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">asp</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="n">array</span><span class="p">([[</span> <span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">],</span>
<span class="p">[</span> <span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">],</span>
<span class="p">[</span> <span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">,</span>
<span class="o"><</span><span class="mi">3</span><span class="n">x3</span> <span class="n">sparse</span> <span class="n">matrix</span> <span class="n">of</span> <span class="nb">type</span> <span class="s1">'<class '</span><span class="n">numpy</span><span class="o">.</span><span class="n">int64</span><span class="s1">'>'</span>
<span class="k">with</span> <span class="mi">8</span> <span class="n">stored</span> <span class="n">elements</span> <span class="ow">in</span> <span class="n">Compressed</span> <span class="n">Sparse</span> <span class="n">Row</span> <span class="nb">format</span><span class="o">></span><span class="p">]],</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">object</span><span class="p">)</span>
</pre></div>
</div>
<p>Here, it appears that the sparse matrix was converted to an object array
scalar, which was then multiplied with all elements of the <code class="docutils literal notranslate"><span class="pre">b</span></code> array.
However, this behavior is more confusing than useful, and having a
<a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> would be preferable.</p>
<p>This proposal will <em>not</em> resolve the issue with scipy.sparse matrices,
which have multiplication semantics incompatible with NumPy arrays.
However, the aim is to enable writing other custom array types that have
strictly ndarray compatible semantics.</p>
<aside class="footnote-list brackets">
<aside class="footnote brackets" id="id11" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id9">5</a><span class="fn-bracket">]</span></span>
<p><a class="reference external" href="https://mail.python.org/pipermail/numpy-discussion/2011-June/056945.html">https://mail.python.org/pipermail/numpy-discussion/2011-June/056945.html</a></p>
</aside>
<aside class="footnote brackets" id="id12" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span>6<span class="fn-bracket">]</span></span>
<span class="backrefs">(<a role="doc-backlink" href="#id10">1</a>,<a role="doc-backlink" href="#id18">2</a>)</span>
<p><a class="github reference external" href="https://github.com/numpy/numpy/issues/5844">numpy/numpy#5844</a></p>
</aside>
</aside>
</section>
<section id="proposed-interface">
<h2>Proposed interface<a class="headerlink" href="#proposed-interface" title="Link to this heading">#</a></h2>
<p>The standard array class <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> gains an <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>
method and objects can override Ufuncs by overriding this method (if
they are <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> subclasses) or defining their own. The method
signature is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__array_ufunc__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ufunc</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="o">*</span><span class="n">inputs</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>Here:</p>
<ul class="simple">
<li><p><em>ufunc</em> is the ufunc object that was called.</p></li>
<li><p><em>method</em> is a string indicating how the Ufunc was called, either
<code class="docutils literal notranslate"><span class="pre">"__call__"</span></code> to indicate it was called directly, or one of its
methods: <code class="docutils literal notranslate"><span class="pre">"reduce"</span></code>, <code class="docutils literal notranslate"><span class="pre">"accumulate"</span></code>, <code class="docutils literal notranslate"><span class="pre">"reduceat"</span></code>, <code class="docutils literal notranslate"><span class="pre">"outer"</span></code>,
or <code class="docutils literal notranslate"><span class="pre">"at"</span></code>.</p></li>
<li><p><em>inputs</em> is a tuple of the input arguments to the <code class="docutils literal notranslate"><span class="pre">ufunc</span></code></p></li>
<li><p><em>kwargs</em> contains any optional or keyword arguments passed to the
function. This includes any <code class="docutils literal notranslate"><span class="pre">out</span></code> arguments, which are always
contained in a tuple.</p></li>
</ul>
<p>Hence, the arguments are normalized: only the required input arguments
(<code class="docutils literal notranslate"><span class="pre">inputs</span></code>) are passed on as positional arguments, all the others are
passed on as a dict of keyword arguments (<code class="docutils literal notranslate"><span class="pre">kwargs</span></code>). In particular, if
there are output arguments, positional are otherwise, that are not
<a class="reference external" href="https://docs.python.org/dev/library/constants.html#None" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">None</span></code></a>, they are passed on as a tuple in the <code class="docutils literal notranslate"><span class="pre">out</span></code> keyword
argument (even for the <code class="docutils literal notranslate"><span class="pre">reduce</span></code>, <code class="docutils literal notranslate"><span class="pre">accumulate</span></code>, and <code class="docutils literal notranslate"><span class="pre">reduceat</span></code> methods
where in all current cases only a single output makes sense).</p>
<p>The function dispatch proceeds as follows:</p>
<ul class="simple">
<li><p>If one of the input, output, or <code class="docutils literal notranslate"><span class="pre">where</span></code> arguments implements
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>, it is executed instead of the ufunc.</p></li>
<li><p>If more than one of the arguments implements <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>,
they are tried in the following order: subclasses before superclasses,
inputs before outputs, outputs before <code class="docutils literal notranslate"><span class="pre">where</span></code>, otherwise left to right.</p></li>
<li><p>The first <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method returning something else than
<a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> determines the return value of the Ufunc.</p></li>
<li><p>If all <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> methods of the input arguments return
<a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>, a <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p></li>
<li><p>If a <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method raises an error, the error is
propagated immediately.</p></li>
<li><p>If none of the input arguments had an <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method, the
execution falls back on the default ufunc behaviour.</p></li>
</ul>
<p>In the above, there is one proviso: if a class has an
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> attribute but it is identical to
<code class="docutils literal notranslate"><span class="pre">ndarray.__array_ufunc__</span></code>, the attribute is ignored. This happens for
instances of <cite>ndarray</cite> and for <cite>ndarray</cite> subclasses that did not
override their inherited <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> implementation.</p>
<section id="type-casting-hierarchy">
<h3>Type casting hierarchy<a class="headerlink" href="#type-casting-hierarchy" title="Link to this heading">#</a></h3>
<p>The Python operator override mechanism gives much freedom in how to
write the override methods, and it requires some discipline in order to
achieve predictable results. Here, we discuss an approach for
understanding some of the implications, which can provide input in the
design.</p>
<p>It is useful to maintain a clear idea of what types can be “upcast” to
others, possibly indirectly (e.g. indirect A->B->C is implemented but
direct A->C not). If the implementations of <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> follow a
coherent type casting hierarchy, it can be used to understand results of
operations.</p>
<p>Type casting can be expressed as a <a class="reference external" href="https://en.wikipedia.org/wiki/Graph_theory">graph</a>
defined as follows:</p>
<blockquote>
<div><p>For each <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method, draw directed edges from each
possible input type to each possible output type.</p>
<p>That is, in each case where <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">x.__array_ufunc__(a,</span> <span class="pre">b,</span> <span class="pre">c,</span> <span class="pre">...)</span></code>
does something else than returning <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> or raising an error,
draw edges <code class="docutils literal notranslate"><span class="pre">type(a)</span> <span class="pre">-></span> <span class="pre">type(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">type(b)</span> <span class="pre">-></span> <span class="pre">type(y)</span></code>, …</p>
</div></blockquote>
<p>If the resulting graph is <em>acyclic</em>, it defines a coherent type casting
hierarchy (unambiguous partial ordering between types). In this case,
operations involving multiple types generally predictably produce result
of the “highest” type, or raise a <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>. See examples at the
end of this section.</p>
<p>If the graph has cycles, the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> type casting is not
well-defined, and things such as <code class="docutils literal notranslate"><span class="pre">type(multiply(a,</span> <span class="pre">b))</span> <span class="pre">!=</span>
<span class="pre">type(multiply(b,</span> <span class="pre">a))</span></code> or <code class="docutils literal notranslate"><span class="pre">type(add(a,</span> <span class="pre">add(b,</span> <span class="pre">c)))</span> <span class="pre">!=</span> <span class="pre">type(add(add(a,</span>
<span class="pre">b),</span> <span class="pre">c))</span></code> are not excluded (and then probably always possible).</p>
<p>If the type casting hierarchy is well defined, for each class A, all
other classes that define <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> belong to exactly one of
three groups:</p>
<ul class="simple">
<li><p><em>Above A</em>: the types that A can be (indirectly) upcast to in ufuncs.</p></li>
<li><p><em>Below A</em>: the types that can be (indirectly) upcast to A in ufuncs.</p></li>
<li><p><em>Incompatible</em>: neither above nor below A; types for which no
(indirect) upcasting is possible.</p></li>
</ul>
<p>Note that the legacy behaviour of NumPy ufuncs is to try to convert
unknown objects to <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> via <code class="xref py py-func docutils literal notranslate"><span class="pre">np.asarray()</span></code>. This is
equivalent to placing <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> above these objects in the graph.
Since we above defined <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> to return <cite>NotImplemented</cite> for
classes with custom <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>, this puts <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>
below such classes in the type hierarchy, allowing the operations to be
overridden.</p>
<p>In view of the above, binary ufuncs describing transitive operations
should aim to define a well-defined casting hierarchy. This is likely
also a sensible approach to all ufuncs — exceptions to this should
consider carefully if any surprising behavior results.</p>
<div class="admonition-example admonition">
<p class="admonition-title">Example</p>
<p>Type casting hierarchy.</p>
<img alt="_images/nep0013_image1.png" src="_images/nep0013_image1.png" />
<p>The <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> of type A can handle ndarrays returning C,
B can handle ndarray and D returning B, and C can handle A and B returning C,
but not ndarrays or D. The
result is a directed acyclic graph, and defines a type casting
hierarchy, with relations <code class="docutils literal notranslate"><span class="pre">C</span> <span class="pre">></span> <span class="pre">A</span></code>, <code class="docutils literal notranslate"><span class="pre">C</span> <span class="pre">></span> <span class="pre">ndarray</span></code>, <code class="docutils literal notranslate"><span class="pre">C</span> <span class="pre">></span> <span class="pre">B</span> <span class="pre">></span> <span class="pre">ndarray</span></code>,
<code class="docutils literal notranslate"><span class="pre">C</span> <span class="pre">></span> <span class="pre">B</span> <span class="pre">></span> <span class="pre">D</span></code>. The type A is incompatible with B, D, ndarray,
and D is incompatible with A and ndarray. Ufunc
expressions involving these classes should produce results of the
highest type involved or raise a <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</div>
<div class="admonition-example admonition">
<p class="admonition-title">Example</p>
<p>One-cycle in the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> graph.</p>
<img alt="_images/nep0013_image2.png" src="_images/nep0013_image2.png" />
<p>In this case, the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> relations have a cycle of length 1,
and a type casting hierarchy does not exist. Binary operations are not
commutative: <code class="docutils literal notranslate"><span class="pre">type(a</span> <span class="pre">+</span> <span class="pre">b)</span> <span class="pre">is</span> <span class="pre">A</span></code> but <code class="docutils literal notranslate"><span class="pre">type(b</span> <span class="pre">+</span> <span class="pre">a)</span> <span class="pre">is</span> <span class="pre">B</span></code>.</p>
</div>
<div class="admonition-example admonition">
<p class="admonition-title">Example</p>
<p>Longer cycle in the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> graph.</p>
<img alt="_images/nep0013_image3.png" src="_images/nep0013_image3.png" />
<p>In this case, the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> relations have a longer cycle, and a
type casting hierarchy does not exist. Binary operations are still
commutative, but type transitivity is lost: <code class="docutils literal notranslate"><span class="pre">type(a</span> <span class="pre">+</span> <span class="pre">(b</span> <span class="pre">+</span> <span class="pre">c))</span> <span class="pre">is</span> <span class="pre">A</span></code> but
<code class="docutils literal notranslate"><span class="pre">type((a</span> <span class="pre">+</span> <span class="pre">b)</span> <span class="pre">+</span> <span class="pre">c)</span> <span class="pre">is</span> <span class="pre">C</span></code>.</p>
</div>
</section>
<section id="subclass-hierarchies">
<h3>Subclass hierarchies<a class="headerlink" href="#subclass-hierarchies" title="Link to this heading">#</a></h3>
<p>Generally, it is desirable to mirror the class hierarchy in the ufunc
type casting hierarchy. The recommendation is that an
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> implementation of a class should generally return
<cite>NotImplemented</cite> unless the inputs are instances of the same class or
superclasses. This guarantees that in the type casting hierarchy,
superclasses are below, subclasses above, and other classes are
incompatible. Exceptions to this need to check they respect the
implicit type casting hierarchy.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Note that type casting hierarchy and class hierarchy are here defined
to go the “opposite” directions. It would in principle also be
consistent to have <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> handle also instances of
subclasses. In this case, the “subclasses first” dispatch rule would
ensure a relatively similar outcome. However, the behavior is then less
explicitly specified.</p>
</div>
<p>Subclasses can be easily constructed if methods consistently use
<code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code> to pass through the class hierarchy <a class="footnote-reference brackets" href="#id14" id="id13" role="doc-noteref"><span class="fn-bracket">[</span>7<span class="fn-bracket">]</span></a>. To support
this, <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> has its own <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> method,
equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__array_ufunc__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ufunc</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="o">*</span><span class="n">inputs</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="c1"># Cannot handle items that have __array_ufunc__ (other than our own).</span>
<span class="n">outputs</span> <span class="o">=</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'out'</span><span class="p">,</span> <span class="p">())</span>
<span class="n">objs</span> <span class="o">=</span> <span class="n">inputs</span> <span class="o">+</span> <span class="n">outputs</span>
<span class="k">if</span> <span class="s2">"where"</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="p">:</span>
<span class="n">objs</span> <span class="o">=</span> <span class="n">objs</span> <span class="o">+</span> <span class="p">(</span><span class="n">kwargs</span><span class="p">[</span><span class="s2">"where"</span><span class="p">],</span> <span class="p">)</span>
<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">objs</span><span class="p">:</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">hasattr</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="s1">'__array_ufunc__'</span><span class="p">)</span> <span class="ow">and</span>
<span class="nb">type</span><span class="p">(</span><span class="n">item</span><span class="p">)</span><span class="o">.</span><span class="n">__array_ufunc__</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">ndarray</span><span class="o">.</span><span class="n">__array_ufunc__</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="c1"># If we didn't have to support legacy behaviour (__array_prepare__,</span>
<span class="c1"># __array_wrap__, etc.), we might here convert python floats,</span>
<span class="c1"># lists, etc, to arrays with</span>
<span class="c1"># items = [np.asarray(item) for item in inputs]</span>
<span class="c1"># and then start the right iterator for the given method.</span>
<span class="c1"># However, we do have to support legacy, so call back into the ufunc.</span>
<span class="c1"># Its arguments are now guaranteed not to have __array_ufunc__</span>
<span class="c1"># overrides, and it will do the coercion to array for us.</span>
<span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">ufunc</span><span class="p">,</span> <span class="n">method</span><span class="p">)(</span><span class="o">*</span><span class="n">items</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that, as a special case, the ufunc dispatch mechanism does not call
this <cite>ndarray.__array_ufunc__</cite> method, even for <cite>ndarray</cite> subclasses
if they have not overridden the default <cite>ndarray</cite> implementation. As a
consequence, calling <cite>ndarray.__array_ufunc__</cite> will not result to a
nested ufunc dispatch cycle.</p>
<p>The use of <code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code> should be particularly useful for subclasses of
<a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> that only add an attribute like a unit. In their
<cite>__array_ufunc__</cite> implementation, such classes can do possible
adjustment of the arguments relevant to their own class, and pass on to
the superclass implementation using <code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code> until the ufunc is
actually done, and then do possible adjustments of the outputs.</p>
<p>In general, custom implementations of <cite>__array_ufunc__</cite> should avoid
nested dispatch cycles, where one not just calls the ufunc via
<code class="docutils literal notranslate"><span class="pre">getattr(ufunc,</span> <span class="pre">method)(*items,</span> <span class="pre">**kwargs)</span></code>, but catches possible
exceptions, etc. As always, there may be exceptions. For instance, for a
class like <code class="xref py py-class docutils literal notranslate"><span class="pre">MaskedArray</span></code>, which only cares that whatever
it contains is an <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> subclass, a reimplementation with
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> may well be more easily done by directly applying
the ufunc to its data, and then adjusting the mask. Indeed, one can
think of this as part of the class determining whether it can handle the
other argument (i.e., where in the type hierarchy it sits). In this
case, one should return <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if the trial fails. So,
the implementation would be something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__array_ufunc__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ufunc</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="o">*</span><span class="n">inputs</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="c1"># for simplicity, outputs are ignored here.</span>
<span class="n">unmasked_items</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">((</span><span class="n">item</span><span class="o">.</span><span class="n">data</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">MaskedArray</span><span class="p">)</span>
<span class="k">else</span> <span class="n">item</span><span class="p">)</span> <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">inputs</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">unmasked_result</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">ufunc</span><span class="p">,</span> <span class="n">method</span><span class="p">)(</span><span class="o">*</span><span class="n">unmasked_items</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="c1"># for simplicity, ignore that unmasked_result could be a tuple</span>
<span class="c1"># or a scalar.</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">unmasked_result</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">ndarray</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="c1"># now combine masks and view as MaskedArray instance</span>
<span class="o">...</span>
</pre></div>
</div>
<p>As a specific example, consider a quantity and a masked array class
which both override <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>, with specific instances <code class="docutils literal notranslate"><span class="pre">q</span></code>
and <code class="docutils literal notranslate"><span class="pre">ma</span></code>, where the latter contains a regular array. Executing
<code class="docutils literal notranslate"><span class="pre">np.multiply(q,</span> <span class="pre">ma)</span></code>, the ufunc will first dispatch to
<code class="docutils literal notranslate"><span class="pre">q.__array_ufunc__</span></code>, which returns <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> (since the
quantity class turns itself into an array and calls <code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code>, which
passes on to <code class="docutils literal notranslate"><span class="pre">ndarray.__array_ufunc__</span></code>, which sees the override on
<code class="docutils literal notranslate"><span class="pre">ma</span></code>). Next, <code class="docutils literal notranslate"><span class="pre">ma.__array_ufunc__</span></code> gets a chance. It does not know
quantity, and if it were to just return <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> as well,
an <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> would result. But in our sample implementation, it
uses <code class="docutils literal notranslate"><span class="pre">getattr(ufunc,</span> <span class="pre">method)</span></code> to, effectively, evaluate
<code class="docutils literal notranslate"><span class="pre">np.multiply(q,</span> <span class="pre">ma.data)</span></code>. This again will pass to
<code class="docutils literal notranslate"><span class="pre">q.__array_ufunc__</span></code>, but this time, since <code class="docutils literal notranslate"><span class="pre">ma.data</span></code> is a regular
array, it will return a result that is also a quantity. Since this is a
subclass of <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>, <code class="docutils literal notranslate"><span class="pre">ma.__array_ufunc__</span></code> can turn this into
a masked array and thus return a result (obviously, if it was not a
array subclass, it could still return <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>).</p>
<p>Note that in the context of the type hierarchy discussed above this is a
somewhat tricky example, since <code class="xref py py-class docutils literal notranslate"><span class="pre">MaskedArray</span></code> has a strange
position: it is above all subclasses of <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>, in that it can
cast them to its own type, but it does not itself know how to interact
with them in ufuncs.</p>
<aside class="footnote-list brackets">
<aside class="footnote brackets" id="id14" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id13">7</a><span class="fn-bracket">]</span></span>
<p><a class="reference external" href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/">https://rhettinger.wordpress.com/2011/05/26/super-considered-super/</a></p>
</aside>
</aside>
</section>
<section id="turning-ufuncs-off">
<span id="neps-ufunc-overrides-turning-ufuncs-off"></span><h3>Turning Ufuncs off<a class="headerlink" href="#turning-ufuncs-off" title="Link to this heading">#</a></h3>
<p>For some classes, Ufuncs make no sense, and, like for some other special
methods such as <code class="docutils literal notranslate"><span class="pre">__hash__</span></code> and <code class="docutils literal notranslate"><span class="pre">__iter__</span></code> <a class="footnote-reference brackets" href="#id16" id="id15" role="doc-noteref"><span class="fn-bracket">[</span>8<span class="fn-bracket">]</span></a>, one can indicate
Ufuncs are not available by setting <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> to <a class="reference external" href="https://docs.python.org/dev/library/constants.html#None" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">None</span></code></a>.
If a Ufunc is called on any operand that sets <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span> <span class="pre">=</span> <span class="pre">None</span></code>,
it will unconditionally raise <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<p>In the type casting hierarchy, this makes it explicit that the type is
incompatible relative to <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>.</p>
<aside class="footnote-list brackets">
<aside class="footnote brackets" id="id16" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id15">8</a><span class="fn-bracket">]</span></span>
<p><a class="reference external" href="https://docs.python.org/3/reference/datamodel.html#specialnames">https://docs.python.org/3/reference/datamodel.html#specialnames</a></p>
</aside>
</aside>
</section>
<section id="behavior-in-combination-with-python-s-binary-operations">
<h3>Behavior in combination with Python’s binary operations<a class="headerlink" href="#behavior-in-combination-with-python-s-binary-operations" title="Link to this heading">#</a></h3>
<p>The Python operator override mechanism in <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> is coupled to
the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> mechanism. For the special methods calls such as
<code class="docutils literal notranslate"><span class="pre">ndarray.__mul__(self,</span> <span class="pre">other)</span></code> that Python calls for implementing
binary operations such as <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">+</span></code>, NumPy’s <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>
implements the following behavior:</p>
<ul class="simple">
<li><p>If <code class="docutils literal notranslate"><span class="pre">other.__array_ufunc__</span> <span class="pre">is</span> <span class="pre">None</span></code>, <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>
returns <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>. Control reverts to Python, which in turn
will try calling a corresponding reflexive method on <code class="docutils literal notranslate"><span class="pre">other</span></code> (e.g.,
<code class="docutils literal notranslate"><span class="pre">other.__rmul__</span></code>), if present.</p></li>
<li><p>If the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> attribute is absent on <code class="docutils literal notranslate"><span class="pre">other</span></code> and
<code class="docutils literal notranslate"><span class="pre">other.__array_priority__</span> <span class="pre">></span> <span class="pre">self.__array_priority__</span></code>, <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a>
also returns <a class="reference external" href="https://docs.python.org/dev/library/constants.html#NotImplemented" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> (and the logic proceeds as in the
previous case). This ensures backwards compatibility with old versions
of NumPy.</p></li>
<li><p>Otherwise, <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> unilaterally calls the corresponding Ufunc.
Ufuncs never return <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, so <strong>reflexive methods such
as</strong> <code class="docutils literal notranslate"><span class="pre">other.__rmul__</span></code> <strong>cannot be used to override arithmetic with
NumPy arrays if</strong> <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> <strong>is set</strong> to any value other than
<code class="docutils literal notranslate"><span class="pre">None</span></code>. Instead, their behavior needs to be changed by implementing
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> in a fashion consistent with the corresponding Ufunc,
e.g., <code class="docutils literal notranslate"><span class="pre">np.multiply</span></code>. See <a class="reference internal" href="#neps-ufunc-overrides-list-of-operators"><span class="std std-ref">List of operators and NumPy Ufuncs</span></a>
for a list of affected operators and their corresponding ufuncs.</p></li>
</ul>
<p>A class wishing to modify the interaction with <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> in
binary operations therefore has two options:</p>
<ol class="arabic simple">
<li><p>Implement <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> and follow NumPy semantics for Python
binary operations (see below).</p></li>
<li><p>Set <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span> <span class="pre">=</span> <span class="pre">None</span></code>, and implement Python binary
operations freely. In this case, ufuncs called on this argument will
raise <a class="reference external" href="https://docs.python.org/dev/library/exceptions.html#TypeError" title="(in Python v3.14)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> (see
<a class="reference internal" href="#neps-ufunc-overrides-turning-ufuncs-off"><span class="std std-ref">Turning Ufuncs off</span></a>).</p></li>
</ol>
</section>
<section id="recommendations-for-implementing-binary-operations">
<h3>Recommendations for implementing binary operations<a class="headerlink" href="#recommendations-for-implementing-binary-operations" title="Link to this heading">#</a></h3>
<p>For most numerical classes, the easiest way to override binary
operations is thus to define <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> and override the
corresponding Ufunc. The class can then, like <a class="reference external" href="https://numpy.org/devdocs/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v2.3.dev0)"><code class="xref py py-class docutils literal notranslate"><span class="pre">ndarray</span></code></a> itself,
define the binary operators in terms of Ufuncs. Here, one has to take
some care to ensure that one allows for other classes to indicate they
are not compatible, i.e., implementations should be something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">_disables_array_ufunc</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
<span class="k">try</span><span class="p">:</span>
<span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">__array_ufunc__</span> <span class="ow">is</span> <span class="kc">None</span>
<span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">class</span> <span class="nc">ArrayLike</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">def</span> <span class="nf">__array_ufunc__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ufunc</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="o">*</span><span class="n">inputs</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="o">...</span>
<span class="k">return</span> <span class="n">result</span>
<span class="c1"># Option 1: call ufunc directly</span>
<span class="k">def</span> <span class="fm">__mul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">if</span> <span class="n">_disables_array_ufunc</span><span class="p">(</span><span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__rmul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">if</span> <span class="n">_disables_array_ufunc</span><span class="p">(</span><span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__imul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="p">(</span><span class="bp">self</span><span class="p">,))</span>
<span class="c1"># Option 2: call into one's own __array_ufunc__</span>
<span class="k">def</span> <span class="fm">__mul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__array_ufunc__</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">,</span> <span class="s1">'__call__'</span><span class="p">,</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__rmul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__array_ufunc__</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">,</span> <span class="s1">'__call__'</span><span class="p">,</span> <span class="n">other</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__imul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="n">result</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">__array_ufunc__</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">multiply</span><span class="p">,</span> <span class="s1">'__call__'</span><span class="p">,</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">,</span>
<span class="n">out</span><span class="o">=</span><span class="p">(</span><span class="bp">self</span><span class="p">,))</span>
<span class="k">if</span> <span class="n">result</span> <span class="ow">is</span> <span class="bp">NotImplemented</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>To see why some care is necessary, consider another class <code class="docutils literal notranslate"><span class="pre">other</span></code> that
does not know how to deal with arrays and ufuncs, and thus has set
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> to <a class="reference external" href="https://docs.python.org/dev/library/constants.html#None" title="(in Python v3.14)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">None</span></code></a>, but does know how to do
multiplication:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyObject</span><span class="p">:</span>
<span class="n">__array_ufunc__</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
<span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="s2">"MyObject(</span><span class="si">{!r}</span><span class="s2">)"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__mul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
<span class="k">return</span> <span class="n">MyObject</span><span class="p">(</span><span class="mi">1234</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__rmul__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>