File: highlevel.py

package info (click to toggle)
python-awkward 2.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 35,360 kB
  • sloc: python: 187,941; cpp: 33,672; sh: 432; ansic: 256; makefile: 21; javascript: 8
file content (3371 lines) | stat: -rw-r--r-- 122,376 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward/blob/main/LICENSE

from __future__ import annotations

import builtins
import copy
import functools
import html
import inspect
import io
import keyword
import pickle
import re
import weakref
from collections.abc import Iterable, Mapping, Sequence, Sized

from awkward_cpp.lib import _ext

import awkward as ak
import awkward._connect.hist
from awkward._attrs import Attrs, attrs_of, without_transient_attrs
from awkward._backends.dispatch import register_backend_lookup_factory
from awkward._backends.numpy import NumpyBackend
from awkward._behavior import behavior_of, get_array_class, get_record_class
from awkward._layout import wrap_layout
from awkward._namedaxis import (
    NAMED_AXIS_KEY,
    AxisMapping,
    NamedAxis,
    _get_named_axis,
    _make_positional_axis_tuple,
    _normalize_named_slice,
    _prepare_named_axis_for_attrs,
    _prettify_named_axes,
)
from awkward._nplikes.numpy import Numpy
from awkward._nplikes.numpy_like import NumpyMetadata
from awkward._operators import NDArrayOperatorsMixin
from awkward._pickle import (
    custom_reduce,
    unpickle_array_schema_1,
    unpickle_record_schema_1,
)
from awkward._regularize import is_non_string_like_iterable
from awkward._typing import Any, TypeVar
from awkward._util import STDOUT
from awkward.prettyprint import highlevel_array_show_rows
from awkward.prettyprint import valuestr as prettyprint_valuestr

__all__ = ("Array", "ArrayBuilder", "Record")

np = NumpyMetadata.instance()
numpy = Numpy.instance()

_dir_pattern = re.compile(r"^[a-zA-Z_]\w*$")


T = TypeVar("T", bound=ak.contents.Content)


def non_inspectable_property(impl):
    """property factory that ensures IPython does not call the property during inspection"""

    @functools.wraps(impl)
    def wrapper(self):
        if hasattr(builtins, "__IPYTHON__"):
            from IPython.utils.wildcard import dict_dir

            caller_frame = inspect.currentframe().f_back
            if caller_frame.f_code is dict_dir.__code__:
                return

        return impl(self)

    return property(wrapper)


def _awkward_1_rewrite_partition_form(form, partition: int, template: str = "part{}"):
    """Rewrite partition i as partition 0 for a given container.

    This routine is a helper function for reading awkward1 pickles
    """
    default_prefix = f"{template.format(0)}-"
    part_prefix = f"{template.format(partition)}-"

    def rename_form_key(key: str) -> str:
        suffix = key[len(default_prefix) :]

        return f"{part_prefix}{suffix}"

    def transform(form):
        if isinstance(form, (ak.forms.NumpyForm, ak.forms.EmptyForm)):
            return form.copy(form_key=rename_form_key(form.form_key))
        elif isinstance(
            form,
            (
                ak.forms.ListForm,
                ak.forms.ListOffsetForm,
                ak.forms.RegularForm,
                ak.forms.IndexedForm,
                ak.forms.IndexedOptionForm,
                ak.forms.ByteMaskedForm,
                ak.forms.BitMaskedForm,
            ),
        ):
            return form.copy(
                content=transform(form.content),
                form_key=rename_form_key(form.form_key),
            )
        elif isinstance(
            form,
            (ak.forms.UnionForm, ak.forms.RecordForm),
        ):
            return form.copy(
                contents=[transform(c) for c in form.contents],
                form_key=rename_form_key(form.form_key),
            )
        else:
            raise AssertionError

    return transform(form)


def prepare_layout(layout: T) -> T | str | bytes:
    if isinstance(layout, ak.contents.NumpyArray):
        array_param = layout.parameter("__array__")
        if array_param == "byte":
            return ak._util.tobytes(layout.data)
        elif array_param == "char":
            return ak._util.tobytes(layout.data).decode(errors="surrogateescape")
        else:
            return layout
    else:
        return layout


class Array(NDArrayOperatorsMixin, Iterable, Sized):
    """
    Args:
        data (#ak.contents.Content, #ak.Array, `np.ndarray`, `cp.ndarray`, `pyarrow.*`, str, dict, or iterable):
            Data to wrap or convert into an array.
               - If a NumPy array, the regularity of its dimensions is preserved
                 and the data are viewed, not copied.
               - CuPy arrays are treated the same way as NumPy arrays except that
                 they default to `backend="cuda"`, rather than `backend="cpu"`.
               - If a pyarrow object, calls #ak.from_arrow, preserving as much
                 metadata as possible, usually zero-copy.
               - If a dict of str \u2192 columns, combines the columns into an
                 array of records (like Pandas's DataFrame constructor).
               - If a string, the data are assumed to be JSON.
               - If an iterable, calls #ak.from_iter, which assumes all dimensions
                 have irregular lengths.
        behavior (None or dict): Custom #ak.behavior for this Array only.
        with_name (None or str): Gives tuples and records a name that can be
            used to override their behavior (see below).
        check_valid (bool): If True, verify that the #layout is valid.
        backend (None, `"cpu"`, `"jax"`, `"cuda"`): If `"cpu"`, the Array will be placed in
            main memory for use with other `"cpu"` Arrays and Records; if `"cuda"`,
            the Array will be placed in GPU global memory using CUDA; if `"jax"`, the structure
            is copied to the CPU for use with JAX. if None, the `data` are left untouched.

    High-level array that can contain data of any type.

    For most users, this is the only class in Awkward Array that matters: it
    is the entry point for data analysis with an emphasis on usability. It
    intentionally has a minimum of methods, preferring standalone functions
    like

        ak.num(array1)
        ak.combinations(array1)
        ak.cartesian([array1, array2])
        ak.zip({"x": array1, "y": array2, "z": array3})

    instead of bound methods like

        array1.num()
        array1.combinations()
        array1.cartesian([array2, array3])
        array1.zip(...)   # ?

    because its namespace is valuable for domain-specific parameters and
    functionality. For example, if records contain a field named `"num"`,
    they can be accessed as

        array1.num

    instead of

        array1["num"]

    without any confusion or interference from #ak.num. The same is true
    for domain-specific methods that have been attached to the data. For
    instance, an analysis of mailing addresses might have a function that
    computes zip codes, which can be attached to the data with a method
    like

        latlon.zip()

    without any confusion or interference from #ak.zip. Custom methods like
    this can be added with #ak.behavior, and so the namespace of Array
    attributes must be kept clear for such applications.

    See also #ak.Record.

    Interfaces to other libraries
    =============================

    NumPy
    *****

    When NumPy
    [universal functions](https://docs.scipy.org/doc/numpy/reference/ufuncs.html)
    (ufuncs) are applied to an ak.Array, they are passed through the Awkward
    data structure, applied to the numerical data at its leaves, and the output
    maintains the original structure.

    For example,

        >>> array = ak.Array([[1, 4, 9], [], [16, 25]])
        >>> np.sqrt(array)
        <Array [[1, 2, 3], [], [4, 5]] type='3 * var * float64'>

    See also #ak.Array.__array_ufunc__.

    Some NumPy functions other than ufuncs are also handled properly in
    NumPy >= 1.17 (see
    [NEP 18](https://numpy.org/neps/nep-0018-array-function-protocol.html))
    and if an Awkward override exists. That is,

        np.concatenate

    can be used on an Awkward Array because

        ak.concatenate

    exists.

    Pandas
    ******

    Ragged arrays (list type) can be converted into Pandas
    [MultiIndex](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html)
    rows and nested records can be converted into MultiIndex columns. If the
    Awkward Array has only one "branch" of nested lists (i.e. different record
    fields do not have different-length lists, but a single chain of lists-of-lists
    is okay), then it can be losslessly converted into a single DataFrame.
    Otherwise, multiple DataFrames are needed, though they can be merged (with a
    loss of information).

    The #ak.to_dataframe function performs this conversion; if `how=None`, it
    returns a list of DataFrames; otherwise, `how` is passed to `pd.merge` when
    merging the resultant DataFrames.

    Numba
    *****

    Arrays can be used in [Numba](http://numba.pydata.org/): they can be
    passed as arguments to a Numba-compiled function or returned as return
    values. The only limitation is that Awkward Arrays cannot be *created*
    inside the Numba-compiled function; to make outputs, consider
    #ak.ArrayBuilder.

    Arrow
    *****

    Arrays are convertible to and from [Apache Arrow](https://arrow.apache.org/),
    a standard for representing nested data structures in columnar arrays.
    See #ak.to_arrow and #ak.from_arrow.

    JAX
    ********

    Derivatives of a calculation on an #ak.Array (s) can be calculated with
    [JAX](https://github.com/google/jax#readme), but only if the array
    functions in `ak` / `numpy` are used, not the functions in the `jax`
    library directly (apart from e.g. `jax.grad`).

    Like NumPy ufuncs, the function and its derivatives are evaluated on the
    numeric leaves of the data structure, maintaining structure in the output.
    """

    def __init__(
        self,
        data,
        *,
        behavior=None,
        with_name=None,
        check_valid=False,
        backend=None,
        attrs=None,
        named_axis=None,
    ):
        self._cpp_type = None
        if isinstance(data, ak.contents.Content):
            layout = data

        elif isinstance(data, Array):
            layout = data._layout
            behavior = behavior_of(data, behavior=behavior)
            attrs = attrs_of(data, attrs=attrs)

        elif isinstance(data, dict):
            fields = []
            _arrays = []
            length = None
            for k, v in data.items():
                fields.append(k)
                _arrays.append(Array(v))
                if length is None:
                    length = _arrays[-1].layout.length
                elif length != _arrays[-1].layout.length:
                    raise ValueError(
                        "dict of arrays in ak.Array constructor must have arrays "
                        f"of equal length ({length} vs {_arrays[-1].layout.length}). "
                        "For automatic broadcasting use 'ak.zip' instead. "
                    )
            layout = ak.contents.RecordArray([arr.layout for arr in _arrays], fields)
            attrs = attrs_of(*_arrays, attrs=attrs)
            behavior = behavior_of(*_arrays, behavior=behavior)

        elif isinstance(data, str):
            layout = ak.operations.from_json(data, highlevel=False)

        else:
            layout = ak.operations.to_layout(
                data, allow_record=False, regulararray=False, primitive_policy="error"
            )

        if not isinstance(layout, ak.contents.Content):
            raise TypeError("could not convert data into an ak.Array")

        if with_name is not None:
            layout = ak.operations.with_name(
                layout, with_name, highlevel=False, behavior=behavior, attrs=attrs
            )

        if not (backend is None or backend == layout.backend.name):
            layout = ak.operations.to_backend(layout, backend, highlevel=False)

        if behavior is not None and not isinstance(behavior, Mapping):
            raise TypeError("behavior must be None or a mapping")

        if attrs is not None and not isinstance(attrs, Mapping):
            raise TypeError("attrs must be None or a mapping")

        if named_axis:
            _named_axis = _prepare_named_axis_for_attrs(
                named_axis=named_axis,
                ndim=layout.minmax_depth[1],
            )
            # now we're good, set the named axis
            if attrs is None:
                attrs = {}
            # if NAMED_AXIS_KEY is already in attrs, it will be overwritten
            attrs[NAMED_AXIS_KEY] = _named_axis

        self._layout = layout
        self._behavior = behavior
        self._attrs = attrs

        docstr = layout.purelist_parameter("__doc__")
        if isinstance(docstr, str):
            self.__doc__ = docstr

        self._update_class()

        if check_valid:
            ak.operations.validity_error(self, exception=True)

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)

        ak.jax.register_behavior_class(cls)

    _histogram_module_ = awkward._connect.hist

    def __dask_tokenize__(self):
        return id(self)

    def _update_class(self):
        self._numbaview = None
        self.__class__ = get_array_class(self._layout, self._behavior)
        if hasattr(self, "__awkward_validation__"):
            self.__awkward_validation__()

    @property
    def attrs(self) -> Attrs:
        """
         The mapping containing top-level metadata, which is serialised
        with the array during pickling.

        Keys prefixed with `@` are identified as "transient" attributes
        which are discarded prior to pickling, permitting the storage of
        non-pickleable types.
        """
        if self._attrs is None:
            self._attrs = Attrs({})
        return self._attrs

    @attrs.setter
    def attrs(self, value: Mapping[str, Any]):
        if isinstance(value, Mapping):
            self._attrs = Attrs(value)
        else:
            raise TypeError("attrs must be a 'Attrs' mapping")

    @property
    def layout(self):
        """
        The composable #ak.contents.Content elements that determine how this
        Array is structured.

        This may be considered a "low-level" view, as it distinguishes between
        arrays that have the same logical meaning (i.e. same JSON output and
        high-level #type) but different

        * node types, such as #ak.contents.ListArray and
             #ak.contents.ListOffsetArray,
        * integer type specialization, such as `int64` vs `int32`
        * or specific values, such as gaps in a #ak.contents.ListArray.

        The #ak.contents.Content elements are fully composable, whereas an
        Array is not; the high-level Array is a single-layer "shell" around
        its layout.

        Layouts are rendered as XML instead of a nested list. For example,
        the following `array`

            ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]])

        is presented as

            <Array [[1.1, 2.2, 3.3], [], [4.4, 5.5]] type='3 * var * float64'>

        but `array.layout` is presented as

            <ListOffsetArray len='3'>
                <offsets><Index dtype='int64' len='4'>
                    [0 3 3 5]
                </Index></offsets>
                <content>
                    <NumpyArray dtype='float64' len='5'>[1.1 2.2 3.3 4.4 5.5]</NumpyArray>
                </content>
            </ListOffsetArray>

        (with truncation for large arrays).
        """
        return self._layout

    @layout.setter
    def layout(self, layout):
        if isinstance(layout, ak.contents.Content):
            self._layout = layout
            self._update_class()
        else:
            raise TypeError("layout must be a subclass of ak.contents.Content")

    @property
    def behavior(self):
        """
        The `behavior` parameter passed into this Array's constructor.

        * If a dict, this `behavior` overrides the global #ak.behavior.
             Any keys in the global #ak.behavior but not this `behavior` are
             still valid, but any keys in both are overridden by this
             `behavior`. Keys with a None value are equivalent to missing keys,
             so this `behavior` can effectively remove keys from the
             global #ak.behavior.

        * If None, the Array defaults to the global #ak.behavior.

        See #ak.behavior for a list of recognized key patterns and their
        meanings.
        """
        return self._behavior

    @behavior.setter
    def behavior(self, behavior):
        if behavior is None or isinstance(behavior, Mapping):
            self._behavior = behavior
            self._update_class()
        else:
            raise TypeError("behavior must be None or a dict")

    @property
    def positional_axis(self) -> tuple[int, ...]:
        (_, ndim) = self._layout.minmax_depth
        return _make_positional_axis_tuple(ndim)

    @property
    def named_axis(self) -> AxisMapping:
        return _get_named_axis(self)

    class Mask:
        def __init__(self, array):
            self._array = weakref.ref(array)

        def __getitem__(self, where):
            array = self._array()
            if array is None:
                msg = "The array to mask was deleted before it could be masked. "
                msg += "If you want to construct this mask, you must either keep the array alive "
                msg += "or use 'ak.mask' explicitly."
                raise ValueError(msg)
            with ak._errors.OperationErrorContext(
                "ak.Array.mask", args=[array, where], kwargs={}
            ):
                return ak.operations.mask(array, where, valid_when=True)

    @property
    def mask(self):
        """
        Whereas

            array[array_of_booleans]

        removes elements from `array` in which `array_of_booleans` is False,

            array.mask[array_of_booleans]

        returns data with the same length as the original `array` but False
        values in `array_of_booleans` are mapped to None. Such an output
        can be used in mathematical expressions with the original `array`
        because they are still aligned.

        See <<<filtering>>> and #ak.mask.
        """
        return self.Mask(self)

    def tolist(self):
        """
        Converts this Array into Python objects; same as #ak.to_list
        (but without the underscore, like NumPy's
        [tolist](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html)).
        """
        return self.to_list()

    def to_list(self):
        """
        Converts this Array into Python objects; same as #ak.to_list.
        """
        return self._layout.to_list(self._behavior)

    def to_numpy(self, allow_missing=True):
        """
        Converts this Array into a NumPy array, if possible; same as #ak.to_numpy.
        """
        return ak.operations.to_numpy(self, allow_missing=allow_missing)

    @property
    def nbytes(self):
        """
        The total number of bytes in all the #ak.index.Index,
        and #ak.contents.NumpyArray buffers in this array tree.

        It does not count buffers that must be kept in memory because
        of ownership, but are not directly used in the array. Nor does it count
        the (small) Python objects that reference the (large) array buffers.
        """
        return self._layout.nbytes

    @property
    def ndim(self):
        """
        Number of dimensions (nested variable-length lists and/or regular arrays)
        before reaching a numeric type or a record.

        There may be nested lists within the record, as field values, but this
        number of dimensions does not count those.

        (Some fields may have different depths than others, which is why they
        are not counted.)
        """
        return self._layout.purelist_depth

    @property
    def fields(self):
        """
        List of field names or tuple slot numbers (as strings) of the outermost
        record or tuple in this array.

        If the array contains nested records, only the fields of the outermost
        record are shown. If it contains tuples instead of records, its fields
        are string representations of integers, such as `"0"`, `"1"`, `"2"`, etc.
        The records or tuples may be within multiple layers of nested lists.

        If the array contains neither tuples nor records, it is an empty list.

        See also #ak.fields.
        """
        return self._layout.fields

    @property
    def is_tuple(self):
        """
        If True, the top-most record structure has no named fields, i.e. it's a tuple.
        """
        return self._layout.is_tuple

    def _ipython_key_completions_(self):
        return self._layout.fields

    @property
    def type(self):
        """
        The high-level type of this Array; same as #ak.type.

        Note that the outermost element of an Array's type is always an
        #ak.types.ArrayType, which specifies the number of elements in the array.

        The type of a #ak.contents.Content (from #ak.Array.layout) is not
        wrapped by an #ak.types.ArrayType.
        """
        return ak.types.ArrayType(
            self._layout.form.type,
            self._layout.length,
            self._behavior,
        )

    @property
    def typestr(self):
        """
        The high-level type of this Array, presented as a string.
        """
        return str(self.type)

    def __len__(self):
        """
        The length of this Array, only counting the outermost structure.

        For example, the length of

            ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]])

        is `3`, not `5`.
        """
        return self._layout.length

    def __iter__(self):
        """
        Iterates over this Array in Python.

        Note that this is the *slowest* way to access data (even slower than
        native Python objects, like lists and dicts). Usually, you should
        express your problems in array-at-a-time operations.

        In other words, do this:

            >>> np.sqrt(ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]))
            <Array [[1.05, 1.48, 1.82], [], [2.1, 2.35]] type='3 * var * float64'>

        not this:

            >>> for outer in ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]):
            ...     for inner in outer:
            ...         print(np.sqrt(inner))
            ...
            1.0488088481701516
            1.4832396974191326
            1.816590212458495
            2.0976176963403033
            2.345207879911715

        Iteration over Arrays exists so that they can be more easily inspected
        as Python objects.

        See also #ak.to_list.
        """
        for item in self._layout:
            yield wrap_layout(
                prepare_layout(item),
                self._behavior,
                allow_other=True,
                attrs=self._attrs,
            )

    def __getitem__(self, where):
        """
        Args:
            where (many types supported; see below): Index of positions to
                select from this Array.

        Select items from the Array using an extension of NumPy's (already
        quite extensive) rules.

        All methods of selecting items described in
        [NumPy indexing](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html)
        are supported with one exception
        ([combining advanced and basic indexing](https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing)
        with basic indexes *between* two advanced indexes: the definition
        NumPy chose for the result does not have a generalization beyond
        rectilinear arrays).

        The `where` parameter can be any of the following or a tuple of
        the following.

        * **An integer** selects one element. Like Python/NumPy, it is
          zero-indexed: `0` is the first item, `1` is the second, etc.
          Negative indexes count from the end of the list: `-1` is the
          last, `-2` is the second-to-last, etc.
          Indexes beyond the size of the array, either because they're too
          large or because they're too negative, raise errors. In
          particular, some nested lists might contain a desired element
          while others don't; this would raise an error.
        * **A slice** (either a Python `slice` object or the
          `start:stop:step` syntax) selects a range of elements. The
          `start` and `stop` values are zero-indexed; `start` is inclusive
          and `stop` is exclusive, like Python/NumPy. Negative `step`
          values are allowed, but a `step` of `0` is an error. Slices
          beyond the size of the array are not errors but are truncated,
          like Python/NumPy.
        * **A string** selects a tuple or record field, even if its
          position in the tuple is to the left of the dimension where the
          tuple/record is defined. (See <<<projection>>> below.) This is
          similar to NumPy's
          [field access](https://numpy.org/doc/stable/user/basics.indexing.html#field-access),
          except that strings are allowed in the same tuple with other
          slice types. While record fields have names, tuple fields are
          integer strings, such as `"0"`, `"1"`, `"2"` (always
          non-negative). Be careful to distinguish these from non-string
          integers.
        * **An iterable of strings** (not the top-level tuple) selects
          multiple tuple/record fields.
        * **An ellipsis** (either the Python `Ellipsis` object or the
          `...` syntax) skips as many dimensions as needed to put the
          rest of the slice items to the innermost dimensions.
        * **A np.newaxis** or its equivalent, None, does not select items
          but introduces a new regular dimension in the output with size
          `1`. This is a convenient way to explicitly choose a dimension
          for broadcasting.
        * **A boolean array** with the same length as the current dimension
          (or any iterable, other than the top-level tuple) selects elements
          corresponding to each True value in the array, dropping those
          that correspond to each False. The behavior is similar to
          NumPy's
          [compress](https://docs.scipy.org/doc/numpy/reference/generated/numpy.compress.html)
          function.
        * **An integer array** (or any iterable, other than the top-level
          tuple) selects elements like a single integer, but produces a
          regular dimension of as many as are desired. The array can have
          any length, any order, and it can have duplicates and incomplete
          coverage. The behavior is similar to NumPy's
          [take](https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html)
          function.
        * **An integer Array with missing (None) items** selects multiple
          values by index, as above, but None values are passed through
          to the output. This behavior matches pyarrow's
          [Array.take](https://arrow.apache.org/docs/python/generated/pyarrow.Array.html#pyarrow.Array.take)
          which also manages arrays with missing values. See
          <<<option indexing>>> below.
        * **An Array of nested lists**, ultimately containing booleans or
          integers and having the same lengths of lists at each level as
          the Array to which they're applied, selects by boolean or by
          integer at the deeply nested level. Missing items at any level
          above the deepest level must broadcast. See <<<nested indexing>>> below.

        A tuple of the above applies each slice item to a dimension of the
        data, which can be very expressive. More than one flat boolean/integer
        array are "iterated as one" as described in the
        [NumPy documentation](https://numpy.org/doc/stable/user/basics.indexing.html#integer-array-indexing).

        Filtering
        *********

        A common use of selection by boolean arrays is to filter a dataset by
        some property. For instance, to get the odd values of

            >>> array = ak.Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

        one can put an array expression with True for each odd value inside
        square brackets:

            >>> array[array % 2 == 1]
            <Array [1, 3, 5, 7, 9] type='5 * int64'>

        This technique is so common in NumPy and Pandas data analysis that it
        is often read as a syntax, rather than a consequence of array slicing.

        The extension to nested arrays like

            >>> array = ak.Array([[[0, 1, 2], [], [3, 4], [5]], [[6, 7, 8], [9]]])

        allows us to use the same syntax more generally.

            >>> array[array % 2 == 1]
            <Array [[[1], [], [3], [5]], [[7], [9]]] type='2 * var * var * int64'>

        In this example, the boolean array is itself nested (see
        <<<nested indexing>>> below).

            >>> array % 2 == 1
            <Array [[[False, True, False], ..., [True]], ...] type='2 * var * var * bool'>

        This also applies to data with record structures.

        For nested data, we often need to select the first or first two
        elements from variable-length lists. That can be a problem if some
        lists are empty. A function like #ak.num can be useful for first
        selecting by the lengths of lists.

            >>> array = ak.Array([[1.1, 2.2, 3.3],
            ...                   [],
            ...                   [4.4, 5.5],
            ...                   [6.6],
            ...                   [],
            ...                   [7.7, 8.8, 9.9]])
            ...
            >>> array[ak.num(array) > 0, 0]
            <Array [1.1, 4.4, 6.6, 7.7] type='4 * float64'>
            >>> array[ak.num(array) > 1, 1]
            <Array [2.2, 5.5, 8.8] type='3 * float64'>

        It's sometimes also a problem that "cleaning" the dataset by dropping
        empty lists changes its alignment, so that it can no longer be used
        in calculations with "uncleaned" data. For this, #ak.mask can be
        useful because it inserts None in positions that fail the filter,
        rather than removing them.

            >>> ak.mask(array, ak.num(array) > 1)
            <Array [[1.1, 2.2, 3.3], ..., [7.7, ..., 9.9]] type='6 * option[var * float64]'>

        Note, however, that the `0` or `1` to pick the first or second
        item of each nested list is in the second dimension, so the first
        dimension of the slice must be a `:`.

            >>> ak.mask(array, ak.num(array) > 1)[:, 0]
            <Array [1.1, None, 4.4, None, None, 7.7] type='6 * ?float64'>
            >>> ak.mask(array, ak.num(array) > 1)[:, 1]
            <Array [2.2, None, 5.5, None, None, 8.8] type='6 * ?float64'>

        Another syntax for

            ak.mask(array, array_of_booleans)

        is

            array.mask[array_of_booleans]

        (which is 5 characters away from simply filtering the `array`).

        Projection
        **********

        The following

            >>> array = ak.Array([[{"x": 1.1, "y": [1]}, {"x": 2.2, "y": [2, 2]}],
            ...                   [{"x": 3.3, "y": [3, 3, 3]}],
            ...                   [{"x": 0, "y": []}, {"x": 1.1, "y": [1, 1, 1]}]])

        has records inside of nested lists:

            >>> array.type.show()
            3 * var * {
                x: float64,
                y: var * int64
            }

        In principle, one should select nested lists before record fields,

            >>> array[2, :, "x"]
            <Array [0, 1.1] type='2 * float64'>
            >>> array[::2, :, "x"]
            <Array [[1.1, 2.2], [0, 1.1]] type='2 * var * float64'>

        but it's also possible to select record fields first.

            >>> array["x"]
            <Array [[1.1, 2.2], [3.3], [0, 1.1]] type='3 * var * float64'>

        The string can "commute" to the left through integers and slices to
        get the same result as it would in its "natural" position.

            >>> array[2, :, "x"]
            <Array [0, 1.1] type='2 * float64'>
            >>> array[2, "x", :]
            <Array [0, 1.1] type='2 * float64'>
            >>> array["x", 2, :]
            <Array [0, 1.1] type='2 * float64'>

        The is analogous to selecting rows (integer indexes) before columns
        (string names) or columns before rows, except that the rows are
        more complex (like a Pandas
        [MultiIndex](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html)).
        This would be an expensive operation in a typical object-oriented
        environment, in which the records with fields `"x"` and `"y"` are
        akin to C structs, but for columnar Awkward Arrays, projecting
        through all records to produce an array of nested lists of `"x"`
        values just changes the metadata (no loop over data, and therefore
        fast).

        Thus, data analysts should think of records as fluid objects that
        can be easily projected apart and zipped back together with
        #ak.zip.

        Note, however, that while a column string can "commute" with row
        indexes to the left of its position in the tree, it can't commute
        to the right. For example, it's possible to use slices inside
        `"y"` because `"y"` is a list:

            >>> array[0, :, "y"]
            <Array [[1], [2, 2]] type='2 * var * int64'>
            >>> array[0, :, "y", 0]
            <Array [1, 2] type='2 * int64'>

        but it's not possible to move `"y"` to the right

            >>> array[0, :, 0, "y"]
            IndexError: while attempting to slice
                <Array [[{x: 1.1, y: [1]}, {...}], ...] type='3 * var * {x: float64, y:...'>
            with
                (0, :, 0, 'y')
            at inner NumpyArray of length 2, using sub-slice (0).

        because the `array[0, :, 0, ...]` slice applies to both `"x"` and
        `"y"` before `"y"` is selected, and `"x"` is a one-dimensional
        NumpyArray that can't take more than its share of slices.

        Finally, note that the dot (`__getattr__`) syntax is equivalent to a single
        string in a slice (`__getitem__`) if the field name is a valid Python
        identifier and doesn't conflict with #ak.Array methods or properties.

            >>> array.x
            <Array [[1.1, 2.2], [3.3], [0, 1.1]] type='3 * var * float64'>
            >>> array.y
            <Array [[[1], [2, 2]], ..., [[], [1, ...]]] type='3 * var * var * int64'>

        Nested Projection
        *****************

        If records are nested within records, you can use a series of strings in
        the selector to drill down. For instance, with the following

            >>> array = ak.Array([
            ...     {"a": {"x": 1, "y": 2}, "b": {"x": 10, "y": 20}, "c": {"x": 1.1, "y": 2.2}},
            ...     {"a": {"x": 1, "y": 2}, "b": {"x": 10, "y": 20}, "c": {"x": 1.1, "y": 2.2}},
            ...     {"a": {"x": 1, "y": 2}, "b": {"x": 10, "y": 20}, "c": {"x": 1.1, "y": 2.2}}])

        we can go directly to the numerical data by specifying a string for the
        outer field and a string for the inner field.

            >>> array["a", "x"]
            <Array [1, 1, 1] type='3 * int64'>
            >>> array["a", "y"]
            <Array [2, 2, 2] type='3 * int64'>
            >>> array["b", "y"]
            <Array [20, 20, 20] type='3 * int64'>
            >>> array["c", "y"]
            <Array [2.2, 2.2, 2.2] type='3 * float64'>

        As with single projections, the dot (`__getattr__`) syntax is equivalent
        to a single string in a slice (`__getitem__`) if the field name is a valid
        Python identifier and doesn't conflict with #ak.Array methods or properties.

            >>> array.a.x
            <Array [1, 1, 1] type='3 * int64'>

        You can even get every field of the same name within an outer record using
        a list of field names for the outer record. The following selects the `"x"`
        field of `"a"`, `"b"`, and `"c"` records:

            >>> array[["a", "b", "c"], "x"].show()
            [{a: 1, b: 10, c: 1.1},
             {a: 1, b: 10, c: 1.1},
             {a: 1, b: 10, c: 1.1}]

        You don't need to get all fields:

            >>> array[["a", "b"], "x"].show()
            [{a: 1, b: 10},
             {a: 1, b: 10},
             {a: 1, b: 10}]

        And you can select lists of field names at all levels:

            >>> array[["a", "b"], ["x", "y"]].show()
            [{a: {x: 1, y: 2}, b: {x: 10, y: 20}},
             {a: {x: 1, y: 2}, b: {x: 10, y: 20}},
             {a: {x: 1, y: 2}, b: {x: 10, y: 20}}]

        Option indexing
        ***************

        NumPy arrays can be sliced by all of the above slice types except
        arrays with missing values and arrays with nested lists, both of
        which are inexpressible in NumPy. Missing values, represented by
        None in Python, are called option types (#ak.types.OptionType) in
        Awkward Array and can be used as a slice.

        For example,

            >>> array = ak.Array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])

        can be sliced with a boolean array

            >>> array[[False, False, False, False, True, False, True, False, True]]
            <Array [5.5, 7.7, 9.9] type='3 * float64'>

        or a boolean array containing None values:

            >>> array[[False, False, False, False, True, None, True, None, True]]
            <Array [5.5, None, 7.7, None, 9.9] type='5 * ?float64'>

        Similarly for arrays of integers and None:

            >>> array[[0, 1, None, None, 7, 8]]
            <Array [1.1, 2.2, None, None, 8.8, 9.9] type='6 * ?float64'>

        This is the same behavior as pyarrow's
        [Array.take](https://arrow.apache.org/docs/python/generated/pyarrow.Array.html#pyarrow.Array.take),
        which establishes a convention for how to interpret slice arrays
        with option type:

            >>> import pyarrow as pa
            >>> array = pa.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
            >>> array.take(pa.array([0, 1, None, None, 7, 8]))
            <pyarrow.lib.DoubleArray object at 0x7efc7f060210>
            [
              1.1,
              2.2,
              null,
              null,
              8.8,
              9.9
            ]

        Nested indexing
        ***************

        Awkward Array's nested lists can be used as slices as well, as long
        as the type at the deepest level of nesting is boolean or integer.

        For example,

            >>> array = ak.Array([[[0.0, 1.1, 2.2], [], [3.3, 4.4]], [], [[5.5]]])

        can be sliced at the top level with one-dimensional arrays:

            >>> array[[False, True, True]]
            <Array [[], [[5.5]]] type='2 * var * var * float64'>
            >>> array[[1, 2]]
            <Array [[], [[5.5]]] type='2 * var * var * float64'>

        with singly nested lists:

            >>> array[[[False, True, True], [], [True]]]
            <Array [[[], [3.3, 4.4]], [], [[5.5]]] type='3 * var * var * float64'>
            >>> array[[[1, 2], [], [0]]]
            <Array [[[], [3.3, 4.4]], [], [[5.5]]] type='3 * var * var * float64'>

        and with doubly nested lists:

            >>> array[[[[False, True, False], [], [True, False]], [], [[False]]]]
            <Array [[[1.1], [], [3.3]], [], [[]]] type='3 * var * var * float64'>
            >>> array[[[[1], [], [0]], [], [[]]]]
            <Array [[[1.1], [], [3.3]], [], [[]]] type='3 * var * var * float64'>

        The key thing is that the nested slice has the same number of elements
        as the array it's slicing at every level of nesting that it reproduces.
        This is similar to the requirement that boolean arrays have the same
        length as the array they're filtering.

        This kind of slicing is useful because NumPy's
        [universal functions](https://docs.scipy.org/doc/numpy/reference/ufuncs.html)
        produce arrays with the same structure as the original array, which
        can then be used as filters.

            >>> ((array * 10) % 2 == 1).show()
            [[[False, True, False], [], [True, False]],
             [],
             [[True]]]
            >>> (array[(array * 10) % 2 == 1]).show()
            [[[1.1], [], [3.3]],
             [],
             [[5.5]]]

        Functions whose names start with "arg" return index positions, which
        can be used with the integer form.

            >>> np.argmax(array, axis=-1).show()
            [[2, None, 1],
             [],
             [0]]
            >>> array[np.argmax(array, axis=-1)].show()
            [[[3.3, 4.4], None, []],
             [],
             [[5.5]]]

        Here, the `np.argmax` returns the integer position of the maximum
        element or None for empty arrays. It's a nice example of
        <<<option indexing>>> with <<<nested indexing>>>.

        When applying a nested index with missing (None) entries at levels
        higher than the last level, the indexer must have the same dimension
        as the array being indexed, and the resulting output will have missing
        entries at the corresponding locations, e.g. for

            >>> array[ [[[0, None, 2, None, None], None, [1]], None, [[0]]] ].show()
            [[[0, None, 2.2, None, None], None, [4.4]],
             None,
             [[5.5]]]

        the sub-list at entry 0,0 is extended as the masked entries are
        acting at the last level, while the higher levels of the indexer all
        have the same dimension as the array being indexed.
        """
        with ak._errors.SlicingErrorContext(self, where):
            # Handle named axis
            (_, ndim) = self._layout.minmax_depth
            named_axis = _get_named_axis(self)
            where = _normalize_named_slice(named_axis, where, ndim)

            NamedAxis.mapping = named_axis

            indexed_layout = prepare_layout(self._layout._getitem(where, NamedAxis))

            if NamedAxis.mapping:
                return ak.operations.ak_with_named_axis._impl(
                    indexed_layout,
                    named_axis=NamedAxis.mapping,
                    highlevel=True,
                    behavior=self._behavior,
                    attrs=self._attrs,
                )
            else:
                return ak.operations.ak_without_named_axis._impl(
                    indexed_layout,
                    highlevel=True,
                    behavior=self._behavior,
                    attrs=self._attrs,
                )

    def __bytes__(self) -> bytes:
        if isinstance(self._layout, ak.contents.NumpyArray) and self._layout.parameter(
            "__array__"
        ) in {"byte", "char"}:
            return ak._util.tobytes(self._layout.data)
        else:
            return bytes(iter(self))

    def __setitem__(self, where, what):
        """
        Args:
            where (str or tuple of str): Field name to add to records in the array.
            what (#ak.Array): Array to add as the new field.

        Unlike #__getitem__, which allows a wide variety of slice types,
        only single field-slicing is supported for assignment.
        (#ak.contents.Content arrays are immutable; field assignment replaces
        the #layout with an array that has the new field using #ak.with_field.)

        However, a field can be assigned deeply into a nested record e.g.

            >>> nested = ak.zip({"a" : ak.zip({"x" : [1, 2, 3]})})
            >>> nested["a", "y"] = 2 * nested.a.x
            >>> nested.show()
            [{a: {x: 1, y: 2}},
             {a: {x: 2, y: 4}},
             {a: {x: 3, y: 6}}]

        Note that the following does **not** work:

            >>> nested["a"]["y"] = 2 * nested.a.x # does not work, nested["a"] is a copy!

        Always assign by passing the whole path to the top level

            >>> nested["a", "y"] = 2 * nested.a.x

        If necessary, the new field will be broadcasted to fit the array.
        For example, given

            >>> array = ak.Array([
            ...     [{"x": 1.1}, {"x": 2.2}, {"x": 3.3}], [], [{"x": 4.4}, {"x": 5.5}]
            ... ])

        which has three elements with nested data in each, assigning

            >>> array["y"] = [100, 200, 300]

        will result in

            >>> array.show()
            [[{x: 1.1, y: 100}, {x: 2.2, y: 100}, {x: 3.3, y: 100}],
             [],
             [{x: 4.4, y: 300}, {x: 5.5, y: 300}]]

        because the `100` in `what[0]` is broadcasted to all three nested
        elements of `array[0]`, the `200` in `what[1]` is broadcasted to the
        empty list `array[1]`, and the `300` in `what[2]` is broadcasted to
        both elements of `array[2]`.

        See #ak.with_field for a variant that does not change the #ak.Array
        in-place. (Internally, this method uses #ak.with_field, so performance
        is not a factor in choosing one over the other.)
        """
        with ak._errors.OperationErrorContext(
            "ak.Array.__setitem__",
            (self,),
            {"where": where, "what": what},
        ):
            if not (
                isinstance(where, str)
                or (isinstance(where, tuple) and all(isinstance(x, str) for x in where))
            ):
                raise TypeError("only fields may be assigned in-place (by field name)")

            # make the property setting explicit (it triggers self._update_class(), which in turn triggers validation)
            self.layout = ak.operations.with_field(
                self.layout,
                what,
                where,
                highlevel=False,
                attrs=self._attrs,
                behavior=self._behavior,
            )

    def __delitem__(self, where):
        """
        Args:
            where (str or tuple of str): Field name to remove from the array.

        For example:

            >>> array = ak.Array([{"x": 3.3, "y": {"this": 10, "that": 20}}])
            >>> del array["y", "that"]
            >>> array.show()
            [{x: 3.3, y: {this: 10}}]

        See #ak.without_field for a variant that does not change the #ak.Array
        in-place. (Internally, this method uses #ak.without_field, so performance
        is not a factor in choosing one over the other.)
        """
        with ak._errors.OperationErrorContext(
            "ak.Array.__delitem__",
            (self,),
            {"where": where},
        ):
            if not (
                isinstance(where, str)
                or (isinstance(where, tuple) and all(isinstance(x, str) for x in where))
            ):
                raise TypeError("only fields may be removed in-place (by field name)")

            # make the property setting explicit (it triggers self._update_class(), which in turn triggers validation)
            self.layout = ak.operations.ak_without_field._impl(
                self.layout,
                where,
                highlevel=False,
                behavior=self._behavior,
                attrs=self._attrs,
            )

    def __getattr__(self, where):
        """
        Args:
            where (str): Attribute name to lookup

        Whenever possible, fields can be accessed as attributes.

        For example, the fields of

            >>> array = ak.Array([
            ...     [{"x": 1.1, "y": [1]}, {"x": 2.2, "y": [2, 2]}, {"x": 3.3, "y": [3, 3, 3]}],
            ...     [],
            ...     [{"x": 4.4, "y": [4, 4, 4, 4]}, {"x": 5.5, "y": [5, 5, 5, 5, 5]}]
            ... ])

        can be accessed as

            >>> array.x
            <Array [[1.1, 2.2, 3.3], [], [4.4, 5.5]] type='3 * var * float64'>
            >>> array.y
            <Array [[[1], [2, 2], [3, 3, 3]], [], [...]] type='3 * var * var * int64'>

        which are equivalent to `array["x"]` and `array["y"]`. (See
        <<<projection>>>.)

        Fields can't be accessed as attributes when

        * #ak.Array methods or properties take precedence,
        * a domain-specific behavior has methods or properties that take
             precedence, or
        * the field name is not a valid Python identifier or is a Python
             keyword.

        Note that while fields can be accessed as attributes, they cannot be
        *assigned* as attributes. See #ak.Array.__setitem__ for more.
        """
        if hasattr(type(self), where):
            return super().__getattribute__(where)
        else:
            if where in self._layout.fields:
                try:
                    return self[where]
                except Exception as err:
                    raise AttributeError(
                        f"while trying to get field {where!r}, an exception "
                        f"occurred:\n{type(err)}: {err!s}"
                    ) from err
            else:
                raise AttributeError(f"no field named {where!r}")

    def __setattr__(self, name, value):
        """
        Args:
            where (str): Attribute name to set

        Set an attribute on the array.

        Only existing public attributes e.g. #ak.Array.layout, or private
        attributes (with leading underscores), can be set.

        Fields are not assignable to as attributes, i.e. the following doesn't work:

            array.z = new_field

        Instead, always use #ak.Array.__setitem__:

            array["z"] = new_field

        or #ak.with_field:

            array = ak.with_field(array, new_field, "z")

        to add or modify a field.
        """
        if name.startswith("_") or hasattr(type(self), name):
            super().__setattr__(name, value)
        elif name in self._layout.fields:
            raise AttributeError(
                "fields cannot be set as attributes. use #__setitem__ or #ak.with_field"
            )
        else:
            raise AttributeError(
                "only private attributes (started with an underscore) can be set on arrays"
            )

    def __dir__(self):
        """
        Lists all methods, properties, and field names (see #__getattr__)
        that can be accessed as attributes.
        """
        return sorted(
            set(
                [x for x in dir(type(self)) if not x.startswith("_")]
                + dir(super())
                + [
                    x
                    for x in self._layout.fields
                    if _dir_pattern.match(x) and not keyword.iskeyword(x)
                ]
            )
        )

    def __str__(self):
        return prettyprint_valuestr(self, 1, 80)

    def __repr__(self):
        return self._repr(80)

    def _repr(self, limit_cols):
        try:
            pytype = super().__getattribute__("__name__")
        except AttributeError:
            pytype = type(self).__name__

        typestr = repr(str(self.type))[1:-1]
        if self._layout.backend.nplike.known_data:
            valuestr = ""
        else:
            valuestr = "-typetracer"

        # prepare named_axis str for repr
        axisstr = ""
        if self.named_axis:
            # we reserve at maximum 20 characters for the named axis string
            axisstr = _prettify_named_axes(self.named_axis, delimiter=",", maxlen=20)
            axisstr = f" {axisstr}"
        # subtract the reserved space from the limit_cols
        limit_cols -= len(axisstr)

        if len(typestr) + len(pytype) + len(" type=''") + 3 < limit_cols // 2:
            strwidth = limit_cols - (len(typestr) + len(pytype) + len(" type=''") + 3)
        else:
            strwidth = max(
                0,
                min(
                    limit_cols // 2,
                    limit_cols - len(pytype) - len(" type='...'") - 3,
                ),
            )
        valuestr = valuestr + " " + prettyprint_valuestr(self, 1, strwidth)

        length = max(3, limit_cols - len(pytype) - len("type='...'") - len(valuestr))
        if len(typestr) > length:
            typestr = "'" + typestr[: length - 3] + "...'"
        else:
            typestr = "'" + typestr + "'"

        return f"<{pytype}{valuestr}{axisstr} type={typestr}>"

    def show(
        self,
        limit_rows=20,
        limit_cols=80,
        *,
        type=False,
        named_axis=False,
        nbytes=False,
        backend=False,
        all=False,
        stream=STDOUT,
        formatter=None,
        precision=3,
    ):
        """
        Args:
            limit_rows (int): Maximum number of rows (lines) to use in the output.
            limit_cols (int): Maximum number of columns (characters wide).
            type (bool): If True, print the type as well. (Doesn't count toward number
                of rows/lines limit.)
            named_axis (bool): If True, print the named axis as well. (Doesn't count toward number
                of rows/lines limit.)
            nbytes (bool): If True, print the number of bytes as well. (Doesn't count toward number
                of rows/lines limit.)
            backend (bool): If True, print the backend of the array as well. (Doesn't count toward number
                of rows/lines limit.)
            all (bool): If True, print the 'type', 'named axis', 'nbytes', and 'backend' of the array. (Doesn't count toward number
                of rows/lines limit.)
            stream (object with a ``write(str)`` method or None): Stream to write the
                output to. If None, return a string instead of writing to a stream.
            formatter (Mapping or None): Mapping of types/type-classes to string formatters.
                If None, use the default formatter.

        Display the contents of the array within `limit_rows` and `limit_cols`, using
        ellipsis (`...`) for hidden nested data.

        The `formatter` argument controls the formatting of individual values, c.f.
        https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html
        As Awkward Array does not implement strings as a NumPy dtype, the `numpystr`
        key is ignored; instead, a `"bytes"` and/or `"str"` key is considered when formatting
        string values, falling back upon `"str_kind"`.
        """
        rows = highlevel_array_show_rows(
            array=self,
            limit_rows=limit_rows,
            limit_cols=limit_cols,
            type=type or all,
            named_axis=named_axis or all,
            nbytes=nbytes or all,
            backend=backend or all,
            formatter=formatter,
            precision=precision,
        )
        array_line = rows.pop(0)

        out_io = io.StringIO()
        if type:
            # it's always the second row (after the array)
            type_line = rows.pop(0)
            out_io.write(type_line)
            out_io.write("\n")

        # the rest of the rows we sort by the length of their '<prefix>:'
        # but we sort it from shortest to longest contrary to _repr_mimebundle_
        sorted_rows = sorted([r for r in rows if r], key=lambda x: len(x.split(":")[0]))

        if sorted_rows:
            out_io.write("\n".join(sorted_rows))
            out_io.write("\n")

        out_io.write(array_line)
        if stream is None:
            return out_io.getvalue()
        else:
            if stream is STDOUT:
                stream = STDOUT.stream
            stream.write(out_io.getvalue() + "\n")

    def _repr_mimebundle_(self, include=None, exclude=None):
        # order:
        # first: array,
        # last: type,
        # middle: rest sorted by length of prefix (longest first)

        rows = highlevel_array_show_rows(
            array=self,
            type=True,
            named_axis=True,
            nbytes=True,
            backend=True,
        )
        header_lines = rows.pop(0).removesuffix("\n").splitlines()

        # it's always the second row (after the array)
        type_lines = rows.pop(0).removesuffix("\n").splitlines()
        # some reasonable number (2 for beginning and end + 10 fields -> 12)
        if len(type_lines) > 12:
            n_white_spaces = len(type_lines[1]) - len(type_lines[1].lstrip())
            type_lines = [
                type_lines[0],
                *type_lines[1:11],
                n_white_spaces * " " + "...",
                type_lines[-1],
            ]

        # the rest of the rows we sort by the length of their '<prefix>:'
        # but we sort it from longest to shortest for _repr_mimebundle_
        sorted_rows = sorted(rows, key=lambda x: -len(x.split(":")[0]))

        n_cols = max(map(len, header_lines), default=0)
        body_lines = header_lines
        body_lines.append("-" * n_cols)
        body_lines.extend(sorted_rows)
        body_lines.extend(type_lines)
        body = "\n".join(body_lines)

        return {
            "text/html": f"<pre>{html.escape(body)}</pre>",
            "text/plain": repr(self),
        }

    def __array__(self, dtype=None, copy=None):
        """
        Intercepts attempts to convert this Array into a NumPy array and
        either performs a conversion if possible or raises an error.
        The array may be copied depending on the values of `dtype` and `copy`.
        The rules for copying are specified in the
        [np.asarray](https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html)
        documentation.

        This function is also called by the
        [np.asarray](https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html)
        family of functions, which have `copy=False` by default.

            >>> np.asarray(ak.Array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]))
            array([[1.1, 2.2, 3.3],
                   [4.4, 5.5, 6.6]])

        If the data are numerical and regular (nested lists have equal lengths
        in each dimension, as described by the #type), they can be losslessly
        converted to a NumPy array and this function returns without an error.

        Otherwise, the function raises an error. It does not create a NumPy
        array with dtype `"O"` for `np.object_` (see the
        [note on object_ type](https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in))
        since silent conversions to dtype `"O"` arrays would not only be a
        significant performance hit, but would also break functionality, since
        nested lists in a NumPy `"O"` array are severed from the array and
        cannot be sliced as dimensions.
        """
        with ak._errors.OperationErrorContext(
            "numpy.asarray", (self,), {"dtype": dtype, "copy": copy}
        ):
            from awkward._connect.numpy import convert_to_array

            return convert_to_array(self._layout, dtype=dtype, copy=copy)

    def __arrow_array__(self, type=None):
        with ak._errors.OperationErrorContext(
            f"{builtins.type(self).__name__}.__arrow_array__", (self,), {"type": type}
        ):
            from awkward._connect.pyarrow import convert_to_array

            return convert_to_array(self._layout, type=type)

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        """
        Intercepts attempts to pass this Array to a NumPy
        [universal functions](https://docs.scipy.org/doc/numpy/reference/ufuncs.html)
        (ufuncs) and passes it through the Array's structure.

        This method conforms to NumPy's
        [NEP 13](https://numpy.org/neps/nep-0013-ufunc-overrides.html)
        for overriding ufuncs, which has been
        [available since NumPy 1.13](https://numpy.org/devdocs/release/1.13.0-notes.html#array-ufunc-added)
        (and thus NumPy 1.13 is the minimum allowed version).

        When any ufunc is applied to an Awkward Array, it applies to the
        innermost level of structure and preserves the structure through the
        operation.

        For example, with

            >>> array = ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]])

        applying `np.sqrt` would yield

            >>> np.sqrt(array).show()
            [[1.05, 1.48, 1.82],
             [],
             [2.1, 2.35]]

        In addition, many unary and binary operators implicitly call ufuncs,
        such as `np.power` in

            >>> (array**2).show()
            [[1.21, 4.84, 10.9],
             [],
             [19.4, 30.2]]

        In the above example, `array` is a nested list of records and `2` is
        a scalar. Awkward Array applies the same broadcasting rules as NumPy
        plus a few more to deal with nested structures. In addition to
        broadcasting a scalar, as above, it is possible to broadcast
        arrays with less depth into arrays with more depth, such as

            >>> (array + ak.Array([10, 20, 30])).show()
            [[11.1, 12.2, 13.3],
             [],
             [34.4, 35.5]]

        See #ak.broadcast_arrays for details about broadcasting and the
        generalized set of broadcasting rules.

        Third party libraries can create ufuncs, not just NumPy, so any library
        that "plays well" with the NumPy ecosystem can be used with Awkward
        Arrays:

            >>> import numba as nb
            >>> @nb.vectorize([nb.float64(nb.float64)])
            ... def sqr(x):
            ...     return x * x
            ...
            >>> sqr(array).show()
            [[1.21, 4.84, 10.9],
             [],
             [19.4, 30.2]]

        See also #__array_function__.
        """
        name = f"{type(ufunc).__module__}.{ufunc.__name__}.{method!s}"
        with ak._errors.OperationErrorContext(name, inputs, kwargs):
            return ak._connect.numpy.array_ufunc(ufunc, method, inputs, kwargs)

    def __array_function__(self, func, types, args, kwargs):
        """
        Intercepts attempts to pass this Array to those NumPy functions other
        than universal functions that have an Awkward equivalent.

        This method conforms to NumPy's
        [NEP 18](https://numpy.org/neps/nep-0018-array-function-protocol.html)
        for overriding functions, which has been
        [available since NumPy 1.17](https://numpy.org/devdocs/release/1.17.0-notes.html#numpy-functions-now-always-support-overrides-with-array-function)
        (and
        [NumPy 1.16 with an experimental flag set](https://numpy.org/devdocs/release/1.16.0-notes.html#numpy-functions-now-support-overrides-with-array-function)).

        See also #__array_ufunc__.
        """
        return ak._connect.numpy.array_function(
            func, types, args, kwargs, behavior=self._behavior, attrs=self._attrs
        )

    @non_inspectable_property
    def numba_type(self):
        """
        The type of this Array when it is used in Numba. It contains enough
        information to generate low-level code for accessing any element,
        down to the leaves.

        See [Numba documentation](https://numba.pydata.org/numba-doc/dev/reference/types.html)
        on types and signatures.
        """
        ak.numba.register_and_check()

        if self._numbaview is None:
            self._numbaview = ak._connect.numba.arrayview.ArrayView.fromarray(self)
        import numba

        return numba.typeof(self._numbaview)

    def __reduce_ex__(self, protocol: int) -> tuple:
        result = custom_reduce(self, protocol)
        if result is not NotImplemented:
            return result

        packed_layout = ak.operations.to_packed(self._layout, highlevel=False)
        form, length, container = ak.operations.to_buffers(
            packed_layout,
            buffer_key="{form_key}-{attribute}",
            form_key="node{id}",
            byteorder="<",
        )

        # For pickle >= 5, we can avoid copying the buffers
        if protocol >= 5:
            container = {k: pickle.PickleBuffer(v) for k, v in container.items()}

        if self._behavior is ak.behavior:
            behavior = None
        else:
            behavior = self._behavior

        if self._attrs is None:
            attrs = self._attrs
        else:
            attrs = without_transient_attrs(self._attrs)

        return unpickle_array_schema_1, (
            form.to_dict(),
            length,
            container,
            behavior,
            attrs,
        )

    def __setstate__(self, state):
        form, length, container, behavior, *_ = state
        # If length is a sequence, we have awkward1
        if isinstance(length, Sequence):
            part_layouts = [
                # Load partition
                ak.operations.from_buffers(
                    _awkward_1_rewrite_partition_form(form, i),
                    part_length,
                    container,
                    highlevel=False,
                    buffer_key="{form_key}-{attribute}",
                    byteorder="<",
                )
                for i, part_length in enumerate(length)
            ]

            # Fuse partitions
            layout = ak.concatenate(part_layouts, axis=0, highlevel=False)
        # Otherwise, we have either awkward1 or awkward2
        else:
            layout = ak.operations.from_buffers(
                form,
                length,
                container,
                highlevel=False,
                buffer_key="{form_key}-{attribute}",
                byteorder="<",
            )
        self._layout = layout
        self._behavior = behavior
        self._attrs = None

        self._update_class()

    def __copy__(self):
        return Array(self._layout, behavior=self._behavior, attrs=self._attrs)

    def __deepcopy__(self, memo):
        return Array(
            copy.deepcopy(self._layout, memo),
            behavior=copy.deepcopy(self._behavior, memo),
            attrs=copy.deepcopy(self._attrs, memo),
        )

    def __bool__(self):
        if len(self) == 1:
            return bool(self[0])
        else:
            raise ValueError(
                "the truth value of an array whose length is not 1 is ambiguous; "
                "use ak.any() or ak.all()"
            )

    @non_inspectable_property
    def cpp_type(self):
        """
        The C++ type of this Array when it is used in cppyy.

            cpp_type (None or str): Generated on demand when the Array needs to be passed
                to a C++ (possibly templated) function defined by a `cppyy` compiler.

        See [cppyy documentation](https://cppyy.readthedocs.io/en/latest/index.html)
        on types and signatures.
        """
        ak.cppyy.register_and_check()  # noqa: F823

        import cppyy

        import awkward._connect.cling  # noqa: F401

        if self._cpp_type is None:
            self._generator = ak._connect.cling.togenerator(
                self._layout.form, flatlist_as_rvec=False
            )
            self._lookup = ak._lookup.Lookup(self._layout)
            self._generator.generate(cppyy.cppdef)
            self._cpp_type = f"awkward::{self._generator.class_type()}"

        return self._cpp_type

    def __cast_cpp__(self):
        """
        The `__cast_cpp__` is called by cppyy to determine a C++ type of an `ak.Array`.
        It returns the C++ dataset type that is already registered with cppyy with the
        parameters needed to construct the C++ type of this Array when it is
        used in cppyy.
        """
        import cppyy

        if self._cpp_type is None:
            self._cpp_type = self.cpp_type

        return getattr(cppyy.gbl, self._cpp_type)(
            0, len(self), 0, self._lookup.arrayptrs, 0
        )


class Record(NDArrayOperatorsMixin):
    """
    Args:
        data (#ak.record.Record, #ak.Record, str, or dict):
            Data to wrap or convert into a record.
            If a string, the data are assumed to be JSON.
            If a dict, calls #ak.from_iter, which assumes all inner
            dimensions have irregular lengths.
        behavior (None or dict): Custom #ak.behavior for this Record only.
        with_name (None or str): Gives the record type a name that can be
            used to override its behavior (see below).
        check_valid (bool): If True, verify that the #layout is valid.
        backend (None, `"cpu"`, `"jax"`, `"cuda"`): If `"cpu"`, the Array will be placed in
            main memory for use with other `"cpu"` Arrays and Records; if `"cuda"`,
            the Array will be placed in GPU global memory using CUDA; if `"jax"`, the structure
            is copied to the CPU for use with JAX. if None, the `data` are left untouched.

    High-level record that can contain fields of any type.

    Most users won't be creating Records manually. This class primarily exists
    to be overridden in the same way as #ak.Array.

    Records can be used in [Numba](http://numba.pydata.org/): they can be
    passed as arguments to a Numba-compiled function or returned as return
    values. The only limitation is that they cannot be *created*
    inside the Numba-compiled function; to make outputs, consider
    #ak.ArrayBuilder.

    See also #ak.Array and #ak.behavior.
    """

    def __init__(
        self,
        data,
        *,
        behavior=None,
        with_name=None,
        check_valid=False,
        backend=None,
        attrs=None,
        named_axis=None,
    ):
        if isinstance(data, ak.record.Record):
            layout = data

        elif isinstance(data, Record):
            layout = data._layout
            attrs = data.attrs

        elif isinstance(data, str):
            layout = ak.operations.from_json(data, highlevel=False)

        elif isinstance(data, dict):
            fields = []
            contents = []
            for k, v in data.items():
                fields.append(k)
                # avoid dictionaries here, see issue #3723
                if (not isinstance(v, dict)) and is_non_string_like_iterable(v):
                    contents.append(Array(v).layout[np.newaxis])
                else:
                    contents.append(Array([v]).layout)

            layout = ak.record.Record(ak.contents.RecordArray(contents, fields), at=0)

        elif isinstance(data, Iterable):
            raise TypeError(
                "could not convert non-dict into an ak.Record; try ak.Array"
            )

        else:
            layout = None

        if not isinstance(layout, ak.record.Record):
            raise TypeError("could not convert data into an ak.Record")

        if with_name is not None:
            layout = ak.operations.with_name(layout, with_name, highlevel=False)

        if not (backend is None or backend == layout.backend.name):
            layout = ak.operations.to_backend(layout, backend, highlevel=False)

        if behavior is not None and not isinstance(behavior, Mapping):
            raise TypeError("behavior must be None or mapping")

        if attrs is not None and not isinstance(attrs, Mapping):
            raise TypeError("attrs must be None or a mapping")

        if named_axis:
            _named_axis = _prepare_named_axis_for_attrs(
                named_axis=named_axis,
                ndim=layout.minmax_depth[1],
            )
            # now we're good, set the named axis
            if attrs is None:
                attrs = {}
            # if NAMED_AXIS_KEY is already in attrs, it will be overwritten
            attrs[NAMED_AXIS_KEY] = _named_axis

        self._layout = layout
        self._behavior = behavior
        self._attrs = attrs

        docstr = layout.purelist_parameter("__doc__")
        if isinstance(docstr, str):
            self.__doc__ = docstr

        self._update_class()

        if check_valid:
            ak.operations.validity_error(self, exception=True)

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)

        ak.jax.register_behavior_class(cls)

    def _update_class(self):
        self._numbaview = None
        self.__class__ = get_record_class(self._layout, self._behavior)
        if hasattr(self, "__awkward_validation__"):
            self.__awkward_validation__()

    @property
    def attrs(self) -> Attrs:
        """
        The mapping containing top-level metadata, which is serialised
        with the record during pickling.

        Keys prefixed with `@` are identified as "transient" attributes
        which are discarded prior to pickling, permitting the storage of
        non-pickleable types.
        """
        if self._attrs is None:
            self._attrs = Attrs({})
        return self._attrs

    @attrs.setter
    def attrs(self, value: Mapping[str, Any]):
        if isinstance(value, Mapping):
            self._attrs = Attrs(value)
        else:
            raise TypeError("attrs must be a mapping")

    @property
    def layout(self):
        """
        The #ak.record.Record that contains composable #ak.contents.Content
        elements to determine how the array is structured.

        See #ak.Array.layout for a more complete description.

        The #ak.record.Record is not a subclass of #ak.contents.Content in
        Python and it is not composable with them: #ak.record.Record contains
        one #ak.contents.RecordArray (which is a #ak.contents.Content), but
        #ak.contents.Content nodes cannot contain a #ak.record.Record.

        A #ak.record.Record is not an independent entity from its
        #ak.contents.RecordArray; it's really just a marker indicating which
        element to select. The XML representation reflects that:

            >>> vectors = ak.Array([{"x": 0.1, "y": 1.0, "z": 30.0},
            ...                     {"x": 0.2, "y": 2.0, "z": 20.0},
            ...                     {"x": 0.3, "y": 3.0, "z": 10.0}])
            >>> vectors[1].layout
            <Record at='1'>
                <array><RecordArray is_tuple='false' len='3'>
                    <content index='0' field='x'>
                        <NumpyArray dtype='float64' len='3'>[0.1 0.2 0.3]</NumpyArray>
                    </content>
                    <content index='1' field='y'>
                        <NumpyArray dtype='float64' len='3'>[1. 2. 3.]</NumpyArray>
                    </content>
                    <content index='2' field='z'>
                        <NumpyArray dtype='float64' len='3'>[30. 20. 10.]</NumpyArray>
                    </content>
                </RecordArray></array>
            </Record>
        """
        return self._layout

    @layout.setter
    def layout(self, layout):
        if isinstance(layout, ak.record.Record):
            self._layout = layout
            self._update_class()
        else:
            raise TypeError("layout must be a subclass of ak.record.Record")

    @property
    def behavior(self):
        """
        The `behavior` parameter passed into this Record's constructor.

        * If a dict, this `behavior` overrides the global #ak.behavior.
             Any keys in the global #ak.behavior but not this `behavior` are
             still valid, but any keys in both are overridden by this
             `behavior`. Keys with a None value are equivalent to missing keys,
             so this `behavior` can effectively remove keys from the
             global #ak.behavior.

        * If None, the Record defaults to the global #ak.behavior.

        See #ak.behavior for a list of recognized key patterns and their
        meanings.
        """
        return self._behavior

    @behavior.setter
    def behavior(self, behavior):
        if behavior is None or isinstance(behavior, Mapping):
            self._behavior = behavior
            self._update_class()
        else:
            raise TypeError("behavior must be None or a dict")

    @property
    def positional_axis(self) -> tuple[int, ...]:
        (_, ndim) = self._layout.minmax_depth
        return _make_positional_axis_tuple(ndim)

    @property
    def named_axis(self) -> AxisMapping:
        return _get_named_axis(self)

    def tolist(self):
        """
        Converts this Record into Python objects; same as #ak.to_list
        (but without the underscore, like NumPy's
        [tolist](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html)).
        """
        return self.to_list()

    def to_list(self):
        """
        Converts this Record into Python objects; same as #ak.to_list.
        """
        return self._layout.to_list(self._behavior)

    @property
    def nbytes(self):
        """
        The total number of bytes in all the #ak.index.Index,
        and #ak.contents.NumpyArray buffers in this array tree.

        It does not count buffers that must be kept in memory because
        of ownership, but are not directly used in the array. Nor does it count
        the (small) Python objects that reference the (large)
        array buffers.
        """
        return self._layout.array.nbytes

    @property
    def fields(self):
        """
        List of field names or tuple slot numbers (as strings) of this record.

        If this is actually a tuple its fields are string representations of
        integers, such as `"0"`, `"1"`, `"2"`, etc.

        See also #ak.fields.
        """
        return self._layout.array.fields

    @property
    def is_tuple(self):
        """
        If True, the top-most record structure has no named fields, i.e. it's a tuple.
        """
        return self._layout.array.is_tuple

    def _ipython_key_completions_(self):
        return self._layout.array.fields

    # Disable iteration (and prevent old-style iteration from being used)
    __iter__ = None

    @property
    def type(self):
        """
        The high-level type of this Record; same as #ak.type.

        Note that the outermost element of a Record's type is always an
        #ak.types.ScalarType, which .

        The type of a #ak.record.Record (from #ak.Array.layout) is not
        wrapped by an #ak.types.ScalarType.
        """
        return ak.types.ScalarType(self._layout.array.form.type, self._behavior)

    @property
    def typestr(self):
        """
        The high-level type of this Record, presented as a string.
        """
        return str(self.type)

    def __getitem__(self, where):
        """
        Args:
            where (many types supported; see below): Index of positions to
                select from this Record.

        Select items from the Record using an extension of NumPy's (already
        quite extensive) rules.

        See #ak.Array.__getitem__ for a more complete description. Since
        this is a record, the first item in the slice tuple must be a
        string, selecting a field.

        For example, with

            >>> record = ak.Record({"x": 3.3, "y": [1, 2, 3]})

        we can select

            >>> record["x"]
            3.3
            >>> record["y"]
            <Array [1, 2, 3] type='3 * int64'>
            >>> record["y", 1]
            2
        """
        with ak._errors.SlicingErrorContext(self, where):
            return wrap_layout(
                prepare_layout(self._layout[where]),
                self._behavior,
                allow_other=True,
                attrs=self._attrs,
            )

    def __setitem__(self, where, what):
        """
        Args:
            where (str or tuple of str): Field name to add data to the record.
            what: Data to add as the new field.

        For example:

            >>> record = ak.Record({"x": 3.3})
            >>> record["y"] = 4
            >>> record["z"] = {"another": "record"}
            >>> record.show()
            {x: 3.3,
             y: 4,
             z: {another: 'record'}}

        See #ak.with_field for a variant that does not change the #ak.Record
        in-place. (Internally, this method uses #ak.with_field, so performance
        is not a factor in choosing one over the other.)
        """
        with ak._errors.OperationErrorContext(
            "ak.Record.__setitem__",
            (self,),
            {"where": where, "what": what},
        ):
            if not (
                isinstance(where, str)
                or (isinstance(where, tuple) and all(isinstance(x, str) for x in where))
            ):
                raise TypeError("only fields may be assigned in-place (by field name)")

            # make the property setting explicit (it triggers self._update_class(), which in turn triggers validation)
            layout = self.layout
            layout._array = ak.operations.ak_with_field._impl(
                layout._array,
                what,
                where,
                highlevel=False,
                behavior=self._behavior,
                attrs=self._attrs,
            )
            self.layout = layout

    def __delitem__(self, where):
        """
        Args:
            where (str or tuple of str): Field name to remove from the record.

        For example:

            >>> record = ak.Record({"x": 3.3, "y": {"this": 10, "that": 20}})
            >>> del record["y", "that"]
            >>> record.show()
            {x: 3.3,
             y: {this: 10}}

        See #ak.without_field for a variant that does not change the #ak.Record
        in-place. (Internally, this method uses #ak.without_field, so performance
        is not a factor in choosing one over the other.)
        """
        with ak._errors.OperationErrorContext(
            "ak.Record.__delitem__",
            (self,),
            {"where": where},
        ):
            if not (
                isinstance(where, str)
                or (isinstance(where, tuple) and all(isinstance(x, str) for x in where))
            ):
                raise TypeError("only fields may be removed in-place (by field name)")

            # make the property setting explicit (it triggers self._update_class(), which in turn triggers validation)
            self.layout = ak.operations.ak_without_field._impl(
                self.layout,
                where,
                highlevel=False,
                behavior=self._behavior,
                attrs=self._attrs,
            )

    def __getattr__(self, where):
        """
        Whenever possible, fields can be accessed as attributes.

        For example, the fields of

            >>> record = ak.Record({"x": 1.1, "y": [2, 2], "z": "three"})

        can be accessed as

            >>> record.x
            1.1
            >>> record.y
            <Array [2, 2] type='2 * int64'>
            >>> record.z
            'three'

        which are equivalent to `record["x"]`, `record["y"]`, and
        `record["z"]`.

        Fields can't be accessed as attributes when

        * #ak.Record methods or properties take precedence,
        * a domain-specific behavior has methods or properties that take
             precedence, or
        * the field name is not a valid Python identifier or is a Python
             keyword.
        """
        if hasattr(type(self), where):
            return super().__getattribute__(where)
        else:
            if where in self._layout.fields:
                try:
                    return self[where]
                except Exception as err:
                    raise AttributeError(
                        f"while trying to get field {where!r}, an exception "
                        f"occurred:\n{type(err)}: {err!s}"
                    ) from err
            else:
                raise AttributeError(f"no field named {where!r}")

    def __setattr__(self, name, value):
        """
        Args:
            where (str): Attribute name to set

        Set an attribute on the record.

        Only existing public attributes e.g. #ak.Record.layout, or private
        attributes (with leading underscores), can be set.

        Fields are not assignable to as attributes, i.e. the following doesn't work:

            record.z = new_field

        Instead, always use #ak.Record.__setitem__:

            record["z"] = new_field

        or #ak.with_field:

            record = ak.with_field(record, new_field, "z")

        to add or modify a field.
        """
        if name.startswith("_") or hasattr(type(self), name):
            super().__setattr__(name, value)
        elif name in self._layout.fields:
            raise AttributeError(
                "fields cannot be set as attributes. use #__setitem__ or #ak.with_field"
            )
        else:
            raise AttributeError(
                "only private attributes (started with an underscore) can be set on records"
            )

    def __dir__(self):
        """
        Lists all methods, properties, and field names (see #__getattr__)
        that can be accessed as attributes.
        """
        return sorted(
            set(
                [x for x in dir(type(self)) if not x.startswith("_")]
                + dir(super())
                + [
                    x
                    for x in self._layout.fields
                    if _dir_pattern.match(x) and not keyword.iskeyword(x)
                ]
            )
        )

    def __str__(self):
        return prettyprint_valuestr(self, 1, 80)

    def __repr__(self):
        return self._repr(80)

    def _repr(self, limit_cols):
        pytype = type(self).__name__

        typestr = repr(str(self.type))[1:-1]
        if self._layout.array.backend.nplike.known_data:
            valuestr = ""
        else:
            valuestr = "-typetracer"

        # prepare named_axis str for repr
        axisstr = ""
        if self.named_axis:
            # we reserve at maximum 20 characters for the named axis string
            axisstr = _prettify_named_axes(self.named_axis, delimiter=",", maxlen=20)
            axisstr = f" {axisstr}"
        # subtract the reserved space from the limit_cols
        limit_cols -= len(axisstr)

        if len(typestr) + len(pytype) + len(" type=''") + 3 < limit_cols // 2:
            strwidth = limit_cols - (len(typestr) + len(pytype) + len(" type=''") + 3)
        else:
            strwidth = max(
                0,
                min(
                    limit_cols // 2,
                    limit_cols - len(pytype) - len(" type='...'") - 3,
                ),
            )
        valuestr = valuestr + " " + prettyprint_valuestr(self, 1, strwidth)

        length = max(3, limit_cols - len(pytype) - len("type='...'") - len(valuestr))
        if len(typestr) > length:
            typestr = "'" + typestr[: length - 3] + "...'"
        else:
            typestr = "'" + typestr + "'"

        return f"<{pytype}{valuestr}{axisstr} type={typestr}>"

    def show(
        self,
        limit_rows=20,
        limit_cols=80,
        *,
        type=False,
        named_axis=False,
        nbytes=False,
        backend=False,
        all=False,
        stream=STDOUT,
        formatter=None,
        precision=3,
    ):
        """
        Args:
            limit_rows (int): Maximum number of rows (lines) to use in the output.
            limit_cols (int): Maximum number of columns (characters wide).
            type (bool): If True, print the type as well. (Doesn't count toward number
                of rows/lines limit.)
            named_axis (bool): If True, print the named axis as well. (Doesn't count toward number
                of rows/lines limit.)
            nbytes (bool): If True, print the number of bytes as well. (Doesn't count toward number
                of rows/lines limit.)
            backend (bool): If True, print the backend of the array as well. (Doesn't count toward number
                of rows/lines limit.)
            all (bool): If True, print the 'type', 'named axis', 'nbytes', and 'backend' of the array. (Doesn't count toward number
                of rows/lines limit.)
            stream (object with a ``write(str)`` method or None): Stream to write the
                output to. If None, return a string instead of writing to a stream.
            formatter (Mapping or None): Mapping of types/type-classes to string formatters.
                If None, use the default formatter.

        Display the contents of the record within `limit_rows` and `limit_cols`, using
        ellipsis (`...`) for hidden nested data.

        The `formatter` argument controls the formatting of individual values, c.f.
        https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html
        As Awkward Array does not implement strings as a NumPy dtype, the `numpystr`
        key is ignored; instead, a `"bytes"` and/or `"str"` key is considered when formatting
        string values, falling back upon `"str_kind"`.
        """
        rows = highlevel_array_show_rows(
            array=self,
            limit_rows=limit_rows,
            limit_cols=limit_cols,
            type=type or all,
            named_axis=named_axis or all,
            nbytes=nbytes or all,
            backend=backend or all,
            formatter=formatter,
            precision=precision,
        )
        array_line = rows.pop(0)

        out_io = io.StringIO()
        if type:
            # it's always the second row (after the array)
            type_line = rows.pop(0)
            out_io.write(type_line)
            out_io.write("\n")

        # the rest of the rows we sort by the length of their '<prefix>:'
        # but we sort it from shortest to longest contrary to _repr_mimebundle_
        sorted_rows = sorted([r for r in rows if r], key=lambda x: len(x.split(":")[0]))

        if sorted_rows:
            out_io.write("\n".join(sorted_rows))
            out_io.write("\n")

        out_io.write(array_line)
        if stream is None:
            return out_io.getvalue()
        else:
            if stream is STDOUT:
                stream = STDOUT.stream
            stream.write(out_io.getvalue() + "\n")

    def _repr_mimebundle_(self, include=None, exclude=None):
        # order:
        # first: array,
        # last: type,
        # middle: rest sorted by length of prefix (longest first)

        rows = highlevel_array_show_rows(
            array=self,
            type=True,
            named_axis=True,
            nbytes=True,
            backend=True,
        )
        header_lines = rows.pop(0).removesuffix("\n").splitlines()

        # it's always the second row (after the array)
        type_lines = rows.pop(0).removesuffix("\n").splitlines()
        # some reasonable number (2 for beginning and end + 10 fields -> 12)
        if len(type_lines) > 12:
            n_white_spaces = len(type_lines[1]) - len(type_lines[1].lstrip())
            type_lines = [
                type_lines[0],
                *type_lines[1:11],
                n_white_spaces * " " + "...",
                type_lines[-1],
            ]

        # the rest of the rows we sort by the length of their '<prefix>:'
        # but we sort it from longest to shortest for _repr_mimebundle_
        sorted_rows = sorted(rows, key=lambda x: -len(x.split(":")[0]))

        n_cols = max(map(len, header_lines), default=0)
        body_lines = header_lines
        body_lines.append("-" * n_cols)
        body_lines.extend(sorted_rows)
        body_lines.extend(type_lines)
        body = "\n".join(body_lines)

        return {
            "text/html": f"<pre>{html.escape(body)}</pre>",
            "text/plain": repr(self),
        }

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        """
        Intercepts attempts to pass this Record to a NumPy
        [universal functions](https://docs.scipy.org/doc/numpy/reference/ufuncs.html)
        (ufuncs) and passes it through the Record's structure.

        This method conforms to NumPy's
        [NEP 13](https://numpy.org/neps/nep-0013-ufunc-overrides.html)
        for overriding ufuncs, which has been
        [available since NumPy 1.13](https://numpy.org/devdocs/release/1.13.0-notes.html#array-ufunc-added)
        (and thus NumPy 1.13 is the minimum allowed version).

        See #ak.Array.__array_ufunc__ for a more complete description.
        """
        name = f"{type(ufunc).__module__}.{ufunc.__name__}.{method!s}"
        with ak._errors.OperationErrorContext(name, inputs, kwargs):
            return ak._connect.numpy.array_ufunc(ufunc, method, inputs, kwargs)

    @property
    def numba_type(self):
        """
        The type of this Record when it is used in Numba. It contains enough
        information to generate low-level code for accessing any element,
        down to the leaves.

        See [Numba documentation](https://numba.pydata.org/numba-doc/dev/reference/types.html)
        on types and signatures.
        """
        ak.numba.register_and_check()

        if self._numbaview is None:
            self._numbaview = ak._connect.numba.arrayview.RecordView.fromrecord(self)
        import numba

        return numba.typeof(self._numbaview)

    def __reduce_ex__(self, protocol: int) -> tuple:
        # Allow third-party libraries to customise pickling
        result = custom_reduce(self, protocol)
        if result is not NotImplemented:
            return result

        packed_layout = ak.operations.to_packed(self._layout, highlevel=False)
        form, length, container = ak.operations.to_buffers(
            packed_layout.array,
            buffer_key="{form_key}-{attribute}",
            form_key="node{id}",
            byteorder="<",
        )

        # For pickle >= 5, we can avoid copying the buffers
        if protocol >= 5:
            container = {k: pickle.PickleBuffer(v) for k, v in container.items()}

        if self._behavior is ak.behavior:
            behavior = None
        else:
            behavior = self._behavior

        if self._attrs is None:
            attrs = self._attrs
        else:
            attrs = without_transient_attrs(self._attrs)

        return unpickle_record_schema_1, (
            form.to_dict(),
            length,
            container,
            behavior,
            attrs,
            packed_layout.at,
        )

    def __setstate__(self, state):
        # awkward1 records cannot contain partitioned arrays, so we don't need to handle such a case here.
        form, length, container, behavior, at, *_ = state
        layout = ak.operations.from_buffers(
            form,
            length,
            container,
            highlevel=False,
            buffer_key="{form_key}-{attribute}",
            byteorder="<",
        )
        layout = ak.record.Record(layout, at)
        self._layout = layout
        self._behavior = behavior
        self._attrs = None

        self._update_class()

    def __copy__(self):
        return Record(self._layout, behavior=self._behavior, attrs=self._attrs)

    def __deepcopy__(self, memo):
        return Record(
            copy.deepcopy(self._layout, memo),
            behavior=copy.deepcopy(self._behavior, memo),
            attrs=copy.deepcopy(self._attrs, memo),
        )

    def __bool__(self):
        raise ValueError(
            "the truth value of a record is ambiguous; "
            "use ak.any() or ak.all() or pick a field"
        )


class ArrayBuilder(Sized):
    """
    Args:
        behavior (None or dict): Custom #ak.behavior for arrays built by
            this ArrayBuilder.
        initial (int): Initial size (in bytes) of buffers used by the `ak::ArrayBuilder`.
        resize (float): Resize multiplier for buffers used by the `ak::ArrayBuilder`;
            should be strictly greater than 1.

    General tool for building arrays of nested data structures from a sequence
    of commands. Most data types can be constructed by calling commands in the
    right order, similar to printing tokens to construct JSON output.

    To illustrate how this works, consider the following example.

        b = ak.ArrayBuilder()

        # fill commands   # as JSON   # current array type
        ##########################################################################################
        b.begin_list()    # [         # 0 * var * unknown     (initially, the type is unknown)
        b.integer(1)      #   1,      # 0 * var * int64
        b.integer(2)      #   2,      # 0 * var * int64
        b.real(3)         #   3.0     # 0 * var * float64     (all the integers have become floats)
        b.end_list()      # ],        # 1 * var * float64     (closed first list; array length is 1)
        b.begin_list()    # [         # 1 * var * float64
        b.end_list()      # ],        # 2 * var * float64     (closed empty list; array length is 2)
        b.begin_list()    # [         # 2 * var * float64
        b.integer(4)      #   4,      # 2 * var * float64
        b.null()          #   null,   # 2 * var * ?float64    (now the floats are nullable)
        b.integer(5)      #   5       # 2 * var * ?float64
        b.end_list()      # ],        # 3 * var * ?float64
        b.begin_list()    # [         # 3 * var * ?float64
        b.begin_record()  #   {       # 3 * var * union[?float64, ?{}]
        b.field("x")      #     "x":  # 3 * var * union[?float64, ?{x: unknown}]
        b.integer(1)      #      1,   # 3 * var * union[?float64, ?{x: int64}]
        b.field("y")      #      "y": # 3 * var * union[?float64, ?{x: int64, y: unknown}]
        b.begin_list()    #      [    # 3 * var * union[?float64, ?{x: int64, y: var * unknown}]
        b.integer(2)      #        2, # 3 * var * union[?float64, ?{x: int64, y: var * int64}]
        b.integer(3)      #        3  # 3 * var * union[?float64, ?{x: int64, y: var * int64}]
        b.end_list()      #      ]    # 3 * var * union[?float64, ?{x: int64, y: var * int64}]
        b.end_record()    #   }       # 3 * var * union[?float64, ?{x: int64, y: var * int64}]
        b.end_list()      # ]         # 4 * var * union[?float64, ?{x: int64, y: var * int64}]

    To get an array, we take a #snapshot of the ArrayBuilder's current state.

        >>> b.snapshot()
        <Array [[1, 2, 3], ..., [{x: 1, y: ..., ...}]] type='4 * var * union[?float...'>
        >>> b.snapshot().show()
        [[1, 2, 3],
         [],
         [4, None, 5],
         [{x: 1, y: [2, 3]}]]

    The full set of filling commands is the following.

    * #null: appends a None value.
    * #boolean: appends True or False.
    * #integer: appends an integer.
    * #real: appends a floating-point value.
    * #complex: appends a complex value.
    * #datetime: appends a datetime value.
    * #timedelta: appends a timedelta value.
    * #bytestring: appends an unencoded string (raw bytes).
    * #string: appends a UTF-8 encoded string.
    * #begin_list: begins filling a list; must be closed with #end_list.
    * #end_list: ends a list.
    * #begin_tuple: begins filling a tuple; must be closed with #end_tuple.
    * #index: selects a tuple slot to fill; must be followed by a command
         that actually fills that slot.
    * #end_tuple: ends a tuple.
    * #begin_record: begins filling a record; must be closed with
         #end_record.
    * #field: selects a record field to fill; must be followed by a command
         that actually fills that field.
    * #end_record: ends a record.
    * #append: generic method for filling #null, #boolean, #integer, #real,
         #bytestring, #string, #ak.Array, #ak.Record, or arbitrary Python data.
    * #extend: appends all the items from an iterable.
    * #list: context manager for #begin_list and #end_list.
    * #tuple: context manager for #begin_tuple and #end_tuple.
    * #record: context manager for #begin_record and #end_record.

    ArrayBuilders can be used in [Numba](http://numba.pydata.org/): they can
    be passed as arguments to a Numba-compiled function or returned as return
    values. (Since ArrayBuilder works by accumulating side-effects, it's not
    strictly necessary to return the object.)

    The primary limitation is that ArrayBuilders cannot be *created* and
    #snapshot cannot be called inside the Numba-compiled function. Awkward
    Array uses Numba as a transformer: #ak.Array and an empty #ak.ArrayBuilder
    go in and a filled #ak.ArrayBuilder is the result; #snapshot can be called
    outside of the compiled function.

    Also, context managers (Python's `with` statement) are not supported in
    Numba yet, so the #list, #tuple, and #record methods are not available
    in Numba-compiled functions.

    Here is an example of filling an ArrayBuilder in Numba, which makes a
    tree of dynamic depth.

        >>> import numba as nb
        >>> @nb.njit
        ... def deepnesting(builder, probability):
        ...     if np.random.uniform(0, 1) > probability:
        ...         builder.append(np.random.normal())
        ...     else:
        ...         builder.begin_list()
        ...         for i in range(np.random.poisson(3)):
        ...             deepnesting(builder, probability**2)
        ...         builder.end_list()
        ...
        >>> builder = ak.ArrayBuilder()
        >>> deepnesting(builder, 0.9)
        >>> builder.snapshot()
        <Array [[[-0.523, ..., [[2.16, ...], ...]]]] type='1 * var * var * union[fl...'>
        >>> builder.type.show()
        1 * var * var * union[
            float64,
            var * union[
                var * union[
                    float64,
                    var * unknown
                ],
                float64
            ]
        ]

    Note that this is a *general* method for building arrays; if the type is
    known in advance, more specialized procedures can be faster. This should
    be considered the "least effort" approach.
    """

    def __init__(self, *, behavior=None, attrs=None, initial=1024, resize=8):
        if behavior is not None and not isinstance(behavior, Mapping):
            raise TypeError("behavior must be None or mapping")

        self._layout = _ext.ArrayBuilder(initial=initial, resize=resize)
        self._behavior = behavior
        self._attrs = attrs

    @classmethod
    def _wrap(cls, layout, behavior=None, attrs=None):
        """
        Args:
            layout (`ak._ext.ArrayBuilder`): Low-level builder to wrap.
            behavior (None or dict): Custom #ak.behavior for arrays built by
                this ArrayBuilder.

        Wraps a low-level `ak._ext.ArrayBuilder` as a high-level
        #ak.ArrayBulider.

        The #ak.ArrayBuilder constructor creates a new `ak._ext.ArrayBuilder`
        with no accumulated data, but Numba needs to wrap existing data
        when returning from a lowered function.
        """
        assert isinstance(layout, _ext.ArrayBuilder)
        out = cls.__new__(cls)
        out._layout = layout
        out._behavior = behavior
        out._attrs = attrs
        return out

    @property
    def attrs(self) -> Attrs:
        """
        The mapping containing top-level metadata, which is serialised
        with the array during pickling.

        Keys prefixed with `@` are identified as "transient" attributes
        which are discarded prior to pickling, permitting the storage of
        non-pickleable types.
        """
        if self._attrs is None:
            self._attrs = Attrs({})
        return self._attrs

    @attrs.setter
    def attrs(self, value: Mapping[str, Any]):
        if isinstance(value, Mapping):
            self._attrs = Attrs(value)
        else:
            raise TypeError("attrs must be a mapping")

    @property
    def behavior(self):
        """
        The `behavior` parameter passed into this ArrayBuilder's constructor.

        * If a dict, this `behavior` overrides the global #ak.behavior.
             Any keys in the global #ak.behavior but not this `behavior` are
             still valid, but any keys in both are overridden by this
             `behavior`. Keys with a None value are equivalent to missing keys,
             so this `behavior` can effectively remove keys from the
             global #ak.behavior.

        * If None, the Array defaults to the global #ak.behavior.

        See #ak.behavior for a list of recognized key patterns and their
        meanings.
        """
        return self._behavior

    @behavior.setter
    def behavior(self, behavior):
        if behavior is None or isinstance(behavior, dict):
            self._behavior = behavior
        else:
            raise TypeError("behavior must be None or a dict")

    def tolist(self):
        """
        Converts this Array into Python objects; same as #ak.to_list
        (but without the underscore, like NumPy's
        [tolist](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html)).
        """
        return self.to_list()

    def to_list(self):
        """
        Converts this Array into Python objects; same as #ak.to_list.
        """
        return self.snapshot().to_list()

    def to_numpy(self, allow_missing=True):
        """
        Converts this Array into a NumPy array, if possible; same as #ak.to_numpy.
        """
        return self.snapshot().to_numpy(allow_missing=allow_missing)

    @property
    def type(self):
        """
        The high-level type of the accumulated array; same as #ak.type.

        Note that the outermost element of an Array's type is always an
        #ak.types.ArrayType, which specifies the number of elements in the array.

        The type of a #ak.contents.Content (from #ak.Array.layout) is not
        wrapped by an #ak.types.ArrayType.
        """
        form = ak.forms.from_json(self._layout.form())
        return ak.types.ArrayType(form.type, len(self._layout), self._behavior)

    @property
    def typestr(self):
        """
        The high-level type of this accumulated array, presented as a string.
        """
        return str(self.type)

    def __len__(self):
        """
        The current length of the accumulated array.
        """
        return len(self._layout)

    def __str__(self):
        return self.__repr__()

    def __repr__(self):
        return self._repr(80)

    def _repr(self, limit_cols):
        typestr = repr(self.typestr)

        limit_type = limit_cols - len("<ArrayBuilder type=>")
        if len(typestr) > limit_type:
            typestr = typestr[: (limit_type - 4)] + "..." + typestr[-1]

        return f"<ArrayBuilder type={typestr}>"

    def show(
        self,
        limit_rows=20,
        limit_cols=80,
        *,
        type=False,
        named_axis=False,
        nbytes=False,
        backend=False,
        all=False,
        stream=STDOUT,
        formatter=None,
        precision=3,
    ):
        """
        Args:
            limit_rows (int): Maximum number of rows (lines) to use in the output.
            limit_cols (int): Maximum number of columns (characters wide).
            type (bool): If True, print the type as well. (Doesn't count toward number
                of rows/lines limit.)
            named_axis (bool): If True, print the named axis as well. (Doesn't count toward number
                of rows/lines limit.)
            nbytes (bool): If True, print the number of bytes as well. (Doesn't count toward number
                of rows/lines limit.)
            backend (bool): If True, print the backend of the array as well. (Doesn't count toward number
                of rows/lines limit.)
            all (bool): If True, print the 'type', 'named axis', 'nbytes', and 'backend' of the array. (Doesn't count toward number
                of rows/lines limit.)
            stream (object with a ``write(str)`` method or None): Stream to write the
                output to. If None, return a string instead of writing to a stream.
            formatter (Mapping or None): Mapping of types/type-classes to string formatters.
                If None, use the default formatter.

        Display the contents of the array builder within `limit_rows` and `limit_cols`, using
        ellipsis (`...`) for hidden nested data.

        The `formatter` argument controls the formatting of individual values, c.f.
        https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html
        As Awkward Array does not implement strings as a NumPy dtype, the `numpystr`
        key is ignored; instead, a `"bytes"` and/or `"str"` key is considered when formatting
        string values, falling back upon `"str_kind"`.

        This method takes a snapshot of the data and calls show on it, and a snapshot
        copies data.
        """
        return self.snapshot().show(
            limit_rows=limit_rows,
            limit_cols=limit_cols,
            type=type,
            named_axis=named_axis,
            nbytes=nbytes,
            backend=backend,
            all=all,
            stream=stream,
            formatter=formatter,
            precision=precision,
        )

    def __array__(self, dtype=None, copy=None):
        """
        Intercepts attempts to convert a #snapshot of this array into a
        NumPy array and either performs a conversion if possible or raises an error.

        See #ak.Array.__array__ for a more complete description.
        """
        with ak._errors.OperationErrorContext(
            "numpy.asarray", (self,), {"dtype": dtype, "copy": copy}
        ):
            from awkward._connect.numpy import convert_to_array

            return convert_to_array(self.snapshot(), dtype=dtype, copy=copy)

    def __arrow_array__(self, type=None):
        with ak._errors.OperationErrorContext(
            f"{builtins.type(self).__name__}.__arrow_array__", (self,), {"type": type}
        ):
            from awkward._connect.pyarrow import convert_to_array

            return convert_to_array(self.snapshot(), type=type)

    @property
    def numba_type(self):
        """
        The type of this Array when it is used in Numba. It contains enough
        information to generate low-level code for accessing any element,
        down to the leaves.

        See [Numba documentation](https://numba.pydata.org/numba-doc/dev/reference/types.html)
        on types and signatures.
        """
        ak.numba.register_and_check()

        return ak._connect.numba.builder.ArrayBuilderType(self._behavior)

    def __bool__(self):
        if len(self) == 1:
            return bool(self.snapshot()[0])
        else:
            raise ValueError(
                "the truth value of an array whose length is not 1 is ambiguous; "
                "use ak.any() or ak.all()"
            )

    def snapshot(self):
        """
        Converts the currently accumulated data into an #ak.Array.

        The currently accumulated data are *copied* into the new array.
        """
        with ak._errors.OperationErrorContext("ak.ArrayBuilder.snapshot", [], {}):
            formstr, length, container = self._layout.to_buffers()
            form = ak.forms.from_json(formstr)
            return ak.operations.ak_from_buffers._impl(
                form,
                length,
                container,
                buffer_key="{form_key}-{attribute}",
                backend="cpu",
                byteorder=ak._util.native_byteorder,
                simplify=True,
                enable_virtualarray_caching=True,
                highlevel=True,
                behavior=self._behavior,
                attrs=self._attrs,
            )

    def null(self):
        """
        Appends a None value at the current position in the accumulated array.
        """
        self._layout.null()

    def boolean(self, x):
        """
        Appends a boolean value `x` at the current position in the accumulated
        array.
        """
        self._layout.boolean(x)

    def integer(self, x):
        """
        Appends an integer `x` at the current position in the accumulated
        array.
        """
        self._layout.integer(x)

    def real(self, x):
        """
        Appends a floating point number `x` at the current position in the
        accumulated array.
        """
        self._layout.real(x)

    def complex(self, x):
        """
        Appends a floating point number `x` at the current position in the
        accumulated array.
        """
        self._layout.complex(x)

    def datetime(self, x):
        """
        Appends a datetime value `x` at the current position in the
        accumulated array.
        """
        self._layout.datetime(x)

    def timedelta(self, x):
        """
        Appends a timedelta value `x` at the current position in the
        accumulated array.
        """
        self._layout.timedelta(x)

    def bytestring(self, x):
        """
        Appends an unencoded string (raw bytes) `x` at the current position
        in the accumulated array.
        """
        self._layout.bytestring(x)

    def string(self, x):
        """
        Appends a UTF-8 encoded string `x` at the current position in the
        accumulated array.
        """
        self._layout.string(x)

    def begin_list(self):
        """
        Begins filling a list; must be closed with #end_list.

        For example,

            >>> builder = ak.ArrayBuilder()
            >>> builder.begin_list()
            >>> builder.real(1.1)
            >>> builder.real(2.2)
            >>> builder.real(3.3)
            >>> builder.end_list()
            >>> builder.begin_list()
            >>> builder.end_list()
            >>> builder.begin_list()
            >>> builder.real(4.4)
            >>> builder.real(5.5)
            >>> builder.end_list()

        produces

            >>> builder.show()
            [[1.1, 2.2, 3.3],
             [],
             [4.4, 5.5]]
        """
        self._layout.beginlist()

    def end_list(self):
        """
        Ends a list.
        """
        self._layout.endlist()

    def begin_tuple(self, numfields):
        """
        Begins filling a tuple with `numfields` fields; must be closed with
        #end_tuple.

        For example,

            >>> builder = ak.ArrayBuilder()
            >>> builder.begin_tuple(3)
            >>> builder.index(0).integer(1)
            >>> builder.index(1).real(1.1)
            >>> builder.index(2).string("one")
            >>> builder.end_tuple()
            >>> builder.begin_tuple(3)
            >>> builder.index(0).integer(2)
            >>> builder.index(1).real(2.2)
            >>> builder.index(2).string("two")
            >>> builder.end_tuple()

        produces

            >>> builder.show()
            [(1, 1.1, 'one'),
             (2, 2.2, 'two')]
        """
        self._layout.begintuple(numfields)

    def index(self, i):
        """
        Args:
            i (int): The tuple slot to fill.

        This method also returns the #ak.ArrayBuilder, so that it can be
        chained with the value that fills the slot.

        Prepares to fill a tuple slot; see #begin_tuple for an example.
        """
        self._layout.index(i)
        return self

    def end_tuple(self):
        """
        Ends a tuple.
        """
        self._layout.endtuple()

    def begin_record(self, name=None):
        """
        Begins filling a record with an optional `name`; must be closed with
        #end_record.

        For example,

            >>> builder = ak.ArrayBuilder()
            >>> builder.begin_record("points")
            >>> builder.field("x").real(1)
            >>> builder.field("y").real(1.1)
            >>> builder.end_record()
            >>> builder.begin_record("points")
            >>> builder.field("x").real(2)
            >>> builder.field("y").real(2.2)
            >>> builder.end_record()

        produces

            >>> builder.show()
            [{x: 1, y: 1.1},
             {x: 2, y: 2.2}]

        with type

            >>> builder.type.show()
            2 * points[
                x: float64,
                y: float64
            ]

        The record type is named `"points"` because its `"__record__"`
        parameter is set to that value:

            >>> builder.snapshot().layout.parameters
            {'__record__': 'points'}

        The `"__record__"` parameter can be used to add behavior to the records
        in the array, as described in #ak.Array, #ak.Record, and #ak.behavior.
        """
        self._layout.beginrecord(name)

    def field(self, key):
        """
        Args:
            key (str): The field key to fill.

        This method also returns the #ak.ArrayBuilder, so that it can be
        chained with the value that fills the slot.

        Prepares to fill a field; see #begin_record for an example.
        """
        self._layout.field(key)
        return self

    def end_record(self):
        """
        Ends a record.
        """
        self._layout.endrecord()

    def append(self, obj):
        """
        Args:
            obj: The data to append (None, bool, int, float, bytes, str, or
                anything recognized by #ak.from_iter).

        Appends any type, which can be a shorthand for #null,
        #boolean, #integer, #real, #bytestring, or #string, but also
        an #ak.Array or #ak.Record to *reference* values from an existing
        dataset, or any Python object to *convert* to Awkward Array.

        If `obj` is an iterable (including dict), this is equivalent to
        #ak.from_iter except that it fills an existing #ak.ArrayBuilder,
        rather than creating a new one.
        """
        self._layout.fromiter(obj)

    def extend(self, obj):
        """
        Args:
            obj (iterable): Iterable of data to extend this ArrayBuilder with.

        Appends every value from `obj`.
        """
        for x in obj:
            self._layout.fromiter(x)

    class _Nested:
        def __init__(self, arraybuilder):
            self._arraybuilder = arraybuilder

        def __repr__(self):
            typestr = repr(self._arraybuilder.typestr)

            limit_type = 80 - len("<ArrayBuilder. type=>") - len(self._name)
            if len(typestr) > limit_type:
                typestr = typestr[: (limit_type - 4)] + "..." + typestr[-1]

            return f"<ArrayBuilder.{self._name} type={typestr}>"

    class List(_Nested):
        _name = "list"

        def __enter__(self):
            self._arraybuilder.begin_list()

        def __exit__(self, type, value, traceback):
            self._arraybuilder.end_list()

    def list(self):
        """
        Context manager to prevent unpaired #begin_list and #end_list. The
        example in the #begin_list documentation can be rewritten as

            >>> builder = ak.ArrayBuilder()
            >>> with builder.list():
            ...     builder.real(1.1)
            ...     builder.real(2.2)
            ...     builder.real(3.3)
            ...
            >>> with builder.list():
            ...     pass
            ...
            >>> with builder.list():
            ...     builder.real(4.4)
            ...     builder.real(5.5)
            ...

        to produce the same result.

            >>> builder.show()
            [[1.1, 2.2, 3.3],
             [],
             [4.4, 5.5]]

        Since context managers aren't yet supported by Numba, this method
        can't be used in Numba.
        """
        return self.List(self)

    class Tuple(_Nested):
        _name = "tuple"

        def __init__(self, arraybuilder, numfields):
            super().__init__(arraybuilder)
            self._numfields = numfields

        def __enter__(self):
            self._arraybuilder.begin_tuple(self._numfields)

        def __exit__(self, type, value, traceback):
            self._arraybuilder.end_tuple()

    def tuple(self, numfields):
        """
        Context manager to prevent unpaired #begin_tuple and #end_tuple. The
        example in the #begin_tuple documentation can be rewritten as

            >>> builder = ak.ArrayBuilder()
            >>> with builder.tuple(3):
            ...     builder.index(0).integer(1)
            ...     builder.index(1).real(1.1)
            ...     builder.index(2).string("one")
            ...
            >>> with builder.tuple(3):
            ...     builder.index(0).integer(2)
            ...     builder.index(1).real(2.2)
            ...     builder.index(2).string("two")
            ...

        to produce the same result.

            >>> builder.show()
            [(1, 1.1, 'one'),
             (2, 2.2, 'two')]

        Since context managers aren't yet supported by Numba, this method
        can't be used in Numba.
        """
        return self.Tuple(self, numfields)

    class Record(_Nested):
        _name = "record"

        def __init__(self, arraybuilder, name):
            super().__init__(arraybuilder)
            self._name = name

        def __enter__(self):
            self._arraybuilder.begin_record(name=self._name)

        def __exit__(self, type, value, traceback):
            self._arraybuilder.end_record()

    def record(self, name=None):
        """
        Context manager to prevent unpaired #begin_record and #end_record. The
        example in the #begin_record documentation can be rewritten as

            >>> builder = ak.ArrayBuilder()
            >>> with builder.record("points"):
            ...     builder.field("x").real(1)
            ...     builder.field("y").real(1.1)
            ...
            >>> with builder.record("points"):
            ...     builder.field("x").real(2)
            ...     builder.field("y").real(2.2)
            ...

        to produce the same result.

            >>> builder.show()
            [{x: 1, y: 1.1},
             {x: 2, y: 2.2}]

        Since context managers aren't yet supported by Numba, this method
        can't be used in Numba.
        """
        return self.Record(self, name)


def ignore_in_to_list(getitem_function):
    getitem_function.ignore_in_to_list = True
    return getitem_function


@register_backend_lookup_factory
def find_highlevel_backend(obj: type):
    if issubclass(obj, (Array, Record)):

        def finder(obj: Array):
            return obj.layout.backend

        return finder
    elif issubclass(obj, ArrayBuilder):

        def numpy_lookup(obj: ArrayBuilder):
            return NumpyBackend.instance()

        return numpy_lookup


@register_backend_lookup_factory
def find_lowlevel_backend(obj: type):
    if issubclass(obj, _ext.ArrayBuilder):

        def numpy_lookup(obj: ArrayBuilder):
            return NumpyBackend.instance()

        return numpy_lookup