-
Notifications
You must be signed in to change notification settings - Fork 6
/
nep-0018-array-function-protocol.html
1471 lines (1275 loc) · 111 KB
/
nep-0018-array-function-protocol.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 18 — A dispatch mechanism for NumPy’s high level array functions — 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-0018-array-function-protocol';</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 19 — Random number generator policy" href="nep-0019-rng-policy.html" />
<link rel="prev" title="NEP 15 — Merging multiarray and umath" href="nep-0015-merge-multiarray-umath.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 17, 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"><a class="reference internal" href="nep-0013-ufunc-overrides.html">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 current active"><a class="current reference internal" href="#">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 18 — A dispatch mechanism for NumPy’s high level array functions</span></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article">
<section id="nep-18-a-dispatch-mechanism-for-numpy-s-high-level-array-functions">
<span id="nep18"></span><h1>NEP 18 — A dispatch mechanism for NumPy’s high level array functions<a class="headerlink" href="#nep-18-a-dispatch-mechanism-for-numpy-s-high-level-array-functions" 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>Stephan Hoyer <<a class="reference external" href="mailto:shoyer%40google.com">shoyer<span>@</span>google<span>.</span>com</a>></p>
</dd>
<dt class="field-even">Author<span class="colon">:</span></dt>
<dd class="field-even"><p>Matthew Rocklin <<a class="reference external" href="mailto:mrocklin%40gmail.com">mrocklin<span>@</span>gmail<span>.</span>com</a>></p>
</dd>
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>Marten van Kerkwijk <<a class="reference external" href="mailto:mhvk%40astro.utoronto.ca">mhvk<span>@</span>astro<span>.</span>utoronto<span>.</span>ca</a>></p>
</dd>
<dt class="field-even">Author<span class="colon">:</span></dt>
<dd class="field-even"><p>Hameer Abbasi <<a class="reference external" href="mailto:hameerabbasi%40yahoo.com">hameerabbasi<span>@</span>yahoo<span>.</span>com</a>></p>
</dd>
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>Eric Wieser <<a class="reference external" href="mailto:wieser.eric%40gmail.com">wieser<span>.</span>eric<span>@</span>gmail<span>.</span>com</a>></p>
</dd>
<dt class="field-even">Status<span class="colon">:</span></dt>
<dd class="field-even"><p>Final</p>
</dd>
<dt class="field-odd">Type<span class="colon">:</span></dt>
<dd class="field-odd"><p>Standards Track</p>
</dd>
<dt class="field-even">Created<span class="colon">:</span></dt>
<dd class="field-even"><p>2018-05-29</p>
</dd>
<dt class="field-odd">Updated<span class="colon">:</span></dt>
<dd class="field-odd"><p>2019-05-25</p>
</dd>
<dt class="field-even">Resolution<span class="colon">:</span></dt>
<dd class="field-even"><p><a class="reference external" href="https://mail.python.org/pipermail/numpy-discussion/2018-August/078493.html">https://mail.python.org/pipermail/numpy-discussion/2018-August/078493.html</a></p>
</dd>
</dl>
<section id="abstract">
<h2>Abstract<a class="headerlink" href="#abstract" title="Link to this heading">#</a></h2>
<p>We propose the <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol, to allow arguments of NumPy
functions to define how that function operates on them. This will allow
using NumPy as a high level API for efficient multi-dimensional array
operations, even with array implementations that differ greatly from
<code class="docutils literal notranslate"><span class="pre">numpy.ndarray</span></code>.</p>
</section>
<section id="detailed-description">
<h2>Detailed description<a class="headerlink" href="#detailed-description" title="Link to this heading">#</a></h2>
<p>NumPy’s high level ndarray API has been implemented several times
outside of NumPy itself for different architectures, such as for GPU
arrays (CuPy), Sparse arrays (scipy.sparse, pydata/sparse) and parallel
arrays (Dask array) as well as various NumPy-like implementations in the
deep learning frameworks, like TensorFlow and PyTorch.</p>
<p>Similarly there are many projects that build on top of the NumPy API
for labeled and indexed arrays (XArray), automatic differentiation
(Autograd, Tangent), masked arrays (numpy.ma), physical units (astropy.units,
pint, unyt), etc. that add additional functionality on top of the NumPy API.
Most of these project also implement a close variation of NumPy’s level high
API.</p>
<p>We would like to be able to use these libraries together, for example we
would like to be able to place a CuPy array within XArray, or perform
automatic differentiation on Dask array code. This would be easier to
accomplish if code written for NumPy ndarrays could also be used by
other NumPy-like projects.</p>
<p>For example, we would like for the following code example to work
equally well with any NumPy-like array object:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">tensordot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">T</span><span class="p">)</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="n">y</span><span class="p">))</span>
</pre></div>
</div>
<p>Some of this is possible today with various protocol mechanisms within
NumPy.</p>
<ul class="simple">
<li><p>The <code class="docutils literal notranslate"><span class="pre">np.exp</span></code> function checks the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> protocol</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">.T</span></code> method works using Python’s method dispatch</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">np.mean</span></code> function explicitly checks for a <code class="docutils literal notranslate"><span class="pre">.mean</span></code> method on
the argument</p></li>
</ul>
<p>However other functions, like <code class="docutils literal notranslate"><span class="pre">np.tensordot</span></code> do not dispatch, and
instead are likely to coerce to a NumPy array (using the <code class="docutils literal notranslate"><span class="pre">__array__</span></code>)
protocol, or err outright. To achieve enough coverage of the NumPy API
to support downstream projects like XArray and autograd we want to
support <em>almost all</em> functions within NumPy, which calls for a more
reaching protocol than just <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>. We would like a
protocol that allows arguments of a NumPy function to take control and
divert execution to another function (for example a GPU or parallel
implementation) in a way that is safe and consistent across projects.</p>
</section>
<section id="implementation">
<h2>Implementation<a class="headerlink" href="#implementation" title="Link to this heading">#</a></h2>
<p>We propose adding support for a new protocol in NumPy,
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.</p>
<p>This protocol is intended to be a catch-all for NumPy functionality that
is not covered by the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> protocol for universal functions
(like <code class="docutils literal notranslate"><span class="pre">np.exp</span></code>). The semantics are very similar to <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>, except
the operation is specified by an arbitrary callable object rather than a ufunc
instance and method.</p>
<p>A prototype implementation can be found in
<a class="reference external" href="https://nbviewer.jupyter.org/gist/shoyer/1f0a308a06cd96df20879a1ddb8f0006">this notebook</a>.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>The <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol, and its use on particular functions,
is <em>experimental</em>. We plan to retain an interface that makes it possible
to override NumPy functions, but the way to do so for particular functions
<strong>can and will change</strong> with little warning. If such reduced backwards
compatibility guarantees are not accepted to you, do not rely upon overrides
of NumPy functions for non-NumPy arrays. See “Non-goals” below for more
details.</p>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Dispatch with the <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol has been implemented but is
not yet enabled by default:</p>
<ul class="simple">
<li><p>In NumPy 1.16, you need to set the environment variable
<code class="docutils literal notranslate"><span class="pre">NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=1</span></code> before importing NumPy to test
NumPy function overrides.</p></li>
<li><p>In NumPy 1.17, the protocol will be enabled by default, but can be disabled
with <code class="docutils literal notranslate"><span class="pre">NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=0</span></code>.</p></li>
<li><p>Eventually, expect to <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> to always be enabled.</p></li>
</ul>
</div>
<section id="the-interface">
<h3>The interface<a class="headerlink" href="#the-interface" title="Link to this heading">#</a></h3>
<p>We propose the following signature for implementations of
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__array_function__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">types</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">func</span></code> is an arbitrary callable exposed by NumPy’s public API,
which was called in the form <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code>.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">types</span></code> is a <a class="reference external" href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Collection">collection</a>
of unique argument types from the original NumPy function call that
implement <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.</p></li>
<li><p>The tuple <code class="docutils literal notranslate"><span class="pre">args</span></code> and dict <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> are directly passed on from the
original call.</p></li>
</ul>
<p>Unlike <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>, there are no high-level guarantees about the
type of <code class="docutils literal notranslate"><span class="pre">func</span></code>, or about which of <code class="docutils literal notranslate"><span class="pre">args</span></code> and <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> may contain objects
implementing the array API.</p>
<p>As a convenience for <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementers, <code class="docutils literal notranslate"><span class="pre">types</span></code> provides all
argument types with an <code class="docutils literal notranslate"><span class="pre">'__array_function__'</span></code> attribute. This
allows implementers to quickly identify cases where they should defer to
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementations on other arguments.
The type of <code class="docutils literal notranslate"><span class="pre">types</span></code> is intentionally vague:
<code class="docutils literal notranslate"><span class="pre">frozenset</span></code> would most closely match intended use, but we may use <code class="docutils literal notranslate"><span class="pre">tuple</span></code>
instead for performance reasons. In any case, <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>
implementations should not rely on the iteration order of <code class="docutils literal notranslate"><span class="pre">types</span></code>, which
would violate a well-defined “Type casting hierarchy” (as described in
<a class="reference internal" href="nep-0013-ufunc-overrides.html#nep13"><span class="std std-ref">NEP-13</span></a>).</p>
</section>
<section id="example-for-a-project-implementing-the-numpy-api">
<h3>Example for a project implementing the NumPy API<a class="headerlink" href="#example-for-a-project-implementing-the-numpy-api" title="Link to this heading">#</a></h3>
<p>Most implementations of <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> will start with two
checks:</p>
<ol class="arabic simple">
<li><p>Is the given function something that we know how to overload?</p></li>
<li><p>Are all arguments of a type that we know how to handle?</p></li>
</ol>
<p>If these conditions hold, <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> should return
the result from calling its implementation for <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code>.
Otherwise, it should return the sentinel value <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, indicating
that the function is not implemented by these types. This is preferable to
raising <code class="docutils literal notranslate"><span class="pre">TypeError</span></code> directly, because it gives <em>other</em> arguments the
opportunity to define the operations.</p>
<p>There are no general requirements on the return value from
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>, although most sensible implementations should probably
return array(s) with the same type as one of the function’s arguments.
If/when Python gains
<a class="reference external" href="https://www.python.org/dev/peps/pep-0544/">typing support for protocols</a>
and NumPy adds static type annotations, the <code class="docutils literal notranslate"><span class="pre">@overload</span></code> implementation
for <code class="docutils literal notranslate"><span class="pre">SupportsArrayFunction</span></code> will indicate a return type of <code class="docutils literal notranslate"><span class="pre">Any</span></code>.</p>
<p>It may also be convenient to define a custom decorators (<code class="docutils literal notranslate"><span class="pre">implements</span></code> below)
for registering <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementations.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">HANDLED_FUNCTIONS</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">class</span> <span class="nc">MyArray</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">__array_function__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">types</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">):</span>
<span class="k">if</span> <span class="n">func</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">HANDLED_FUNCTIONS</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="c1"># Note: this allows subclasses that don't override</span>
<span class="c1"># __array_function__ to handle MyArray objects</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">all</span><span class="p">(</span><span class="nb">issubclass</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">MyArray</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">types</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="k">return</span> <span class="n">HANDLED_FUNCTIONS</span><span class="p">[</span><span class="n">func</span><span class="p">](</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">implements</span><span class="p">(</span><span class="n">numpy_function</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""Register an __array_function__ implementation for MyArray objects."""</span>
<span class="k">def</span> <span class="nf">decorator</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
<span class="n">HANDLED_FUNCTIONS</span><span class="p">[</span><span class="n">numpy_function</span><span class="p">]</span> <span class="o">=</span> <span class="n">func</span>
<span class="k">return</span> <span class="n">func</span>
<span class="k">return</span> <span class="n">decorator</span>
<span class="nd">@implements</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">concatenate</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">concatenate</span><span class="p">(</span><span class="n">arrays</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="o">...</span> <span class="c1"># implementation of concatenate for MyArray objects</span>
<span class="nd">@implements</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">broadcast_to</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">broadcast_to</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="n">shape</span><span class="p">):</span>
<span class="o">...</span> <span class="c1"># implementation of broadcast_to for MyArray objects</span>
</pre></div>
</div>
<p>Note that it is not required for <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementations to
include <em>all</em> of the corresponding NumPy function’s optional arguments
(e.g., <code class="docutils literal notranslate"><span class="pre">broadcast_to</span></code> above omits the irrelevant <code class="docutils literal notranslate"><span class="pre">subok</span></code> argument).
Optional arguments are only passed in to <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> if they
were explicitly used in the NumPy function call.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Just like the case for builtin special methods like <code class="docutils literal notranslate"><span class="pre">__add__</span></code>, properly
written <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods should always return
<code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> when an unknown type is encountered. Otherwise, it will
be impossible to correctly override NumPy functions from another object
if the operation also includes one of your objects.</p>
</div>
</section>
<section id="necessary-changes-within-the-numpy-codebase-itself">
<h3>Necessary changes within the NumPy codebase itself<a class="headerlink" href="#necessary-changes-within-the-numpy-codebase-itself" title="Link to this heading">#</a></h3>
<p>This will require two changes within the NumPy codebase:</p>
<ol class="arabic">
<li><p>A function to inspect available inputs, look for the
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> attribute on those inputs, and call those
methods appropriately until one succeeds. This needs to be fast in the
common all-NumPy case, and have acceptable performance (no worse than
linear time) even if the number of overloaded inputs is large (e.g.,
as might be the case for <cite>np.concatenate</cite>).</p>
<p>This is one additional function of moderate complexity.</p>
</li>
<li><p>Calling this function within all relevant NumPy functions.</p>
<p>This affects many parts of the NumPy codebase, although with very low
complexity.</p>
</li>
</ol>
<section id="finding-and-calling-the-right-array-function">
<h4>Finding and calling the right <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code><a class="headerlink" href="#finding-and-calling-the-right-array-function" title="Link to this heading">#</a></h4>
<p>Given a NumPy function, <code class="docutils literal notranslate"><span class="pre">*args</span></code> and <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code> inputs, we need to
search through <code class="docutils literal notranslate"><span class="pre">*args</span></code> and <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code> for all appropriate inputs
that might have the <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> attribute. Then we need to
select among those possible methods and execute the right one.
Negotiating between several possible implementations can be complex.</p>
<section id="finding-arguments">
<h5>Finding arguments<a class="headerlink" href="#finding-arguments" title="Link to this heading">#</a></h5>
<p>Valid arguments may be directly in the <code class="docutils literal notranslate"><span class="pre">*args</span></code> and <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>, such
as in the case for <code class="docutils literal notranslate"><span class="pre">np.tensordot(left,</span> <span class="pre">right,</span> <span class="pre">out=out)</span></code>, or they may
be nested within lists or dictionaries, such as in the case of
<code class="docutils literal notranslate"><span class="pre">np.concatenate([x,</span> <span class="pre">y,</span> <span class="pre">z])</span></code>. This can be problematic for two reasons:</p>
<ol class="arabic simple">
<li><p>Some functions are given long lists of values, and traversing them
might be prohibitively expensive.</p></li>
<li><p>Some functions may have arguments that we don’t want to inspect, even
if they have the <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> method.</p></li>
</ol>
<p>To resolve these issues, NumPy functions should explicitly indicate which
of their arguments may be overloaded, and how these arguments should be
checked. As a rule, this should include all arguments documented as either
<code class="docutils literal notranslate"><span class="pre">array_like</span></code> or <code class="docutils literal notranslate"><span class="pre">ndarray</span></code>.</p>
<p>We propose to do so by writing “dispatcher” functions for each overloaded
NumPy function:</p>
<ul class="simple">
<li><p>These functions will be called with the exact same arguments that were passed
into the NumPy function (i.e., <code class="docutils literal notranslate"><span class="pre">dispatcher(*args,</span> <span class="pre">**kwargs)</span></code>), and should
return an iterable of arguments to check for overrides.</p></li>
<li><p>Dispatcher functions are required to share the exact same positional,
optional and keyword-only arguments as their corresponding NumPy functions.
Otherwise, valid invocations of a NumPy function could result in an error when
calling its dispatcher.</p></li>
<li><p>Because default <em>values</em> for keyword arguments do not have
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> attributes, by convention we set all default argument
values to <code class="docutils literal notranslate"><span class="pre">None</span></code>. This reduces the likelihood of signatures falling out
of sync, and minimizes extraneous information in the dispatcher.
The only exception should be cases where the argument value in some way
effects dispatching, which should be rare.</p></li>
</ul>
<p>An example of the dispatcher for <code class="docutils literal notranslate"><span class="pre">np.concatenate</span></code> may be instructive:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">_concatenate_dispatcher</span><span class="p">(</span><span class="n">arrays</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">for</span> <span class="n">array</span> <span class="ow">in</span> <span class="n">arrays</span><span class="p">:</span>
<span class="k">yield</span> <span class="n">array</span>
<span class="k">if</span> <span class="n">out</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">yield</span> <span class="n">out</span>
</pre></div>
</div>
<p>The concatenate dispatcher is written as generator function, which allows it
to potentially include the value of the optional <code class="docutils literal notranslate"><span class="pre">out</span></code> argument without
needing to create a new sequence with the (potentially long) list of objects
to be concatenated.</p>
</section>
<section id="trying-array-function-methods-until-the-right-one-works">
<h5>Trying <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods until the right one works<a class="headerlink" href="#trying-array-function-methods-until-the-right-one-works" title="Link to this heading">#</a></h5>
<p>Many arguments may implement the <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol. Some
of these may decide that, given the available inputs, they are unable to
determine the correct result. How do we call the right one? If several
are valid then which has precedence?</p>
<p>For the most part, the rules for dispatch with <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>
match those for <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> (see
<a class="reference internal" href="nep-0013-ufunc-overrides.html#nep13"><span class="std std-ref">NEP-13</span></a>).
In particular:</p>
<ul class="simple">
<li><p>NumPy will gather implementations of <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> from all
specified inputs and call them in order: subclasses before
superclasses, and otherwise left to right. Note that in some edge cases
involving subclasses, this differs slightly from the
<a class="reference external" href="https://bugs.python.org/issue30140">current behavior</a> of Python.</p></li>
<li><p>Implementations of <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> indicate that they can
handle the operation by returning any value other than
<code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>.</p></li>
<li><p>If all <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods return <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>,
NumPy will raise <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.</p></li>
</ul>
<p>If no <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> methods exist, NumPy will default to calling its
own implementation, intended for use on NumPy arrays. This case arises, for
example, when all array-like arguments are Python numbers or lists.
(NumPy arrays do have a <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> method, given below, but it
always returns <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> if any argument other than a NumPy array
subclass implements <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.)</p>
<p>One deviation from the current behavior of <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> is that NumPy
will only call <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> on the <em>first</em> argument of each unique
type. This matches Python’s
<a class="reference external" href="https://docs.python.org/3/reference/datamodel.html#object.__ror__">rule for calling reflected methods</a>,
and this ensures that checking overloads has acceptable performance even when
there are a large number of overloaded arguments. To avoid long-term divergence
between these two dispatch protocols, we should
<a class="reference external" href="https://github.com/numpy/numpy/issues/11306">also update</a>
<code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> to match this behavior.</p>
</section>
<section id="the-array-function-method-on-numpy-ndarray">
<h5>The <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> method on <code class="docutils literal notranslate"><span class="pre">numpy.ndarray</span></code><a class="headerlink" href="#the-array-function-method-on-numpy-ndarray" title="Link to this heading">#</a></h5>
<p>The use cases for subclasses with <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> are the same as those
with <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code>, so <code class="docutils literal notranslate"><span class="pre">numpy.ndarray</span></code> also defines a
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> method:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__array_function__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">types</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">all</span><span class="p">(</span><span class="nb">issubclass</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">ndarray</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">types</span><span class="p">):</span>
<span class="c1"># Defer to any non-subclasses that implement __array_function__</span>
<span class="k">return</span> <span class="bp">NotImplemented</span>
<span class="c1"># Use NumPy's private implementation without __array_function__</span>
<span class="c1"># dispatching</span>
<span class="k">return</span> <span class="n">func</span><span class="o">.</span><span class="n">_implementation</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>This method matches NumPy’s dispatching rules, so for most part it is
possible to pretend that <code class="docutils literal notranslate"><span class="pre">ndarray.__array_function__</span></code> does not exist.
The private <code class="docutils literal notranslate"><span class="pre">_implementation</span></code> attribute, defined below in the
<code class="docutils literal notranslate"><span class="pre">array_function_dispatch</span></code> decorator, allows us to avoid the special cases for
NumPy arrays that were needed in the <code class="docutils literal notranslate"><span class="pre">__array_ufunc__</span></code> protocol.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol always calls subclasses before
superclasses, so if any <code class="docutils literal notranslate"><span class="pre">ndarray</span></code> subclasses are involved in an operation,
they will get the chance to override it, just as if any other argument
overrides <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>. But the default behavior in an operation
that combines a base NumPy array and a subclass is different: if the subclass
returns <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, NumPy’s implementation of the function will be
called instead of raising an exception. This is appropriate since subclasses
are <a class="reference external" href="https://en.wikipedia.org/wiki/Liskov_substitution_principle">expected to be substitutable</a>.</p>
<p>We still caution authors of subclasses to exercise caution when relying
upon details of NumPy’s internal implementations. It is not always possible to
write a perfectly substitutable ndarray subclass, e.g., in cases involving the
creation of new arrays, not least because NumPy makes use of internal
optimizations specialized to base NumPy arrays, e.g., code written in C. Even
if NumPy’s implementation happens to work today, it may not work in the future.
In these cases, your recourse is to re-implement top-level NumPy functions via
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> on your subclass.</p>
</section>
</section>
<section id="changes-within-numpy-functions">
<h4>Changes within NumPy functions<a class="headerlink" href="#changes-within-numpy-functions" title="Link to this heading">#</a></h4>
<p>Given a function defining the above behavior, for now call it
<code class="docutils literal notranslate"><span class="pre">implement_array_function</span></code>, we now need to call that
function from within every relevant NumPy function. This is a pervasive change,
but of fairly simple and innocuous code that should complete quickly and
without effect if no arguments implement the <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>
protocol.</p>
<p>To achieve this, we define a <code class="docutils literal notranslate"><span class="pre">array_function_dispatch</span></code> decorator to rewrite
NumPy functions. The basic implementation is as follows:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">array_function_dispatch</span><span class="p">(</span><span class="n">dispatcher</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""Wrap a function for dispatch with the __array_function__ protocol."""</span>
<span class="k">def</span> <span class="nf">decorator</span><span class="p">(</span><span class="n">implementation</span><span class="p">):</span>
<span class="nd">@functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">implementation</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">public_api</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">relevant_args</span> <span class="o">=</span> <span class="n">dispatcher</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="k">return</span> <span class="n">implement_array_function</span><span class="p">(</span>
<span class="n">implementation</span><span class="p">,</span> <span class="n">public_api</span><span class="p">,</span> <span class="n">relevant_args</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>
<span class="k">if</span> <span class="n">module</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">public_api</span><span class="o">.</span><span class="vm">__module__</span> <span class="o">=</span> <span class="n">module</span>
<span class="c1"># for ndarray.__array_function__</span>
<span class="n">public_api</span><span class="o">.</span><span class="n">_implementation</span> <span class="o">=</span> <span class="n">implementation</span>
<span class="k">return</span> <span class="n">public_api</span>
<span class="k">return</span> <span class="n">decorator</span>
<span class="c1"># example usage</span>
<span class="k">def</span> <span class="nf">_broadcast_to_dispatcher</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="n">shape</span><span class="p">,</span> <span class="n">subok</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">return</span> <span class="p">(</span><span class="n">array</span><span class="p">,)</span>
<span class="nd">@array_function_dispatch</span><span class="p">(</span><span class="n">_broadcast_to_dispatcher</span><span class="p">,</span> <span class="n">module</span><span class="o">=</span><span class="s1">'numpy'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">broadcast_to</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="n">shape</span><span class="p">,</span> <span class="n">subok</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
<span class="o">...</span> <span class="c1"># existing definition of np.broadcast_to</span>
</pre></div>
</div>
<p>Using a decorator is great! We don’t need to change the definitions of
existing NumPy functions, and only need to write a few additional lines
for the dispatcher function. We could even reuse a single dispatcher for
families of functions with the same signature (e.g., <code class="docutils literal notranslate"><span class="pre">sum</span></code> and <code class="docutils literal notranslate"><span class="pre">prod</span></code>).
For such functions, the largest change could be adding a few lines to the
docstring to note which arguments are checked for overloads.</p>
<p>It’s particularly worth calling out the decorator’s use of
<code class="docutils literal notranslate"><span class="pre">functools.wraps</span></code>:</p>
<ul class="simple">
<li><p>This ensures that the wrapped function has the same name and docstring as
the wrapped NumPy function.</p></li>
<li><p>On Python 3, it also ensures that the decorator function copies the original
function signature, which is important for introspection based tools such as
auto-complete.</p></li>
<li><p>Finally, it ensures that the wrapped function
<a class="reference external" href="http://gael-varoquaux.info/programming/decoration-in-python-done-right-decorating-and-pickling.html">can be pickled</a>.</p></li>
</ul>
<p>The example usage illustrates several best practices for writing dispatchers
relevant to NumPy contributors:</p>
<ul>
<li><p>We passed the <code class="docutils literal notranslate"><span class="pre">module</span></code> argument, which in turn sets the <code class="docutils literal notranslate"><span class="pre">__module__</span></code>
attribute on the generated function. This is for the benefit of better error
messages, here for errors raised internally by NumPy when no implementation
is found, e.g.,
<code class="docutils literal notranslate"><span class="pre">TypeError:</span> <span class="pre">no</span> <span class="pre">implementation</span> <span class="pre">found</span> <span class="pre">for</span> <span class="pre">'numpy.broadcast_to'</span></code>. Setting
<code class="docutils literal notranslate"><span class="pre">__module__</span></code> to the canonical location in NumPy’s public API encourages
users to use NumPy’s public API for identifying functions in
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.</p></li>
<li><p>The dispatcher is a function that returns a tuple, rather than an equivalent
(and equally valid) generator using <code class="docutils literal notranslate"><span class="pre">yield</span></code>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># example usage</span>
<span class="k">def</span> <span class="nf">broadcast_to</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="n">shape</span><span class="p">,</span> <span class="n">subok</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">yield</span> <span class="n">array</span>
</pre></div>
</div>
<p>This is no accident: NumPy’s implementation of dispatch for
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> is fastest when dispatcher functions return a builtin
sequence type (<code class="docutils literal notranslate"><span class="pre">tuple</span></code> or <code class="docutils literal notranslate"><span class="pre">list</span></code>).</p>
<p>On a related note, it’s perfectly fine for dispatchers to return arguments
even if in some cases you <em>know</em> that they cannot have an
<code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> method. This can arise for functions with default
arguments (e.g., <code class="docutils literal notranslate"><span class="pre">None</span></code>) or complex signatures. NumPy’s dispatching logic
sorts out these cases very quickly, so it generally is not worth the trouble
of parsing them on your own.</p>
</li>
</ul>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The code for <code class="docutils literal notranslate"><span class="pre">array_function_dispatch</span></code> above has been updated from the
original version of this NEP to match the actual
<a class="reference external" href="https://github.com/numpy/numpy/blob/e104f03ac8f65ae5b92a9b413b0fa639f39e6de2/numpy/core/overrides.py">implementation in NumPy</a>.</p>
</div>
</section>
</section>
<section id="extensibility">
<h3>Extensibility<a class="headerlink" href="#extensibility" title="Link to this heading">#</a></h3>
<p>An important virtue of this approach is that it allows for adding new
optional arguments to NumPy functions without breaking code that already
relies on <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code>.</p>
<p>This is not a theoretical concern. NumPy’s older, haphazard implementation of
overrides <em>within</em> functions like <code class="docutils literal notranslate"><span class="pre">np.sum()</span></code> necessitated some awkward
gymnastics when we decided to add new optional arguments, e.g., the new
<code class="docutils literal notranslate"><span class="pre">keepdims</span></code> argument is only passed in cases where it is used:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">sum</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">_NoValue</span><span class="p">):</span>
<span class="n">kwargs</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">if</span> <span class="n">keepdims</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">np</span><span class="o">.</span><span class="n">_NoValue</span><span class="p">:</span>
<span class="n">kwargs</span><span class="p">[</span><span class="s1">'keepdims'</span><span class="p">]</span> <span class="o">=</span> <span class="n">keepdims</span>
<span class="k">return</span> <span class="n">array</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>For <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> implementers, this also means that it is possible
to implement even existing optional arguments incrementally, and only in cases
where it makes sense. For example, a library implementing immutable arrays
would not be required to explicitly include an unsupported <code class="docutils literal notranslate"><span class="pre">out</span></code> argument in
the function signature. This can be somewhat onerous to implement properly,
e.g.,</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_sum</span><span class="p">(</span><span class="n">array</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">out</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">out</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s1">'out argument is not supported'</span><span class="p">)</span>
<span class="o">...</span>
</pre></div>
</div>
<p>We thus avoid encouraging the tempting shortcut of adding catch-all
<code class="docutils literal notranslate"><span class="pre">**ignored_kwargs</span></code> to the signatures of functions called by NumPy, which fails
silently for misspelled or ignored arguments.</p>
</section>
<section id="performance">
<h3>Performance<a class="headerlink" href="#performance" title="Link to this heading">#</a></h3>
<p>Performance is always a concern with NumPy, even though NumPy users have
already prioritized usability over pure speed with their choice of the Python
language itself. It’s important that this new <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol
not impose a significant cost in the typical case of NumPy functions acting
on NumPy arrays.</p>
<p>Our <a class="reference external" href="https://nbviewer.jupyter.org/gist/shoyer/1f0a308a06cd96df20879a1ddb8f0006">microbenchmark results</a>
show that a pure Python implementation of the override machinery described
above adds roughly 2-3 microseconds of overhead to each NumPy function call
without any overloaded arguments. For context, typical NumPy functions on small
arrays have a runtime of 1-10 microseconds, mostly determined by what fraction
of the function’s logic is written in C. For example, one microsecond is about
the difference in speed between the <code class="docutils literal notranslate"><span class="pre">ndarray.sum()</span></code> method (1.6 us) and
<code class="docutils literal notranslate"><span class="pre">numpy.sum()</span></code> function (2.6 us).</p>
<p>Fortunately, we expect significantly less overhead with a C implementation of
<code class="docutils literal notranslate"><span class="pre">implement_array_function</span></code>, which is where the bulk of the
runtime is. This would leave the <code class="docutils literal notranslate"><span class="pre">array_function_dispatch</span></code> decorator and
dispatcher function on their own adding about 0.5 microseconds of overhead,
for perhaps ~1 microsecond of overhead in the typical case.</p>
<p>In our view, this level of overhead is reasonable to accept for code written
in Python. We’re pretty sure that the vast majority of NumPy users aren’t
concerned about performance differences measured in microsecond(s) on NumPy
functions, because it’s difficult to do <em>anything</em> in Python in less than a
microsecond.</p>
</section>
<section id="use-outside-of-numpy">
<h3>Use outside of NumPy<a class="headerlink" href="#use-outside-of-numpy" title="Link to this heading">#</a></h3>
<p>Nothing about this protocol that is particular to NumPy itself. Should
we encourage use of the same <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> protocol third-party
libraries for overloading non-NumPy functions, e.g., for making
array-implementation generic functionality in SciPy?</p>
<p>This would offer significant advantages (SciPy wouldn’t need to invent
its own dispatch system) and no downsides that we can think of, because
every function that dispatches with <code class="docutils literal notranslate"><span class="pre">__array_function__</span></code> already needs
to be explicitly recognized. Libraries like Dask, CuPy, and Autograd
already wrap a limited subset of SciPy functionality (e.g.,
<code class="docutils literal notranslate"><span class="pre">scipy.linalg</span></code>) similarly to how they wrap NumPy.</p>
<p>If we want to do this, we should expose at least the decorator
<code class="docutils literal notranslate"><span class="pre">array_function_dispatch()</span></code> and possibly also the lower level
<code class="docutils literal notranslate"><span class="pre">implement_array_function()</span></code> as part of NumPy’s public API.</p>
</section>
</section>
<section id="non-goals">
<h2>Non-goals<a class="headerlink" href="#non-goals" title="Link to this heading">#</a></h2>