summaryrefslogtreecommitdiff
path: root/src/webob/acceptparse.py
blob: 19443b6d3c797b129d813c5fee8a0f3216f94630 (plain)
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
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
"""
Parse four ``Accept*`` headers used in server-driven content negotiation.

The four headers are ``Accept``, ``Accept-Charset``, ``Accept-Encoding`` and
``Accept-Language``.
"""

from collections import namedtuple
import re
import textwrap
import warnings


# RFC 7230 Section 3.2.3 "Whitespace"
# OWS            = *( SP / HTAB )
#                ; optional whitespace
OWS_re = "[ \t]*"

# RFC 7230 Section 3.2.6 "Field Value Components":
# tchar          = "!" / "#" / "$" / "%" / "&" / "'" / "*"
#                / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
#                / DIGIT / ALPHA
tchar_re = r"[!#$%&'*+\-.^_`|~0-9A-Za-z]"

# token          = 1*tchar
token_re = tchar_re + "+"
token_compiled_re = re.compile("^" + token_re + "$")

# RFC 7231 Section 5.3.1 "Quality Values"
# qvalue = ( "0" [ "." 0*3DIGIT ] )
#        / ( "1" [ "." 0*3("0") ] )
qvalue_re = r"(?:0(?:\.[0-9]{0,3})?)" "|" r"(?:1(?:\.0{0,3})?)"
# weight = OWS ";" OWS "q=" qvalue
weight_re = OWS_re + ";" + OWS_re + "[qQ]=(" + qvalue_re + ")"


def _item_n_weight_re(item_re):
    return "(" + item_re + ")(?:" + weight_re + ")?"


def _item_qvalue_pair_to_header_element(pair):
    item, qvalue = pair

    if qvalue == 1.0:
        element = item
    elif qvalue == 0.0:
        element = "{};q=0".format(item)
    else:
        element = "{};q={}".format(item, qvalue)

    return element


def _list_0_or_more__compiled_re(element_re):
    # RFC 7230 Section 7 "ABNF List Extension: #rule":
    # #element => [ ( "," / element ) *( OWS "," [ OWS element ] ) ]

    return re.compile(
        "^(?:$)|"
        + "(?:"
        + "(?:,|(?:"
        + element_re
        + "))"
        + "(?:"
        + OWS_re
        + ",(?:"
        + OWS_re
        + element_re
        + ")?)*"
        + ")$"
    )


def _list_1_or_more__compiled_re(element_re):
    # RFC 7230 Section 7 "ABNF List Extension: #rule":
    # 1#element => *( "," OWS ) element *( OWS "," [ OWS element ] )
    # and RFC 7230 Errata ID: 4169

    return re.compile(
        "^(?:,"
        + OWS_re
        + ")*"
        + element_re
        + "(?:"
        + OWS_re
        + ",(?:"
        + OWS_re
        + element_re
        + ")?)*$"
    )


class AcceptOffer(namedtuple("AcceptOffer", ["type", "subtype", "params"])):
    """
    A pre-parsed offer tuple represeting a value in the format
    ``type/subtype;param0=value0;param1=value1``.

    :ivar type: The media type's root category.
    :ivar subtype: The media type's subtype.
    :ivar params: A tuple of 2-tuples containing parameter names and values.

    """

    __slots__ = ()

    def __str__(self):
        """
        Return the properly quoted media type string.

        """
        value = self.type + "/" + self.subtype

        return Accept._form_media_range(value, self.params)


class Accept:
    """
    Represent an ``Accept`` header.

    Base class for :class:`AcceptValidHeader`, :class:`AcceptNoHeader`, and
    :class:`AcceptInvalidHeader`.
    """

    # RFC 6838 describes syntax rules for media types that are different to
    # (and stricter than) those in RFC 7231, but if RFC 7231 intended us to
    # follow the rules in RFC 6838 for media ranges, it would not have
    # specified its own syntax rules for media ranges, so it appears we should
    # use the rules in RFC 7231 for now.

    # RFC 5234 Appendix B.1 "Core Rules":
    # VCHAR         =  %x21-7E
    #                       ; visible (printing) characters
    vchar_re = "\x21-\x7e"
    # RFC 7230 Section 3.2.6 "Field Value Components":
    # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
    # qdtext        = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
    # obs-text      = %x80-FF
    # quoted-pair   = "\" ( HTAB / SP / VCHAR / obs-text )
    obs_text_re = "\x80-\xff"
    qdtext_re = "[\t \x21\x23-\x5b\\\x5d-\x7e" + obs_text_re + "]"
    # The '\\' between \x5b and \x5d is needed to escape \x5d (']')
    quoted_pair_re = r"\\" + "[\t " + vchar_re + obs_text_re + "]"
    quoted_string_re = '"(?:(?:' + qdtext_re + ")|(?:" + quoted_pair_re + '))*"'

    # RFC 7231 Section 3.1.1.1 "Media Type":
    # type       = token
    # subtype    = token
    # parameter  = token "=" ( token / quoted-string )
    type_re = token_re
    subtype_re = token_re
    parameter_re = (
        token_re + "=" + "(?:(?:" + token_re + ")|(?:" + quoted_string_re + "))"
    )

    # Section 5.3.2 "Accept":
    # media-range    = ( "*/*"
    #                  / ( type "/" "*" )
    #                  / ( type "/" subtype )
    #                  ) *( OWS ";" OWS parameter )
    media_range_re = (
        "("
        + "(?:"
        + type_re
        + "/"
        + subtype_re
        + ")"
        +
        # '*' is included through type_re and subtype_re, so this covers */*
        # and type/*
        ")"
        + "("
        + "(?:"
        + OWS_re
        + ";"
        + OWS_re
        + "(?![qQ]=)"
        + parameter_re  # media type parameter cannot be named "q"
        + ")*"
        + ")"
    )
    # accept-params  = weight *( accept-ext )
    # accept-ext = OWS ";" OWS token [ "=" ( token / quoted-string ) ]
    accept_ext_re = (
        OWS_re
        + ";"
        + OWS_re
        + token_re
        + "(?:"
        + "=(?:"
        + "(?:"
        + token_re
        + ")|(?:"
        + quoted_string_re
        + ")"
        + ")"
        + ")?"
    )
    accept_params_re = weight_re + "((?:" + accept_ext_re + ")*)"

    media_range_n_accept_params_re = media_range_re + "(?:" + accept_params_re + ")?"
    media_range_n_accept_params_compiled_re = re.compile(media_range_n_accept_params_re)

    accept_compiled_re = _list_0_or_more__compiled_re(
        element_re=media_range_n_accept_params_re
    )

    # For parsing repeated groups within the media type parameters and
    # extension parameters segments
    parameters_compiled_re = re.compile(
        OWS_re
        + ";"
        + OWS_re
        + "("
        + token_re
        + ")=("
        + token_re
        + "|"
        + quoted_string_re
        + ")"
    )
    accept_ext_compiled_re = re.compile(
        OWS_re
        + ";"
        + OWS_re
        + "("
        + token_re
        + ")"
        + "(?:"
        + "=("
        + "(?:"
        + "(?:"
        + token_re
        + ")|(?:"
        + quoted_string_re
        + ")"
        + ")"
        + ")"
        + ")?"
    )

    # For parsing the media types in the `offers` argument to
    # .acceptable_offers(), we re-use the media range regex for media types, as
    # they work out to have the exact same syntax according to RFC 7231.
    media_type_re = media_range_re
    media_type_compiled_re = re.compile("^" + media_type_re + "$")

    @classmethod
    def _escape_and_quote_parameter_value(cls, param_value):
        """
        Escape and quote parameter value where necessary.

        For media type and extension parameter values.
        """

        if param_value == "":
            param_value = '""'
        else:
            param_value = param_value.replace("\\", "\\\\").replace('"', r"\"")

            if not token_compiled_re.match(param_value):
                param_value = '"' + param_value + '"'

        return param_value

    @classmethod
    def _form_extension_params_segment(cls, extension_params):
        """
        Convert iterable of extension parameters to str segment for header.

        `extension_params` is an iterable where each item is either a parameter
        string or a (name, value) tuple.
        """
        extension_params_segment = ""

        for item in extension_params:
            try:
                extension_params_segment += ";" + item
            except TypeError:
                param_name, param_value = item
                param_value = cls._escape_and_quote_parameter_value(
                    param_value=param_value
                )
                extension_params_segment += ";" + param_name + "=" + param_value

        return extension_params_segment

    @classmethod
    def _form_media_range(cls, type_subtype, media_type_params):
        """
        Combine `type_subtype` and `media_type_params` to form a media range.

        `type_subtype` is a ``str``, and `media_type_params` is an iterable of
        (parameter name, parameter value) tuples.
        """
        media_type_params_segment = ""

        for param_name, param_value in media_type_params:
            param_value = cls._escape_and_quote_parameter_value(param_value=param_value)
            media_type_params_segment += ";" + param_name + "=" + param_value

        return type_subtype + media_type_params_segment

    @classmethod
    def _iterable_to_header_element(cls, iterable):
        """
        Convert iterable of tuples into header element ``str``.

        Each tuple is expected to be in one of two forms: (media_range, qvalue,
        extension_params_segment), or (media_range, qvalue).
        """
        try:
            media_range, qvalue, extension_params_segment = iterable
        except ValueError:
            media_range, qvalue = iterable
            extension_params_segment = ""

        if qvalue == 1.0:
            if extension_params_segment:
                element = "{};q=1{}".format(media_range, extension_params_segment)
            else:
                element = media_range
        elif qvalue == 0.0:
            element = "{};q=0{}".format(media_range, extension_params_segment)
        else:
            element = "{};q={}{}".format(media_range, qvalue, extension_params_segment)

        return element

    @classmethod
    def _parse_media_type_params(cls, media_type_params_segment):
        """
        Parse media type parameters segment into list of (name, value) tuples.
        """
        media_type_params = cls.parameters_compiled_re.findall(
            media_type_params_segment
        )

        for index, (name, value) in enumerate(media_type_params):
            if value.startswith('"') and value.endswith('"'):
                value = cls._process_quoted_string_token(token=value)
                media_type_params[index] = (name, value)

        return media_type_params

    @classmethod
    def _process_quoted_string_token(cls, token):
        """
        Return unescaped and unquoted value from quoted token.
        """
        # RFC 7230, section 3.2.6 "Field Value Components": "Recipients that
        # process the value of a quoted-string MUST handle a quoted-pair as if
        # it were replaced by the octet following the backslash."

        return re.sub(r"\\(?![\\])", "", token[1:-1]).replace("\\\\", "\\")

    @classmethod
    def _python_value_to_header_str(cls, value):
        """
        Convert Python value to header string for __add__/__radd__.
        """

        if isinstance(value, str):
            return value

        if hasattr(value, "items"):
            if value == {}:
                value = []
            else:
                value_list = []

                for media_range, item in value.items():
                    # item is either (media range, (qvalue, extension
                    # parameters segment)), or (media range, qvalue) (supported
                    # for backward compatibility)

                    if isinstance(item, (float, int)):
                        value_list.append((media_range, item, ""))
                    else:
                        value_list.append((media_range, item[0], item[1]))
                value = sorted(
                    value_list, key=lambda item: item[1], reverse=True  # qvalue
                )

        if isinstance(value, (tuple, list)):
            header_elements = []

            for item in value:
                if isinstance(item, (tuple, list)):
                    item = cls._iterable_to_header_element(iterable=item)
                header_elements.append(item)
            header_str = ", ".join(header_elements)
        else:
            header_str = str(value)

        return header_str

    @classmethod
    def parse(cls, value):
        """
        Parse an ``Accept`` header.

        :param value: (``str``) header value
        :return: If `value` is a valid ``Accept`` header, returns an iterator
                 of (*media_range*, *qvalue*, *media_type_params*,
                 *extension_params*) tuples, as parsed from the header from
                 left to right.

                 | *media_range* is the media range, including any media type
                   parameters. The media range is returned in a canonicalised
                   form (except the case of the characters are unchanged):
                   unnecessary spaces around the semicolons before media type
                   parameters are removed; the parameter values are returned in
                   a form where only the '``\\``' and '``"``' characters are
                   escaped, and the values are quoted with double quotes only
                   if they need to be quoted.

                 | *qvalue* is the quality value of the media range.

                 | *media_type_params* is the media type parameters, as a list
                   of (parameter name, value) tuples.

                 | *extension_params* is the extension parameters, as a list
                   where each item is either a parameter string or a (parameter
                   name, value) tuple.
        :raises ValueError: if `value` is an invalid header
        """
        # Check if header is valid
        # Using Python stdlib's `re` module, there is currently no way to check
        # the match *and* get all the groups using the same regex, so we have
        # to do this in steps using multiple regexes.

        if cls.accept_compiled_re.match(value) is None:
            raise ValueError("Invalid value for an Accept header.")

        def generator(value):
            for match in cls.media_range_n_accept_params_compiled_re.finditer(value):
                groups = match.groups()

                type_subtype = groups[0]

                media_type_params = cls._parse_media_type_params(
                    media_type_params_segment=groups[1]
                )

                media_range = cls._form_media_range(
                    type_subtype=type_subtype, media_type_params=media_type_params
                )

                # qvalue (groups[2]) and extension_params (groups[3]) are both
                # None if neither qvalue or extension parameters are found in
                # the match.

                qvalue = groups[2]
                qvalue = float(qvalue) if qvalue else 1.0

                extension_params = groups[3]

                if extension_params:
                    extension_params = cls.accept_ext_compiled_re.findall(
                        extension_params
                    )

                    for index, (token_key, token_value) in enumerate(extension_params):
                        if token_value:
                            if token_value.startswith('"') and token_value.endswith(
                                '"'
                            ):
                                token_value = cls._process_quoted_string_token(
                                    token=token_value
                                )
                                extension_params[index] = (token_key, token_value)
                        else:
                            extension_params[index] = token_key
                else:
                    extension_params = []

                yield (media_range, qvalue, media_type_params, extension_params)

        return generator(value=value)

    @classmethod
    def parse_offer(cls, offer):
        """
        Parse an offer into its component parts.

        :param offer: A media type or range in the format
                      ``type/subtype[;params]``.
        :return: A named tuple containing ``(*type*, *subtype*, *params*)``.

                 | *params* is a list containing ``(*parameter name*, *value*)``
                   values.

        :raises ValueError: If the offer does not match the required format.

        """

        if isinstance(offer, AcceptOffer):
            return offer
        match = cls.media_type_compiled_re.match(offer)

        if not match:
            raise ValueError("Invalid value for an Accept offer.")

        groups = match.groups()
        offer_type, offer_subtype = groups[0].split("/")
        offer_params = cls._parse_media_type_params(media_type_params_segment=groups[1])

        if offer_type == "*" or offer_subtype == "*":
            raise ValueError("Invalid value for an Accept offer.")

        return AcceptOffer(
            offer_type.lower(),
            offer_subtype.lower(),
            tuple((name.lower(), value) for name, value in offer_params),
        )

    @classmethod
    def _parse_and_normalize_offers(cls, offers):
        """
        Throw out any offers that do not match the media range ABNF.

        :return: A list of offers split into the format ``[offer_index,
                 parsed_offer]``.

        """
        parsed_offers = []

        for index, offer in enumerate(offers):
            try:
                parsed_offer = cls.parse_offer(offer)
            except ValueError:
                continue
            parsed_offers.append([index, parsed_offer])

        return parsed_offers


class AcceptValidHeader(Accept):
    """
    Represent a valid ``Accept`` header.

    A valid header is one that conforms to :rfc:`RFC 7231, section 5.3.2
    <7231#section-5.3.2>`.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptValidHeader.__add__`).
    """

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        A list of (*media_range*, *qvalue*, *media_type_params*,
        *extension_params*) tuples, where

        *media_range* is the media range, including any media type parameters.
        The media range is returned in a canonicalised form (except the case of
        the characters are unchanged): unnecessary spaces around the semicolons
        before media type parameters are removed; the parameter values are
        returned in a form where only the '``\\``' and '``"``' characters are
        escaped, and the values are quoted with double quotes only if they need
        to be quoted.

        *qvalue* is the quality value of the media range.

        *media_type_params* is the media type parameters, as a list of
        (parameter name, value) tuples.

        *extension_params* is the extension parameters, as a list where each
        item is either a parameter string or a (parameter name, value) tuple.
        """

        return self._parsed

    def __init__(self, header_value):
        """
        Create an :class:`AcceptValidHeader` instance.

        :param header_value: (``str``) header value.
        :raises ValueError: if `header_value` is an invalid value for an
                            ``Accept`` header.
        """
        self._header_value = header_value
        self._parsed = list(self.parse(header_value))
        self._parsed_nonzero = [item for item in self.parsed if item[1]]
        # item[1] is the qvalue

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with media ranges ``str``'s (including any media type
          parameters) as keys, and either qvalues ``float``'s or (*qvalues*,
          *extension_params*) tuples as values, where *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (*media_range*, *qvalue*, *extension_params*) ``tuple``
          or ``list`` where *media_range* is a ``str`` of the media range
          including any media type parameters, and *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * an :class:`AcceptValidHeader`, :class:`AcceptNoHeader`, or
          :class:`AcceptInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or another
        :class:`AcceptValidHeader` instance, and the header value it represents
        is not `''`, then the two header values are joined with ``', '``, and a
        new :class:`AcceptValidHeader` instance with the new header value is
        returned.

        If `other` is a valid header value or another
        :class:`AcceptValidHeader` instance representing a header value of
        `''`; or if it is ``None`` or an :class:`AcceptNoHeader` instance; or
        if it is an invalid header value, or an :class:`AcceptInvalidHeader`
        instance, then a new :class:`AcceptValidHeader` instance with the same
        header value as ``self`` is returned.
        """

        if isinstance(other, AcceptValidHeader):
            if other.header_value == "":
                return self.__class__(header_value=self.header_value)
            else:
                return create_accept_header(
                    header_value=self.header_value + ", " + other.header_value
                )

        if isinstance(other, (AcceptNoHeader, AcceptInvalidHeader)):
            return self.__class__(header_value=self.header_value)

        return self._add_instance_and_non_accept_type(instance=self, other=other)

    def __bool__(self):
        """
        Return whether ``self`` represents a valid ``Accept`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``True``.
        """

        return True

    __nonzero__ = __bool__  # Python 2

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of :meth:`AcceptValidHeader.__contains__` is currently
           being maintained for backward compatibility, but it will change in
           the future to better conform to the RFC.

        :param offer: (``str``) media type offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        This uses the old criterion of a match in
        :meth:`AcceptValidHeader._old_match`, which is not as specified in
        :rfc:`RFC 7231, section 5.3.2 <7231#section-5.3.2>`. It does not
        correctly take into account media type parameters:

            >>> 'text/html;p=1' in AcceptValidHeader('text/html')
            False

        or media ranges with ``q=0`` in the header::

            >>> 'text/html' in AcceptValidHeader('text/*, text/html;q=0')
            True
            >>> 'text/html' in AcceptValidHeader('text/html;q=0, */*')
            True

        (See the docstring for :meth:`AcceptValidHeader._old_match` for other
        problems with the old criterion for matching.)
        """
        warnings.warn(
            "The behavior of AcceptValidHeader.__contains__ is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )

        for (
            media_range,
            _quality,
            _media_type_params,
            _extension_params,
        ) in self._parsed_nonzero:
            if self._old_match(media_range, offer):
                return True

        return False

    def __iter__(self):
        """
        Return all the ranges with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the media ranges in the header with non-0
                 qvalues, in descending order of qvalue. If two ranges have the
                 same qvalue, they are returned in the order of their positions
                 in the header, from left to right.

        Please note that this is a simple filter for the ranges in the header
        with non-0 qvalues, and is not necessarily the same as what the client
        prefers, e.g. ``'audio/basic;q=0, */*'`` means 'everything but
        audio/basic', but ``list(instance)`` would return only ``['*/*']``.
        """
        warnings.warn(
            "The behavior of AcceptLanguageValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )

        for media_range, _qvalue, _media_type_params, _extension_params in sorted(
            self._parsed_nonzero, key=lambda i: i[1], reverse=True
        ):
            yield media_range

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{} ({!r})>".format(self.__class__.__name__, str(self))

    def __str__(self):
        r"""
        Return a tidied up version of the header value.

        e.g. If ``self.header_value`` is ``r',,text/html ; p1="\"\1\"" ;
        q=0.50; e1=1 ;e2  ,  text/plain ,'``, ``str(instance)`` returns
        ``r'text/html;p1="\"1\"";q=0.5;e1=1;e2, text/plain'``.
        """
        # self.parsed tuples are in the form: (media_range, qvalue,
        # media_type_params, extension_params)
        # self._iterable_to_header_element() requires iterable to be in the
        # form: (media_range, qvalue, extension_params_segment).
        return ", ".join(
            self._iterable_to_header_element(
                iterable=(
                    tuple_[0],  # media_range
                    tuple_[1],  # qvalue
                    self._form_extension_params_segment(
                        extension_params=tuple_[3]  # extension_params
                    ),
                )
            )
            for tuple_ in self.parsed
        )

    def _add_instance_and_non_accept_type(
        self, instance, other, instance_on_the_right=False
    ):
        if not other:
            return self.__class__(header_value=instance.header_value)

        other_header_value = self._python_value_to_header_str(value=other)

        if other_header_value == "":
            # if ``other`` is an object whose type we don't recognise, and
            # str(other) returns ''
            return self.__class__(header_value=instance.header_value)

        try:
            self.parse(value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__(header_value=instance.header_value)

        new_header_value = (
            (other_header_value + ", " + instance.header_value)
            if instance_on_the_right
            else (instance.header_value + ", " + other_header_value)
        )
        return self.__class__(header_value=new_header_value)

    def _old_match(self, mask, offer):
        """
        Check if the offer is covered by the mask

        ``offer`` may contain wildcards to facilitate checking if a ``mask``
        would match a 'permissive' offer.

        Wildcard matching forces the match to take place against the type or
        subtype of the mask and offer (depending on where the wildcard matches)

        .. warning::

           This is maintained for backward compatibility, and will be
           deprecated in the future.

        This method was WebOb's old criterion for deciding whether a media type
        matches a media range, used in

        - :meth:`AcceptValidHeader.__contains__`
        - :meth:`AcceptValidHeader.best_match`
        - :meth:`AcceptValidHeader.quality`

        It allows offers of *, */*, type/*, */subtype and types with no
        subtypes, which are not media types as specified in :rfc:`RFC 7231,
        section 5.3.2 <7231#section-5.3.2>`. This is also undocumented in any
        of the public APIs that uses this method.
        """
        # Match if comparisons are the same or either is a complete wildcard
        if mask.lower() == offer.lower() or "*/*" in (mask, offer) or "*" == offer:
            return True

        # Set mask type with wildcard subtype for malformed masks
        try:
            mask_type, mask_subtype = [x.lower() for x in mask.split("/")]
        except ValueError:
            mask_type = mask
            mask_subtype = "*"

        # Set offer type with wildcard subtype for malformed offers
        try:
            offer_type, offer_subtype = [x.lower() for x in offer.split("/")]
        except ValueError:
            offer_type = offer
            offer_subtype = "*"

        if mask_subtype == "*":
            # match on type only
            if offer_type == "*":
                return True
            else:
                return mask_type.lower() == offer_type.lower()

        if mask_type == "*":
            # match on subtype only
            if offer_subtype == "*":
                return True
            else:
                return mask_subtype.lower() == offer_subtype.lower()

        if offer_subtype == "*":
            # match on type only
            return mask_type.lower() == offer_type.lower()

        if offer_type == "*":
            # match on subtype only
            return mask_subtype.lower() == offer_subtype.lower()

        return offer.lower() == mask.lower()

    def accept_html(self):
        """
        Return ``True`` if any HTML-like type is accepted.

        The HTML-like types are 'text/html', 'application/xhtml+xml',
        'application/xml' and 'text/xml'.
        """
        return bool(
            self.acceptable_offers(
                offers=[
                    "text/html",
                    "application/xhtml+xml",
                    "application/xml",
                    "text/xml",
                ]
            )
        )

    accepts_html = property(fget=accept_html, doc=accept_html.__doc__)
    # note the plural

    def acceptable_offers(self, offers):
        """
        Return the offers that are acceptable according to the header.

        The offers are returned in descending order of preference, where
        preference is indicated by the qvalue of the media range in the header
        that best matches the offer.

        This uses the matching rules described in :rfc:`RFC 7231, section 5.3.2
        <7231#section-5.3.2>`.

        Any offers that cannot be parsed via
        :meth:`.Accept.parse_offer` will be ignored.

        :param offers: ``iterable`` of ``str`` media types (media types can
                       include media type parameters) or pre-parsed instances
                       of :class:`.AcceptOffer`.
        :return: A list of tuples of the form (media type, qvalue), in
                 descending order of qvalue. Where two offers have the same
                 qvalue, they are returned in the same order as their order in
                 `offers`.
        """
        parsed = self.parsed

        # RFC 7231, section 3.1.1.1 "Media Type":
        # "The type, subtype, and parameter name tokens are case-insensitive.
        # Parameter values might or might not be case-sensitive, depending on
        # the semantics of the parameter name."
        lowercased_ranges = [
            (
                media_range.partition(";")[0].lower(),
                qvalue,
                tuple((name.lower(), value) for name, value in media_type_params),
            )
            for media_range, qvalue, media_type_params, __ in parsed
        ]
        lowercased_offers_parsed = self._parse_and_normalize_offers(offers)

        acceptable_offers_n_quality_factors = {}
        for offer_index, parsed_offer in lowercased_offers_parsed:
            offer = offers[offer_index]
            offer_type, offer_subtype, offer_media_type_params = parsed_offer
            for (
                range_type_subtype,
                range_qvalue,
                range_media_type_params,
            ) in lowercased_ranges:
                range_type, range_subtype = range_type_subtype.split("/", 1)

                # The specificity values below are based on the list in the
                # example in RFC 7231 section 5.3.2 explaining how "media
                # ranges can be overridden by more specific media ranges or
                # specific media types". We assign specificity to the list
                # items in reverse order, so specificity 4, 3, 2, 1 correspond
                # to 1, 2, 3, 4 in the list, respectively (so that higher
                # specificity has higher precedence).
                if offer_type == range_type and offer_subtype == range_subtype:
                    if range_media_type_params == ():
                        # If offer_media_type_params == () the offer and the
                        # range match exactly, with neither having media type
                        # parameters.
                        # If offer_media_type_params is not (), the offer and
                        # the range are a match. See the table towards the end
                        # of RFC 7231 section 5.3.2, where the media type
                        # 'text/html;level=3' matches the range 'text/html' in
                        # the header.
                        # Both cases are a match with a specificity of 3.
                        specificity = 3
                    elif offer_media_type_params == range_media_type_params:
                        specificity = 4
                    else:  # pragma: no cover
                        continue
                else:
                    if range_subtype == "*" and offer_type == range_type:
                        specificity = 2
                    elif range_type_subtype == "*/*":
                        specificity = 1
                    else:  # pragma: no cover
                        continue
                try:
                    if specificity <= (acceptable_offers_n_quality_factors[offer][2]):
                        continue
                except KeyError:
                    # the entry for the offer is not already in
                    # acceptable_offers_n_quality_factors
                    pass
                acceptable_offers_n_quality_factors[offer] = (
                    range_qvalue,  # qvalue of matched range
                    offer_index,
                    specificity,  # specifity of matched range
                )

        acceptable_offers_n_quality_factors = [
            # key is offer, value[0] is qvalue, value[1] is offer_index
            (key, value[0], value[1])
            for key, value in acceptable_offers_n_quality_factors.items()
            if value[0]  # != 0.0
            # We have to filter out the offers with qvalues of 0 here instead
            # of just skipping them early in the large ``for`` loop because
            # that would not work for e.g. when the header is 'text/html;q=0,
            # text/html' (which does not make sense, but is nonetheless valid),
            # and offers is ['text/html']
        ]
        acceptable_offers_n_quality_factors.sort(
            key=lambda tuple_: (tuple_[1], -tuple_[2]),
            reverse=True,
            # descending sort by (qvalue, -offer_index)
        )
        # return list of (offer, qvalue) tuples, dropping offer_index
        return [(item[0], item[1]) for item in acceptable_offers_n_quality_factors]
        # If a media range is repeated in the header (which would not make
        # sense, but would be valid according to the rules in the RFC), an
        # offer for which the media range is the most specific match would take
        # its qvalue from the first appearance of the range in the header.

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of media type `offers`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

           :meth:`AcceptValidHeader.best_match` uses its own algorithm (one not
           specified in :rfc:`RFC 7231 <7231>`) to determine what is a best
           match. The algorithm has many issues, and does not conform to
           :rfc:`RFC 7231 <7231>`.

        Each media type in `offers` is checked against each non-``q=0`` range
        in the header. If the two are a match according to WebOb's old
        criterion for a match, the quality value of the match is the qvalue of
        the media range from the header multiplied by the server quality value
        of the offer (if the server quality value is not supplied, it is 1).

        The offer in the match with the highest quality value is the best
        match. If there is more than one match with the highest qvalue, the
        match where the media range has a lower number of '*'s is the best
        match. If the two have the same number of '*'s, the one that shows up
        first in `offers` is the best match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` media type,
                         or a (media type, server quality value) ``tuple`` or
                         ``list``. (The two may be mixed in the iterable.)

        :param default_match: (optional, any type) the value to be returned if
                              there is no match

        :return: (``str``, or the type of `default_match`)

                 | The offer that is the best match. If there is no match, the
                   value of `default_match` is returned.

        This uses the old criterion of a match in
        :meth:`AcceptValidHeader._old_match`, which is not as specified in
        :rfc:`RFC 7231, section 5.3.2 <7231#section-5.3.2>`. It does not
        correctly take into account media type parameters:

            >>> instance = AcceptValidHeader('text/html')
            >>> instance.best_match(offers=['text/html;p=1']) is None
            True

        or media ranges with ``q=0`` in the header::

            >>> instance = AcceptValidHeader('text/*, text/html;q=0')
            >>> instance.best_match(offers=['text/html'])
            'text/html'

            >>> instance = AcceptValidHeader('text/html;q=0, */*')
            >>> instance.best_match(offers=['text/html'])
            'text/html'

        (See the docstring for :meth:`AcceptValidHeader._old_match` for other
        problems with the old criterion for matching.)

        Another issue is that this method considers the best matching range for
        an offer to be the matching range with the highest quality value,
        (where quality values are tied, the most specific media range is
        chosen); whereas :rfc:`RFC 7231, section 5.3.2 <7231#section-5.3.2>`
        specifies that we should consider the best matching range for a media
        type offer to be the most specific matching range.::

            >>> instance = AcceptValidHeader('text/html;q=0.5, text/*')
            >>> instance.best_match(offers=['text/html', 'text/plain'])
            'text/html'
        """
        warnings.warn(
            "The behavior of AcceptValidHeader.best_match is currently being "
            "maintained for backward compatibility, but it will be deprecated"
            " in the future, as it does not conform to the RFC.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        matched_by = "*/*"
        for offer in offers:
            if isinstance(offer, (tuple, list)):
                offer, server_quality = offer
            else:
                server_quality = 1
            for item in self._parsed_nonzero:
                mask = item[0]
                quality = item[1]
                possible_quality = server_quality * quality
                if possible_quality < best_quality:
                    continue
                elif possible_quality == best_quality:
                    # 'text/plain' overrides 'message/*' overrides '*/*'
                    # (if all match w/ the same q=)
                    if matched_by.count("*") <= mask.count("*"):
                        continue
                if self._old_match(mask, offer):
                    best_quality = possible_quality
                    best_offer = offer
                    matched_by = mask
        return best_offer

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

        :param offer: (``str``) media type offer
        :return: (``float`` or ``None``)

                 | The highest quality value from the media range(s) that match
                   the `offer`, or ``None`` if there is no match.

        This uses the old criterion of a match in
        :meth:`AcceptValidHeader._old_match`, which is not as specified in
        :rfc:`RFC 7231, section 5.3.2 <7231#section-5.3.2>`. It does not
        correctly take into account media type parameters:

            >>> instance = AcceptValidHeader('text/html')
            >>> instance.quality('text/html;p=1') is None
            True

        or media ranges with ``q=0`` in the header::

            >>> instance = AcceptValidHeader('text/*, text/html;q=0')
            >>> instance.quality('text/html')
            1.0
            >>> AcceptValidHeader('text/html;q=0, */*').quality('text/html')
            1.0

        (See the docstring for :meth:`AcceptValidHeader._old_match` for other
        problems with the old criterion for matching.)

        Another issue is that this method considers the best matching range for
        an offer to be the matching range with the highest quality value,
        whereas :rfc:`RFC 7231, section 5.3.2 <7231#section-5.3.2>` specifies
        that we should consider the best matching range for a media type offer
        to be the most specific matching range.::

            >>> instance = AcceptValidHeader('text/html;q=0.5, text/*')
            >>> instance.quality('text/html')
            1.0
        """
        warnings.warn(
            "The behavior of AcceptValidHeader.quality is currently being "
            "maintained for backward compatibility, but it will be deprecated "
            "in the future, as it does not conform to the RFC.",
            DeprecationWarning,
        )
        bestq = 0
        for item in self.parsed:
            media_range = item[0]
            qvalue = item[1]
            if self._old_match(media_range, offer):
                bestq = max(bestq, qvalue)
        return bestq or None


class MIMEAccept(Accept):
    """
    Backwards compatibility shim for the new functionality provided by
    AcceptValidHeader, AcceptInvalidHeader, or AcceptNoHeader, that acts like
    the old MIMEAccept from WebOb version 1.7 or lower.

    This shim does use the newer Accept header parsing, which will mean your
    application may be less liberal in what Accept headers are correctly
    parsed. It is recommended that user agents be updated to send appropriate
    Accept headers that are valid according to :rfc:`7231#section-5.3.2`.

    .. deprecated:: 1.8

       Instead of directly creating the Accept object, please see:
       :func:`create_accept_header(header_value)
       <webob.acceptparse.create_accept_header>`, which will create the
       appropriate object.

       This shim has an extended deprecation period to allow for application
       developers to switch to the new API.

    """

    def __init__(self, header_value):
        warnings.warn(
            "The MIMEAccept class has been replaced by "
            "webob.acceptparse.create_accept_header. This compatibility shim "
            "will be deprecated in a future version of WebOb.",
            DeprecationWarning,
        )
        self._accept = create_accept_header(header_value)
        if self._accept.parsed:
            self._parsed = [(media, q) for (media, q, _, _) in self._accept.parsed]
            self._parsed_nonzero = [(m, q) for (m, q) in self._parsed if q]
        else:
            self._parsed = []
            self._parsed_nonzero = []

    @staticmethod
    def parse(value):
        try:
            parsed_accepted = Accept.parse(value)

            for (media, q, _, _) in parsed_accepted:
                yield (media, q)
        except ValueError:
            pass

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

    def __iter__(self):
        return self._accept.__iter__()

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

    def __add__(self, other):
        if isinstance(other, self.__class__):
            return self.__class__(str(self._accept.__add__(other._accept)))
        else:
            return self.__class__(str(self._accept.__add__(other)))

    def __radd__(self, other):
        return self.__class__(str(self._accept.__radd__(other)))

    def __contains__(self, offer):
        return offer in self._accept

    def quality(self, offer):
        return self._accept.quality(offer)

    def best_match(self, offers, default_match=None):
        return self._accept.best_match(offers, default_match=default_match)

    def accept_html(self):
        return self._accept.accept_html()


class _AcceptInvalidOrNoHeader(Accept):
    """
    Represent when an ``Accept`` header is invalid or not in request.

    This is the base class for the behaviour that :class:`.AcceptInvalidHeader`
    and :class:`.AcceptNoHeader` have in common.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept`` header has an invalid value. This implementation disregards the
    header when the header is invalid, so :class:`.AcceptInvalidHeader` and
    :class:`.AcceptNoHeader` have much behaviour in common.
    """

    def __bool__(self):
        """
        Return whether ``self`` represents a valid ``Accept`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``False``.
        """
        return False

    __nonzero__ = __bool__  # Python 2

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of ``.__contains__`` for the ``Accept`` classes is
           currently being maintained for backward compatibility, but it will
           change in the future to better conform to the RFC.

        :param offer: (``str``) media type offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        For this class, either there is no ``Accept`` header in the request, or
        the header is invalid, so any media type is acceptable, and this always
        returns ``True``.
        """
        warnings.warn(
            "The behavior of .__contains__ for the Accept classes is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )
        return True

    def __iter__(self):
        """
        Return all the ranges with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the media ranges in the header with non-0
                 qvalues, in descending order of qvalue. If two ranges have the
                 same qvalue, they are returned in the order of their positions
                 in the header, from left to right.

        When there is no ``Accept`` header in the request or the header is
        invalid, there are no media ranges, so this always returns an empty
        iterator.
        """
        warnings.warn(
            "The behavior of AcceptValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )
        return iter(())

    def accept_html(self):
        """
        Return ``True`` if any HTML-like type is accepted.

        The HTML-like types are 'text/html', 'application/xhtml+xml',
        'application/xml' and 'text/xml'.

        When the header is invalid, or there is no `Accept` header in the
        request, all `offers` are considered acceptable, so this always returns
        ``True``.
        """
        return bool(
            self.acceptable_offers(
                offers=[
                    "text/html",
                    "application/xhtml+xml",
                    "application/xml",
                    "text/xml",
                ]
            )
        )

    accepts_html = property(fget=accept_html, doc=accept_html.__doc__)
    # note the plural

    def acceptable_offers(self, offers):
        """
        Return the offers that are acceptable according to the header.

        Any offers that cannot be parsed via
        :meth:`.Accept.parse_offer` will be ignored.

        :param offers: ``iterable`` of ``str`` media types (media types can
                       include media type parameters)
        :return: When the header is invalid, or there is no ``Accept`` header
                 in the request, all `offers` are considered acceptable, so
                 this method returns a list of (media type, qvalue) tuples
                 where each offer in `offers` is paired with the qvalue of 1.0,
                 in the same order as in `offers`.
        """
        # avoid returning any offers that don't match the grammar so
        # that the return values here are consistent with what would be
        # returned in AcceptValidHeader
        return [
            (offers[offer_index], 1.0)
            for offer_index, _ in self._parse_and_normalize_offers(offers)
        ]

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of language tag `offers`.

        This is the ``.best_match()`` method for when the header is invalid or
        not found in the request, corresponding to
        :meth:`AcceptValidHeader.best_match`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptValidHeader.best_match`).

        When the header is invalid, or there is no `Accept` header in the
        request, all `offers` are considered acceptable, so the best match is
        the media type in `offers` with the highest server quality value (if
        the server quality value is not supplied for a media type, it is 1).

        If more than one media type in `offers` have the same highest server
        quality value, then the one that shows up first in `offers` is the best
        match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` media type,
                         or a (media type, server quality value) ``tuple`` or
                         ``list``. (The two may be mixed in the iterable.)

        :param default_match: (optional, any type) the value to be returned if
                              `offers` is empty.

        :return: (``str``, or the type of `default_match`)

                 | The offer that has the highest server quality value.  If
                   `offers` is empty, the value of `default_match` is returned.
        """
        warnings.warn(
            "The behavior of .best_match for the Accept classes is currently "
            "being maintained for backward compatibility, but the method will"
            " be deprecated in the future, as its behavior is not specified "
            "in (and currently does not conform to) RFC 7231.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        for offer in offers:
            if isinstance(offer, (list, tuple)):
                offer, quality = offer
            else:
                quality = 1
            if quality > best_quality:
                best_offer = offer
                best_quality = quality
        return best_offer

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        This is the ``.quality()`` method for when the header is invalid or not
        found in the request, corresponding to
        :meth:`AcceptValidHeader.quality`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptValidHeader.quality`).

        :param offer: (``str``) media type offer
        :return: (``float``) ``1.0``.

        When the ``Accept`` header is invalid or not in the request, all offers
        are equally acceptable, so 1.0 is always returned.
        """
        warnings.warn(
            "The behavior of .quality for the Accept classes is currently "
            "being maintained for backward compatibility, but the method will"
            " be deprecated in the future, as its behavior does not conform to"
            "RFC 7231.",
            DeprecationWarning,
        )
        return 1.0


class AcceptNoHeader(_AcceptInvalidOrNoHeader):
    """
    Represent when there is no ``Accept`` header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptNoHeader.__add__`).
    """

    @property
    def header_value(self):
        """
        (``str`` or ``None``) The header value.

        As there is no header in the request, this is ``None``.
        """
        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As there is no header in the request, this is ``None``.
        """
        return self._parsed

    def __init__(self):
        """
        Create an :class:`AcceptNoHeader` instance.
        """
        self._header_value = None
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__()

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with media ranges ``str``'s (including any media type
          parameters) as keys, and either qvalues ``float``'s or (*qvalues*,
          *extension_params*) tuples as values, where *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (*media_range*, *qvalue*, *extension_params*) ``tuple``
          or ``list`` where *media_range* is a ``str`` of the media range
          including any media type parameters, and *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * an :class:`AcceptValidHeader`, :class:`AcceptNoHeader`, or
          :class:`AcceptInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an :class:`AcceptValidHeader`
        instance, a new :class:`AcceptValidHeader` instance with the valid
        header value is returned.

        If `other` is ``None``, an :class:`AcceptNoHeader` instance, an invalid
        header value, or an :class:`AcceptInvalidHeader` instance, a new
        :class:`AcceptNoHeader` instance is returned.
        """
        if isinstance(other, AcceptValidHeader):
            return AcceptValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptNoHeader, AcceptInvalidHeader)):
            return self.__class__()

        return self._add_instance_and_non_accept_type(instance=self, other=other)

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptNoHeader.__add__`.
        """
        return self.__add__(other=other)

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    def __str__(self):
        """Return the ``str`` ``'<no header in request>'``."""

        return "<no header in request>"

    def _add_instance_and_non_accept_type(self, instance, other):
        if other is None:
            return self.__class__()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__()


class AcceptInvalidHeader(_AcceptInvalidOrNoHeader):
    """
    Represent an invalid ``Accept`` header.

    An invalid header is one that does not conform to
    :rfc:`7231#section-5.3.2`.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept`` header has an invalid value. This implementation disregards the
    header, and treats it as if there is no ``Accept`` header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptInvalidHeader.__add__`).
    """

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As the header is invalid and cannot be parsed, this is ``None``.
        """

        return self._parsed

    def __init__(self, header_value):
        """
        Create an :class:`AcceptInvalidHeader` instance.
        """
        self._header_value = header_value
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with media ranges ``str``'s (including any media type
          parameters) as keys, and either qvalues ``float``'s or (*qvalues*,
          *extension_params*) tuples as values, where *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (*media_range*, *qvalue*, *extension_params*) ``tuple``
          or ``list`` where *media_range* is a ``str`` of the media range
          including any media type parameters, and *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * an :class:`AcceptValidHeader`, :class:`AcceptNoHeader`, or
          :class:`AcceptInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an :class:`AcceptValidHeader`
        instance, then a new :class:`AcceptValidHeader` instance with the valid
        header value is returned.

        If `other` is ``None``, an :class:`AcceptNoHeader` instance, an invalid
        header value, or an :class:`AcceptInvalidHeader` instance, a new
        :class:`AcceptNoHeader` instance is returned.
        """

        if isinstance(other, AcceptValidHeader):
            return AcceptValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptNoHeader, AcceptInvalidHeader)):
            return AcceptNoHeader()

        return self._add_instance_and_non_accept_type(instance=self, other=other)

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)
        # We do not display the header_value, as it is untrusted input. The
        # header_value could always be easily obtained from the .header_value
        # property.

    def __str__(self):
        """Return the ``str`` ``'<invalid header value>'``."""

        return "<invalid header value>"

    def _add_instance_and_non_accept_type(
        self, instance, other, instance_on_the_right=False
    ):
        if other is None:
            return AcceptNoHeader()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return AcceptNoHeader()


def create_accept_header(header_value):
    """
    Create an object representing the ``Accept`` header in a request.

    :param header_value: (``str``) header value
    :return: If `header_value` is ``None``, an :class:`AcceptNoHeader`
             instance.

             | If `header_value` is a valid ``Accept`` header, an
               :class:`AcceptValidHeader` instance.

             | If `header_value` is an invalid ``Accept`` header, an
               :class:`AcceptInvalidHeader` instance.
    """

    if header_value is None:
        return AcceptNoHeader()
    if isinstance(header_value, Accept):
        return header_value.copy()
    try:
        return AcceptValidHeader(header_value=header_value)
    except ValueError:
        return AcceptInvalidHeader(header_value=header_value)


def accept_property():
    doc = """
        Property representing the ``Accept`` header.

        (:rfc:`RFC 7231, section 5.3.2 <7231#section-5.3.2>`)

        The header value in the request environ is parsed and a new object
        representing the header is created every time we *get* the value of the
        property. (*set* and *del* change the header value in the request
        environ, and do not involve parsing.)
    """

    ENVIRON_KEY = "HTTP_ACCEPT"

    def fget(request):
        """Get an object representing the header in the request."""

        return create_accept_header(header_value=request.environ.get(ENVIRON_KEY))

    def fset(request, value):
        """
        Set the corresponding key in the request environ.

        `value` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with media ranges ``str``'s (including any media type
          parameters) as keys, and either qvalues ``float``'s or (*qvalues*,
          *extension_params*) tuples as values, where *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (*media_range*, *qvalue*, *extension_params*) ``tuple``
          or ``list`` where *media_range* is a ``str`` of the media range
          including any media type parameters, and *extension_params* is a
          ``str`` of the extension parameters segment of the header element,
          starting with the first '``;``'
        * an :class:`AcceptValidHeader`, :class:`AcceptNoHeader`, or
          :class:`AcceptInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``
        """

        if value is None or isinstance(value, AcceptNoHeader):
            fdel(request=request)
        else:
            if isinstance(value, (AcceptValidHeader, AcceptInvalidHeader)):
                header_value = value.header_value
            else:
                header_value = Accept._python_value_to_header_str(value=value)
            request.environ[ENVIRON_KEY] = header_value

    def fdel(request):
        """Delete the corresponding key from the request environ."""
        try:
            del request.environ[ENVIRON_KEY]
        except KeyError:
            pass

    return property(fget, fset, fdel, textwrap.dedent(doc))


class AcceptCharset:
    """
    Represent an ``Accept-Charset`` header.

    Base class for :class:`AcceptCharsetValidHeader`,
    :class:`AcceptCharsetNoHeader`, and :class:`AcceptCharsetInvalidHeader`.
    """

    # RFC 7231 Section 3.1.1.2 "Charset":
    # charset = token
    charset_re = token_re
    # RFC 7231 Section 5.3.3 "Accept-Charset":
    # Accept-Charset = 1#( ( charset / "*" ) [ weight ] )
    charset_n_weight_re = _item_n_weight_re(item_re=charset_re)
    charset_n_weight_compiled_re = re.compile(charset_n_weight_re)
    accept_charset_compiled_re = _list_1_or_more__compiled_re(
        element_re=charset_n_weight_re
    )

    @classmethod
    def _python_value_to_header_str(cls, value):
        if isinstance(value, str):
            header_str = value
        else:
            if hasattr(value, "items"):
                value = sorted(value.items(), key=lambda item: item[1], reverse=True)

            if isinstance(value, (tuple, list)):
                result = []

                for item in value:
                    if isinstance(item, (tuple, list)):
                        item = _item_qvalue_pair_to_header_element(pair=item)
                    result.append(item)
                header_str = ", ".join(result)
            else:
                header_str = str(value)

        return header_str

    @classmethod
    def parse(cls, value):
        """
        Parse an ``Accept-Charset`` header.

        :param value: (``str``) header value
        :return: If `value` is a valid ``Accept-Charset`` header, returns an
                 iterator of (charset, quality value) tuples, as parsed from
                 the header from left to right.
        :raises ValueError: if `value` is an invalid header
        """
        # Check if header is valid
        # Using Python stdlib's `re` module, there is currently no way to check
        # the match *and* get all the groups using the same regex, so we have
        # to use one regex to check the match, and another to get the groups.

        if cls.accept_charset_compiled_re.match(value) is None:
            raise ValueError("Invalid value for an Accept-Charset header.")

        def generator(value):
            for match in cls.charset_n_weight_compiled_re.finditer(value):
                charset = match.group(1)
                qvalue = match.group(2)
                qvalue = float(qvalue) if qvalue else 1.0
                yield (charset, qvalue)

        return generator(value=value)


class AcceptCharsetValidHeader(AcceptCharset):
    """
    Represent a valid ``Accept-Charset`` header.

    A valid header is one that conforms to :rfc:`RFC 7231, section 5.3.3
    <7231#section-5.3.3>`.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptCharsetValidHeader.__add__`).
    """

    @property
    def header_value(self):
        """(``str``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list``) Parsed form of the header.

        A list of (charset, quality value) tuples.
        """

        return self._parsed

    def __init__(self, header_value):
        """
        Create an :class:`AcceptCharsetValidHeader` instance.

        :param header_value: (``str``) header value.
        :raises ValueError: if `header_value` is an invalid value for an
                            ``Accept-Charset`` header.
        """
        self._header_value = header_value
        self._parsed = list(self.parse(header_value))
        self._parsed_nonzero = [
            item for item in self.parsed if item[1]  # item[1] is the qvalue
        ]

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, where keys are charsets and values are qvalues
        * a ``tuple`` or ``list``, where each item is a charset ``str`` or a
          ``tuple`` or ``list`` (charset, qvalue) pair (``str``'s and pairs
          can be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptCharsetValidHeader`, :class:`AcceptCharsetNoHeader`,
          or :class:`AcceptCharsetInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or another
        :class:`AcceptCharsetValidHeader` instance, the two header values are
        joined with ``', '``, and a new :class:`AcceptCharsetValidHeader`
        instance with the new header value is returned.

        If `other` is ``None``, an :class:`AcceptCharsetNoHeader` instance, an
        invalid header value, or an :class:`AcceptCharsetInvalidHeader`
        instance, a new :class:`AcceptCharsetValidHeader` instance with the
        same header value as ``self`` is returned.
        """

        if isinstance(other, AcceptCharsetValidHeader):
            return create_accept_charset_header(
                header_value=self.header_value + ", " + other.header_value
            )

        if isinstance(other, (AcceptCharsetNoHeader, AcceptCharsetInvalidHeader)):
            return self.__class__(header_value=self.header_value)

        return self._add_instance_and_non_accept_charset_type(
            instance=self, other=other
        )

    def __bool__(self):
        """
        Return whether ``self`` represents a valid ``Accept-Charset`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``True``.
        """

        return True

    __nonzero__ = __bool__  # Python 2

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of :meth:`AcceptCharsetValidHeader.__contains__` is
           currently being maintained for backward compatibility, but it will
           change in the future to better conform to the RFC.

        :param offer: (``str``) charset offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        This does not fully conform to :rfc:`RFC 7231, section 5.3.3
        <7231#section-5.3.3>`: it incorrect interprets ``*`` to mean 'match any
        charset in the header', rather than 'match any charset that is not
        mentioned elsewhere in the header'::

            >>> 'UTF-8' in AcceptCharsetValidHeader('UTF-8;q=0, *')
            True
        """
        warnings.warn(
            "The behavior of AcceptCharsetValidHeader.__contains__ is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )

        for mask, _quality in self._parsed_nonzero:
            if self._old_match(mask, offer):
                return True

        return False

    def __iter__(self):
        """
        Return all the items with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the items (charset or ``*``) in the header
                 with non-0 qvalues, in descending order of qvalue. If two
                 items have the same qvalue, they are returned in the order of
                 their positions in the header, from left to right.

        Please note that this is a simple filter for the items in the header
        with non-0 qvalues, and is not necessarily the same as what the client
        prefers, e.g. ``'utf-7;q=0, *'`` means 'everything but utf-7', but
        ``list(instance)`` would return only ``['*']``.
        """
        warnings.warn(
            "The behavior of AcceptCharsetValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )

        for mask, _quality in sorted(
            self._parsed_nonzero, key=lambda i: i[1], reverse=True
        ):
            yield mask

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptCharsetValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_charset_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{} ({!r})>".format(self.__class__.__name__, str(self))

    def __str__(self):
        r"""
        Return a tidied up version of the header value.

        e.g. If the ``header_value`` is ``', \t,iso-8859-5;q=0.000 \t,
        utf-8;q=1.000, UTF-7, unicode-1-1;q=0.210  ,'``, ``str(instance)``
        returns ``'iso-8859-5;q=0, utf-8, UTF-7, unicode-1-1;q=0.21'``.
        """
        return ", ".join(
            _item_qvalue_pair_to_header_element(pair=tuple_) for tuple_ in self.parsed
        )

    def _add_instance_and_non_accept_charset_type(
        self, instance, other, instance_on_the_right=False
    ):
        if not other:
            return self.__class__(header_value=instance.header_value)

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            self.parse(value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__(header_value=instance.header_value)

        new_header_value = (
            (other_header_value + ", " + instance.header_value)
            if instance_on_the_right
            else (instance.header_value + ", " + other_header_value)
        )
        return self.__class__(header_value=new_header_value)

    def _old_match(self, mask, offer):
        """
        Return whether charset offer matches header item (charset or ``*``).

        .. warning::

           This is maintained for backward compatibility, and will be
           deprecated in the future.

        This method was WebOb's old criterion for deciding whether a charset
        matches a header item (charset or ``*``), used in

        - :meth:`AcceptCharsetValidHeader.__contains__`
        - :meth:`AcceptCharsetValidHeader.best_match`
        - :meth:`AcceptCharsetValidHeader.quality`

        It does not conform to :rfc:`RFC 7231, section 5.3.3
        <7231#section-5.3.3>` in that it does not interpret ``*`` values in the
        header correctly: ``*`` should only match charsets not mentioned
        elsewhere in the header.
        """
        return mask == "*" or offer.lower() == mask.lower()

    def acceptable_offers(self, offers):
        """
        Return the offers that are acceptable according to the header.

        The offers are returned in descending order of preference, where
        preference is indicated by the qvalue of the charset or ``*`` in the
        header matching the offer.

        This uses the matching rules described in :rfc:`RFC 7231, section 5.3.3
        <7231#section-5.3.3>`.

        :param offers: ``iterable`` of ``str`` charsets
        :return: A list of tuples of the form (charset, qvalue), in descending
                 order of qvalue. Where two offers have the same qvalue, they
                 are returned in the same order as their order in `offers`.
        """
        lowercased_parsed = [
            (charset.lower(), qvalue) for (charset, qvalue) in self.parsed
        ]
        lowercased_offers = [offer.lower() for offer in offers]

        not_acceptable_charsets = set()
        acceptable_charsets = dict()
        asterisk_qvalue = None

        for charset, qvalue in lowercased_parsed:
            if charset == "*":
                if asterisk_qvalue is None:
                    asterisk_qvalue = qvalue
            elif (
                charset not in acceptable_charsets
                and charset not in not_acceptable_charsets
                # if we have not already encountered this charset in the header
            ):
                if qvalue == 0.0:
                    not_acceptable_charsets.add(charset)
                else:
                    acceptable_charsets[charset] = qvalue
        acceptable_charsets = list(acceptable_charsets.items())
        # Sort acceptable_charsets by qvalue, descending order
        acceptable_charsets.sort(key=lambda tuple_: tuple_[1], reverse=True)

        filtered_offers = []
        for index, offer in enumerate(lowercased_offers):
            # If offer matches a non-* charset with q=0, it is filtered out
            if any(((offer == charset) for charset in not_acceptable_charsets)):
                continue

            matched_charset_qvalue = None
            for charset, qvalue in acceptable_charsets:
                if offer == charset:
                    matched_charset_qvalue = qvalue
                    break
            else:
                if asterisk_qvalue:
                    matched_charset_qvalue = asterisk_qvalue
            if matched_charset_qvalue is not None:  # if there was a match
                filtered_offers.append((offers[index], matched_charset_qvalue, index))

        # sort by position in `offers` argument, ascending
        filtered_offers.sort(key=lambda tuple_: tuple_[2])
        # When qvalues are tied, position in `offers` is the tiebreaker.

        # sort by qvalue, descending
        filtered_offers.sort(key=lambda tuple_: tuple_[1], reverse=True)

        return [(item[0], item[1]) for item in filtered_offers]
        # (offer, qvalue), dropping the position

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of charset `offers`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

           :meth:`AcceptCharsetValidHeader.best_match`  has many issues, and
           does not conform to :rfc:`RFC 7231 <7231>`.

        Each charset in `offers` is checked against each non-``q=0`` item
        (charset or ``*``) in the header. If the two are a match according to
        WebOb's old criterion for a match, the quality value of the match is
        the qvalue of the item from the header multiplied by the server quality
        value of the offer (if the server quality value is not supplied, it is
        1).

        The offer in the match with the highest quality value is the best
        match. If there is more than one match with the highest qvalue, the one
        that shows up first in `offers` is the best match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` charset, or
                         a (charset, server quality value) ``tuple`` or
                         ``list``.  (The two may be mixed in the iterable.)

        :param default_match: (optional, any type) the value to be returned if
                              there is no match

        :return: (``str``, or the type of `default_match`)

                 | The offer that is the best match. If there is no match, the
                   value of `default_match` is returned.

        The algorithm behind this method was written for the ``Accept`` header
        rather than the ``Accept-Charset`` header. It uses the old criterion of
        a match in :meth:`AcceptCharsetValidHeader._old_match`, which does not
        conform to :rfc:`RFC 7231, section 5.3.3 <7231#section-5.3.3>`, in that
        it does not interpret ``*`` values in the header correctly: ``*``
        should only match charsets not mentioned elsewhere in the header::

            >>> AcceptCharsetValidHeader('utf-8;q=0, *').best_match(['utf-8'])
            'utf-8'
        """
        warnings.warn(
            "The behavior of AcceptCharsetValidHeader.best_match is currently"
            " being maintained for backward compatibility, but it will be "
            "deprecated in the future, as it does not conform to the RFC.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        matched_by = "*/*"
        for offer in offers:
            if isinstance(offer, (tuple, list)):
                offer, server_quality = offer
            else:
                server_quality = 1
            for mask, quality in self._parsed_nonzero:
                possible_quality = server_quality * quality
                if possible_quality < best_quality:
                    continue
                elif possible_quality == best_quality:
                    # 'text/plain' overrides 'message/*' overrides '*/*'
                    # (if all match w/ the same q=)
                    # [We can see that this was written for the Accept header,
                    # not the Accept-Charset header.]
                    if matched_by.count("*") <= mask.count("*"):
                        continue
                if self._old_match(mask, offer):
                    best_quality = possible_quality
                    best_offer = offer
                    matched_by = mask
        return best_offer

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

        :param offer: (``str``) charset offer
        :return: (``float`` or ``None``)

                 | The quality value from the charset that matches the `offer`,
                   or ``None`` if there is no match.

        This uses the old criterion of a match in
        :meth:`AcceptCharsetValidHeader._old_match`, which does not conform to
        :rfc:`RFC 7231, section 5.3.3 <7231#section-5.3.3>`, in that it does
        not interpret ``*`` values in the header correctly: ``*`` should only
        match charsets not mentioned elsewhere in the header::

            >>> AcceptCharsetValidHeader('utf-8;q=0, *').quality('utf-8')
            1.0
            >>> AcceptCharsetValidHeader('utf-8;q=0.9, *').quality('utf-8')
            1.0
        """
        warnings.warn(
            "The behavior of AcceptCharsetValidHeader.quality is currently "
            "being maintained for backward compatibility, but it will be "
            "deprecated in the future, as it does not conform to the RFC.",
            DeprecationWarning,
        )
        bestq = 0
        for mask, quality in self.parsed:
            if self._old_match(mask, offer):
                bestq = max(bestq, quality)
        return bestq or None


class _AcceptCharsetInvalidOrNoHeader(AcceptCharset):
    """
    Represent when an ``Accept-Charset`` header is invalid or not in request.

    This is the base class for the behaviour that
    :class:`.AcceptCharsetInvalidHeader` and :class:`.AcceptCharsetNoHeader`
    have in common.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept-Charset`` header has an invalid value. This implementation
    disregards the header when the header is invalid, so
    :class:`.AcceptCharsetInvalidHeader` and :class:`.AcceptCharsetNoHeader`
    have much behaviour in common.
    """

    def __bool__(self):
        """
        Return whether ``self`` represents a valid ``Accept-Charset`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``False``.
        """
        return False

    __nonzero__ = __bool__  # Python 2

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of ``.__contains__`` for the ``AcceptCharset`` classes
           is currently being maintained for backward compatibility, but it
           will change in the future to better conform to the RFC.

        :param offer: (``str``) charset offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        For this class, either there is no ``Accept-Charset`` header in the
        request, or the header is invalid, so any charset is acceptable, and
        this always returns ``True``.
        """
        warnings.warn(
            "The behavior of .__contains__ for the AcceptCharset classes is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )
        return True

    def __iter__(self):
        """
        Return all the items with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the items (charset or ``*``) in the header
                 with non-0 qvalues, in descending order of qvalue. If two
                 items have the same qvalue, they are returned in the order of
                 their positions in the header, from left to right.

        When there is no ``Accept-Charset`` header in the request or the header
        is invalid, there are no items, and this always returns an empty
        iterator.
        """
        warnings.warn(
            "The behavior of AcceptCharsetValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )
        return iter(())

    def acceptable_offers(self, offers):
        """
        Return the offers that are acceptable according to the header.

        The offers are returned in descending order of preference, where
        preference is indicated by the qvalue of the charset or ``*`` in the
        header matching the offer.

        This uses the matching rules described in :rfc:`RFC 7231, section 5.3.3
        <7231#section-5.3.3>`.

        :param offers: ``iterable`` of ``str`` charsets
        :return: A list of tuples of the form (charset, qvalue), in descending
                 order of qvalue. Where two offers have the same qvalue, they
                 are returned in the same order as their order in `offers`.

                 | When the header is invalid or there is no ``Accept-Charset``
                   header in the request, all `offers` are considered
                   acceptable, so this method returns a list of (charset,
                   qvalue) tuples where each offer in `offers` is paired with
                   the qvalue of 1.0, in the same order as `offers`.
        """
        return [(offer, 1.0) for offer in offers]

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of charset `offers`.

        This is the ``.best_match()`` method for when the header is invalid or
        not found in the request, corresponding to
        :meth:`AcceptCharsetValidHeader.best_match`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptCharsetValidHeader.best_match`).

        When the header is invalid, or there is no `Accept-Charset` header in
        the request, all the charsets in `offers` are considered acceptable, so
        the best match is the charset in `offers` with the highest server
        quality value (if the server quality value is not supplied, it is 1).

        If more than one charsets in `offers` have the same highest server
        quality value, then the one that shows up first in `offers` is the best
        match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` charset, or
                         a (charset, server quality value) ``tuple`` or
                         ``list``.  (The two may be mixed in the iterable.)

        :param default_match: (optional, any type) the value to be returned if
                              `offers` is empty.

        :return: (``str``, or the type of `default_match`)

                 | The charset that has the highest server quality value.  If
                   `offers` is empty, the value of `default_match` is returned.
        """
        warnings.warn(
            "The behavior of .best_match for the AcceptCharset classes is "
            "currently being maintained for backward compatibility, but the "
            "method will be deprecated in the future, as its behavior is not "
            "specified in (and currently does not conform to) RFC 7231.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        for offer in offers:
            if isinstance(offer, (list, tuple)):
                offer, quality = offer
            else:
                quality = 1
            if quality > best_quality:
                best_offer = offer
                best_quality = quality
        return best_offer

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        This is the ``.quality()`` method for when the header is invalid or not
        found in the request, corresponding to
        :meth:`AcceptCharsetValidHeader.quality`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptCharsetValidHeader.quality`).

        :param offer: (``str``) charset offer
        :return: (``float``) ``1.0``.

        When the ``Accept-Charset`` header is invalid or not in the request,
        all offers are equally acceptable, so 1.0 is always returned.
        """
        warnings.warn(
            "The behavior of .quality for the Accept-Charset classes is "
            "currently being maintained for backward compatibility, but the "
            "method will be deprecated in the future, as its behavior does not"
            " conform to RFC 7231.",
            DeprecationWarning,
        )
        return 1.0


class AcceptCharsetNoHeader(_AcceptCharsetInvalidOrNoHeader):
    """
    Represent when there is no ``Accept-Charset`` header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptCharsetNoHeader.__add__`).
    """

    @property
    def header_value(self):
        """
        (``str`` or ``None``) The header value.

        As there is no header in the request, this is ``None``.
        """
        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As there is no header in the request, this is ``None``.
        """
        return self._parsed

    def __init__(self):
        """
        Create an :class:`AcceptCharsetNoHeader` instance.
        """
        self._header_value = None
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__()

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, where keys are charsets and values are qvalues
        * a ``tuple`` or ``list``, where each item is a charset ``str`` or a
          ``tuple`` or ``list`` (charset, qvalue) pair (``str`` and pairs
          can be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptCharsetValidHeader`, :class:`AcceptCharsetNoHeader`,
          or :class:`AcceptCharsetInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an
        :class:`AcceptCharsetValidHeader` instance, a new
        :class:`AcceptCharsetValidHeader` instance with the valid header value
        is returned.

        If `other` is ``None``, an :class:`AcceptCharsetNoHeader` instance, an
        invalid header value, or an :class:`AcceptCharsetInvalidHeader`
        instance, a new :class:`AcceptCharsetNoHeader` instance is returned.
        """
        if isinstance(other, AcceptCharsetValidHeader):
            return AcceptCharsetValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptCharsetNoHeader, AcceptCharsetInvalidHeader)):
            return self.__class__()

        return self._add_instance_and_non_accept_charset_type(
            instance=self, other=other
        )

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptCharsetNoHeader.__add__`.
        """
        return self.__add__(other=other)

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    def __str__(self):
        """Return the ``str`` ``'<no header in request>'``."""

        return "<no header in request>"

    def _add_instance_and_non_accept_charset_type(self, instance, other):
        if not other:
            return self.__class__()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptCharsetValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__()


class AcceptCharsetInvalidHeader(_AcceptCharsetInvalidOrNoHeader):
    """
    Represent an invalid ``Accept-Charset`` header.

    An invalid header is one that does not conform to
    :rfc:`7231#section-5.3.3`. As specified in the RFC, an empty header is an
    invalid ``Accept-Charset`` header.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept-Charset`` header has an invalid value. This implementation
    disregards the header, and treats it as if there is no ``Accept-Charset``
    header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptCharsetInvalidHeader.__add__`).
    """

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As the header is invalid and cannot be parsed, this is ``None``.
        """

        return self._parsed

    def __init__(self, header_value):
        """
        Create an :class:`AcceptCharsetInvalidHeader` instance.
        """
        self._header_value = header_value
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, where keys are charsets and values are qvalues
        * a ``tuple`` or ``list``, where each item is a charset ``str`` or a
          ``tuple`` or ``list`` (charset, qvalue) pair (``str``'s and pairs
          can be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptCharsetValidHeader`, :class:`AcceptCharsetNoHeader`,
          or :class:`AcceptCharsetInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an
        :class:`AcceptCharsetValidHeader` instance, a new
        :class:`AcceptCharsetValidHeader` instance with the valid header value
        is returned.

        If `other` is ``None``, an :class:`AcceptCharsetNoHeader` instance, an
        invalid header value, or an :class:`AcceptCharsetInvalidHeader`
        instance, a new :class:`AcceptCharsetNoHeader` instance is returned.
        """

        if isinstance(other, AcceptCharsetValidHeader):
            return AcceptCharsetValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptCharsetNoHeader, AcceptCharsetInvalidHeader)):
            return AcceptCharsetNoHeader()

        return self._add_instance_and_non_accept_charset_type(
            instance=self, other=other
        )

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptCharsetValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_charset_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)
        # We do not display the header_value, as it is untrusted input. The
        # header_value could always be easily obtained from the .header_value
        # property.

    def __str__(self):
        """Return the ``str`` ``'<invalid header value>'``."""

        return "<invalid header value>"

    def _add_instance_and_non_accept_charset_type(
        self, instance, other, instance_on_the_right=False
    ):
        if not other:
            return AcceptCharsetNoHeader()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptCharsetValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return AcceptCharsetNoHeader()


def create_accept_charset_header(header_value):
    """
    Create an object representing the ``Accept-Charset`` header in a request.

    :param header_value: (``str``) header value
    :return: If `header_value` is ``None``, an :class:`AcceptCharsetNoHeader`
             instance.

             | If `header_value` is a valid ``Accept-Charset`` header, an
               :class:`AcceptCharsetValidHeader` instance.

             | If `header_value` is an invalid ``Accept-Charset`` header, an
               :class:`AcceptCharsetInvalidHeader` instance.
    """

    if header_value is None:
        return AcceptCharsetNoHeader()
    if isinstance(header_value, AcceptCharset):
        return header_value.copy()
    try:
        return AcceptCharsetValidHeader(header_value=header_value)
    except ValueError:
        return AcceptCharsetInvalidHeader(header_value=header_value)


def accept_charset_property():
    doc = """
        Property representing the ``Accept-Charset`` header.

        (:rfc:`RFC 7231, section 5.3.3 <7231#section-5.3.3>`)

        The header value in the request environ is parsed and a new object
        representing the header is created every time we *get* the value of the
        property. (*set* and *del* change the header value in the request
        environ, and do not involve parsing.)
    """

    ENVIRON_KEY = "HTTP_ACCEPT_CHARSET"

    def fget(request):
        """Get an object representing the header in the request."""

        return create_accept_charset_header(
            header_value=request.environ.get(ENVIRON_KEY)
        )

    def fset(request, value):
        """
        Set the corresponding key in the request environ.

        `value` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, where keys are charsets and values are qvalues
        * a ``tuple`` or ``list``, where each item is a charset ``str`` or a
          ``tuple`` or ``list`` (charset, qvalue) pair (``str``'s and pairs
          can be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptCharsetValidHeader`, :class:`AcceptCharsetNoHeader`,
          or :class:`AcceptCharsetInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``
        """

        if value is None or isinstance(value, AcceptCharsetNoHeader):
            fdel(request=request)
        else:
            if isinstance(
                value, (AcceptCharsetValidHeader, AcceptCharsetInvalidHeader)
            ):
                header_value = value.header_value
            else:
                header_value = AcceptCharset._python_value_to_header_str(value=value)
            request.environ[ENVIRON_KEY] = header_value

    def fdel(request):
        """Delete the corresponding key from the request environ."""
        try:
            del request.environ[ENVIRON_KEY]
        except KeyError:
            pass

    return property(fget, fset, fdel, textwrap.dedent(doc))


class AcceptEncoding:
    """
    Represent an ``Accept-Encoding`` header.

    Base class for :class:`AcceptEncodingValidHeader`,
    :class:`AcceptEncodingNoHeader`, and :class:`AcceptEncodingInvalidHeader`.
    """

    # RFC 7231 Section 3.1.2.1 "Content Codings":
    # content-coding = token
    # Section 5.3.4 "Accept-Encoding":
    # Accept-Encoding  = #( codings [ weight ] )
    # codings          = content-coding / "identity" / "*"
    codings_re = token_re
    # "identity" (case-insensitive) and "*" are both already included in token
    # rule
    codings_n_weight_re = _item_n_weight_re(item_re=codings_re)
    codings_n_weight_compiled_re = re.compile(codings_n_weight_re)
    accept_encoding_compiled_re = _list_0_or_more__compiled_re(
        element_re=codings_n_weight_re
    )

    @classmethod
    def _python_value_to_header_str(cls, value):
        if isinstance(value, str):
            header_str = value
        else:
            if hasattr(value, "items"):
                value = sorted(value.items(), key=lambda item: item[1], reverse=True)

            if isinstance(value, (tuple, list)):
                result = []

                for item in value:
                    if isinstance(item, (tuple, list)):
                        item = _item_qvalue_pair_to_header_element(pair=item)
                    result.append(item)
                header_str = ", ".join(result)
            else:
                header_str = str(value)

        return header_str

    @classmethod
    def parse(cls, value):
        """
        Parse an ``Accept-Encoding`` header.

        :param value: (``str``) header value
        :return: If `value` is a valid ``Accept-Encoding`` header, returns an
                 iterator of (codings, quality value) tuples, as parsed from
                 the header from left to right.
        :raises ValueError: if `value` is an invalid header
        """
        # Check if header is valid
        # Using Python stdlib's `re` module, there is currently no way to check
        # the match *and* get all the groups using the same regex, so we have
        # to use one regex to check the match, and another to get the groups.

        if cls.accept_encoding_compiled_re.match(value) is None:
            raise ValueError("Invalid value for an Accept-Encoding header.")

        def generator(value):
            for match in cls.codings_n_weight_compiled_re.finditer(value):
                codings = match.group(1)
                qvalue = match.group(2)
                qvalue = float(qvalue) if qvalue else 1.0
                yield (codings, qvalue)

        return generator(value=value)


class AcceptEncodingValidHeader(AcceptEncoding):
    """
    Represent a valid ``Accept-Encoding`` header.

    A valid header is one that conforms to :rfc:`RFC 7231, section 5.3.4
    <7231#section-5.3.4>`.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptEncodingValidHeader.__add__`).
    """

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        A list of (*codings*, *qvalue*) tuples, where

        *codings* (``str``) is a content-coding, the string "``identity``", or
        "``*``"; and

        *qvalue* (``float``) is the quality value of the codings.
        """

        return self._parsed

    def __init__(self, header_value):
        """
        Create an :class:`AcceptEncodingValidHeader` instance.

        :param header_value: (``str``) header value.
        :raises ValueError: if `header_value` is an invalid value for an
                            ``Accept-Encoding`` header.
        """
        self._header_value = header_value
        self._parsed = list(self.parse(header_value))
        self._parsed_nonzero = [item for item in self.parsed if item[1]]
        # item[1] is the qvalue

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with content-coding, ``identity`` or ``*`` ``str``'s as
          keys, and qvalue ``float``'s as values
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (content-coding/``identity``/``*``, qvalue) ``tuple``
          or ``list``
        * an :class:`AcceptEncodingValidHeader`,
          :class:`AcceptEncodingNoHeader`, or
          :class:`AcceptEncodingInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or another
        :class:`AcceptEncodingValidHeader` instance, and the header value it
        represents is not ``''``, then the two header values are joined with
        ``', '``, and a new :class:`AcceptEncodingValidHeader` instance with
        the new header value is returned.

        If `other` is a valid header value or another
        :class:`AcceptEncodingValidHeader` instance representing a header value
        of ``''``; or if it is ``None`` or an :class:`AcceptEncodingNoHeader`
        instance; or if it is an invalid header value, or an
        :class:`AcceptEncodingInvalidHeader` instance, then a new
        :class:`AcceptEncodingValidHeader` instance with the same header value
        as ``self`` is returned.
        """

        if isinstance(other, AcceptEncodingValidHeader):
            if other.header_value == "":
                return self.__class__(header_value=self.header_value)
            else:
                return create_accept_encoding_header(
                    header_value=self.header_value + ", " + other.header_value
                )

        if isinstance(other, (AcceptEncodingNoHeader, AcceptEncodingInvalidHeader)):
            return self.__class__(header_value=self.header_value)

        return self._add_instance_and_non_accept_encoding_type(
            instance=self, other=other
        )

    def __bool__(self):
        """
        Return whether ``self`` represents a valid ``Accept-Encoding`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``True``.
        """

        return True

    __nonzero__ = __bool__  # Python 2

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of :meth:`AcceptEncodingValidHeader.__contains__` is
           currently being maintained for backward compatibility, but it will
           change in the future to better conform to the RFC.

        :param offer: (``str``) a content-coding or ``identity`` offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        The behavior of this method does not fully conform to :rfc:`7231`.
        It does not correctly interpret ``*``::

            >>> 'gzip' in AcceptEncodingValidHeader('gzip;q=0, *')
            True

        and does not handle the ``identity`` token correctly::

            >>> 'identity' in AcceptEncodingValidHeader('gzip')
            False
        """
        warnings.warn(
            "The behavior of AcceptEncodingValidHeader.__contains__ is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )

        for mask, _quality in self._parsed_nonzero:
            if self._old_match(mask, offer):
                return True

    def __iter__(self):
        """
        Return all the ranges with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the (content-coding/``identity``/``*``) items
                 in the header with non-0 qvalues, in descending order of
                 qvalue. If two items have the same qvalue, they are returned
                 in the order of their positions in the header, from left to
                 right.

        Please note that this is a simple filter for the items in the header
        with non-0 qvalues, and is not necessarily the same as what the client
        prefers, e.g. ``'gzip;q=0, *'`` means 'everything but gzip', but
        ``list(instance)`` would return only ``['*']``.
        """
        warnings.warn(
            "The behavior of AcceptEncodingLanguageValidHeader.__iter__ is "
            "currently maintained for backward compatibility, but will change"
            " in the future.",
            DeprecationWarning,
        )

        for mask, _quality in sorted(
            self._parsed_nonzero, key=lambda i: i[1], reverse=True
        ):
            yield mask

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptEncodingValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_encoding_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{} ({!r})>".format(self.__class__.__name__, str(self))

    def __str__(self):
        r"""
        Return a tidied up version of the header value.

        e.g. If the ``header_value`` is ``",\t, a ;\t q=0.20 , b ,',"``,
        ``str(instance)`` returns ``"a;q=0.2, b, '"``.
        """
        return ", ".join(
            _item_qvalue_pair_to_header_element(pair=tuple_) for tuple_ in self.parsed
        )

    def _add_instance_and_non_accept_encoding_type(
        self, instance, other, instance_on_the_right=False
    ):
        if not other:
            return self.__class__(header_value=instance.header_value)

        other_header_value = self._python_value_to_header_str(value=other)

        if other_header_value == "":
            # if ``other`` is an object whose type we don't recognise, and
            # str(other) returns ''
            return self.__class__(header_value=instance.header_value)

        try:
            self.parse(value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__(header_value=instance.header_value)

        new_header_value = (
            (other_header_value + ", " + instance.header_value)
            if instance_on_the_right
            else (instance.header_value + ", " + other_header_value)
        )
        return self.__class__(header_value=new_header_value)

    def _old_match(self, mask, offer):
        """
        Return whether content-coding offer matches codings header item.

        .. warning::

           This is maintained for backward compatibility, and will be
           deprecated in the future.

        This method was WebOb's old criterion for deciding whether a
        content-coding offer matches a header item (content-coding,
        ``identity`` or ``*``), used in

        - :meth:`AcceptCharsetValidHeader.__contains__`
        - :meth:`AcceptCharsetValidHeader.best_match`
        - :meth:`AcceptCharsetValidHeader.quality`

        It does not conform to :rfc:`RFC 7231, section 5.3.4
        <7231#section-5.3.4>` in that it does not interpret ``*`` values in the
        header correctly: ``*`` should only match content-codings not mentioned
        elsewhere in the header.
        """
        return mask == "*" or offer.lower() == mask.lower()

    def acceptable_offers(self, offers):
        """
        Return the offers that are acceptable according to the header.

        The offers are returned in descending order of preference, where
        preference is indicated by the qvalue of the item (content-coding,
        "identity" or "*") in the header that matches the offer.

        This uses the matching rules described in :rfc:`RFC 7231, section 5.3.4
        <7231#section-5.3.4>`.

        :param offers: ``iterable`` of ``str``s, where each ``str`` is a
                       content-coding or the string ``identity`` (the token
                       used to represent "no encoding")
        :return: A list of tuples of the form (content-coding or "identity",
                 qvalue), in descending order of qvalue. Where two offers have
                 the same qvalue, they are returned in the same order as their
                 order in `offers`.

        Use the string ``'identity'`` (without the quotes) in `offers` to
        indicate an offer with no content-coding. From the RFC: 'If the
        representation has no content-coding, then it is acceptable by default
        unless specifically excluded by the Accept-Encoding field stating
        either "identity;q=0" or "\\*;q=0" without a more specific entry for
        "identity".' The RFC does not specify the qvalue that should be
        assigned to the representation/offer with no content-coding; this
        implementation assigns it a qvalue of 1.0.
        """
        lowercased_parsed = [
            (codings.lower(), qvalue) for (codings, qvalue) in self.parsed
        ]
        lowercased_offers = [offer.lower() for offer in offers]

        not_acceptable_codingss = set()
        acceptable_codingss = dict()
        asterisk_qvalue = None

        for codings, qvalue in lowercased_parsed:
            if codings == "*":
                if asterisk_qvalue is None:
                    asterisk_qvalue = qvalue
            elif (
                codings not in acceptable_codingss
                and codings not in not_acceptable_codingss
                # if we have not already encountered this codings in the header
            ):
                if qvalue == 0.0:
                    not_acceptable_codingss.add(codings)
                else:
                    acceptable_codingss[codings] = qvalue
        acceptable_codingss = list(acceptable_codingss.items())
        # Sort acceptable_codingss by qvalue, descending order
        acceptable_codingss.sort(key=lambda tuple_: tuple_[1], reverse=True)

        filtered_offers = []
        for index, offer in enumerate(lowercased_offers):
            # If offer matches a non-* codings with q=0, it is filtered out
            if any(((offer == codings) for codings in not_acceptable_codingss)):
                continue

            matched_codings_qvalue = None
            for codings, qvalue in acceptable_codingss:
                if offer == codings:
                    matched_codings_qvalue = qvalue
                    break
            else:
                if asterisk_qvalue:
                    matched_codings_qvalue = asterisk_qvalue
                elif asterisk_qvalue != 0.0 and offer == "identity":
                    matched_codings_qvalue = 1.0
            if matched_codings_qvalue is not None:  # if there was a match
                filtered_offers.append((offers[index], matched_codings_qvalue, index))

        # sort by position in `offers` argument, ascending
        filtered_offers.sort(key=lambda tuple_: tuple_[2])
        # When qvalues are tied, position in `offers` is the tiebreaker.

        # sort by qvalue, descending
        filtered_offers.sort(key=lambda tuple_: tuple_[1], reverse=True)

        return [(item[0], item[1]) for item in filtered_offers]
        # (offer, qvalue), dropping the position

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of `offers`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

           :meth:`AcceptEncodingValidHeader.best_match` uses its own algorithm
           (one not specified in :rfc:`RFC 7231 <7231>`) to determine what is a
           best match. The algorithm has many issues, and does not conform to
           the RFC.

        Each offer in `offers` is checked against each non-``q=0`` item
        (content-coding/``identity``/``*``) in the header. If the two are a
        match according to WebOb's old criterion for a match, the quality value
        of the match is the qvalue of the item from the header multiplied by
        the server quality value of the offer (if the server quality value is
        not supplied, it is 1).

        The offer in the match with the highest quality value is the best
        match. If there is more than one match with the highest qvalue, the one
        that shows up first in `offers` is the best match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` *codings*,
                         or a (*codings*, server quality value) ``tuple`` or
                         ``list``, where *codings* is either a content-coding,
                         or the string ``identity`` (which represents *no
                         encoding*). ``str`` and ``tuple``/``list`` elements
                         may be mixed within the iterable.

        :param default_match: (optional, any type) the value to be returned if
                              there is no match

        :return: (``str``, or the type of `default_match`)

                 | The offer that is the best match. If there is no match, the
                   value of `default_match` is returned.

        This method does not conform to :rfc:`RFC 7231, section 5.3.4
        <7231#section-5.3.4>`, in that it does not correctly interpret ``*``::

            >>> AcceptEncodingValidHeader('gzip;q=0, *').best_match(['gzip'])
            'gzip'

        and does not handle the ``identity`` token correctly::

            >>> instance = AcceptEncodingValidHeader('gzip')
            >>> instance.best_match(['identity']) is None
            True
        """
        warnings.warn(
            "The behavior of AcceptEncodingValidHeader.best_match is "
            "currently being maintained for backward compatibility, but it "
            "will be deprecated in the future, as it does not conform to the"
            " RFC.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        matched_by = "*/*"
        for offer in offers:
            if isinstance(offer, (tuple, list)):
                offer, server_quality = offer
            else:
                server_quality = 1
            for item in self._parsed_nonzero:
                mask = item[0]
                quality = item[1]
                possible_quality = server_quality * quality
                if possible_quality < best_quality:
                    continue
                elif possible_quality == best_quality:
                    # 'text/plain' overrides 'message/*' overrides '*/*'
                    # (if all match w/ the same q=)
                    # [We can see that this was written for the Accept header,
                    # not the Accept-Encoding header.]
                    if matched_by.count("*") <= mask.count("*"):
                        continue
                if self._old_match(mask, offer):
                    best_quality = possible_quality
                    best_offer = offer
                    matched_by = mask
        return best_offer

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

        :param offer: (``str``) A content-coding, or ``identity``.
        :return: (``float`` or ``None``)

                 | The quality value from the header item
                   (content-coding/``identity``/``*``) that matches the
                   `offer`, or ``None`` if there is no match.

        The behavior of this method does not conform to :rfc:`RFC 7231, section
        5.3.4<7231#section-5.3.4>`, in that it does not correctly interpret
        ``*``::

            >>> AcceptEncodingValidHeader('gzip;q=0, *').quality('gzip')
            1.0

        and does not handle the ``identity`` token correctly::

            >>> AcceptEncodingValidHeader('gzip').quality('identity') is None
            True
        """
        warnings.warn(
            "The behavior of AcceptEncodingValidHeader.quality is currently "
            "being maintained for backward compatibility, but it will be "
            "deprecated in the future, as it does not conform to the RFC.",
            DeprecationWarning,
        )
        bestq = 0
        for mask, q in self.parsed:
            if self._old_match(mask, offer):
                bestq = max(bestq, q)
        return bestq or None


class _AcceptEncodingInvalidOrNoHeader(AcceptEncoding):
    """
    Represent when an ``Accept-Encoding`` header is invalid or not in request.

    This is the base class for the behaviour that
    :class:`.AcceptEncodingInvalidHeader` and :class:`.AcceptEncodingNoHeader`
    have in common.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``AcceptEncoding`` header has an invalid value. This implementation
    disregards the header when the header is invalid, so
    :class:`.AcceptEncodingInvalidHeader` and :class:`.AcceptEncodingNoHeader`
    have much behaviour in common.
    """

    def __bool__(self):
        """
        Return whether ``self`` represents a valid ``Accept-Encoding`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``False``.
        """
        return False

    __nonzero__ = __bool__  # Python 2

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of ``.__contains__`` for the ``Accept-Encoding``
           classes is currently being maintained for backward compatibility,
           but it will change in the future to better conform to the RFC.

        :param offer: (``str``) a content-coding or ``identity`` offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        For this class, either there is no ``Accept-Encoding`` header in the
        request, or the header is invalid, so any content-coding is acceptable,
        and this always returns ``True``.
        """
        warnings.warn(
            "The behavior of .__contains__ for the Accept-Encoding classes is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )
        return True

    def __iter__(self):
        """
        Return all the header items with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the (content-coding/``identity``/``*``) items
                 in the header with non-0 qvalues, in descending order of
                 qvalue. If two items have the same qvalue, they are returned
                 in the order of their positions in the header, from left to
                 right.

        When there is no ``Accept-Encoding`` header in the request or the
        header is invalid, there are no items in the header, so this always
        returns an empty iterator.
        """
        warnings.warn(
            "The behavior of AcceptEncodingValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )
        return iter(())

    def acceptable_offers(self, offers):
        """
        Return the offers that are acceptable according to the header.

        :param offers: ``iterable`` of ``str``s, where each ``str`` is a
                       content-coding or the string ``identity`` (the token
                       used to represent "no encoding")
        :return: When the header is invalid, or there is no ``Accept-Encoding``
                 header in the request, all `offers` are considered acceptable,
                 so this method returns a list of (content-coding or
                 "identity", qvalue) tuples where each offer in `offers` is
                 paired with the qvalue of 1.0, in the same order as in
                 `offers`.
        """
        return [(offer, 1.0) for offer in offers]

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of `offers`.

        This is the ``.best_match()`` method for when the header is invalid or
        not found in the request, corresponding to
        :meth:`AcceptEncodingValidHeader.best_match`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptEncodingValidHeader.best_match`).

        When the header is invalid, or there is no `Accept-Encoding` header in
        the request, all `offers` are considered acceptable, so the best match
        is the offer in `offers` with the highest server quality value (if the
        server quality value is not supplied for a media type, it is 1).

        If more than one offer in `offers` have the same highest server quality
        value, then the one that shows up first in `offers` is the best match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` *codings*,
                         or a (*codings*, server quality value) ``tuple`` or
                         ``list``, where *codings* is either a content-coding,
                         or the string ``identity`` (which represents *no
                         encoding*). ``str`` and ``tuple``/``list`` elements
                         may be mixed within the iterable.

        :param default_match: (optional, any type) the value to be returned if
                              `offers` is empty.

        :return: (``str``, or the type of `default_match`)

                 | The offer that has the highest server quality value. If
                   `offers` is empty, the value of `default_match` is returned.
        """
        warnings.warn(
            "The behavior of .best_match for the Accept-Encoding classes is "
            "currently being maintained for backward compatibility, but the "
            "method will be deprecated in the future, as its behavior is not "
            "specified in (and currently does not conform to) RFC 7231.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        for offer in offers:
            if isinstance(offer, (list, tuple)):
                offer, quality = offer
            else:
                quality = 1
            if quality > best_quality:
                best_offer = offer
                best_quality = quality
        return best_offer

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        This is the ``.quality()`` method for when the header is invalid or not
        found in the request, corresponding to
        :meth:`AcceptEncodingValidHeader.quality`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptEncodingValidHeader.quality`).

        :param offer: (``str``) A content-coding, or ``identity``.
        :return: (``float``) ``1.0``.

        When the ``Accept-Encoding`` header is invalid or not in the request,
        all offers are equally acceptable, so 1.0 is always returned.
        """
        warnings.warn(
            "The behavior of .quality for the Accept-Encoding classes is "
            "currently being maintained for backward compatibility, but the "
            "method will be deprecated in the future, as its behavior does "
            "not conform to RFC 7231.",
            DeprecationWarning,
        )
        return 1.0


class AcceptEncodingNoHeader(_AcceptEncodingInvalidOrNoHeader):
    """
    Represent when there is no ``Accept-Encoding`` header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptEncodingNoHeader.__add__`).
    """

    @property
    def header_value(self):
        """
        (``str`` or ``None``) The header value.

        As there is no header in the request, this is ``None``.
        """
        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As there is no header in the request, this is ``None``.
        """
        return self._parsed

    def __init__(self):
        """
        Create an :class:`AcceptEncodingNoHeader` instance.
        """
        self._header_value = None
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__()

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with content-coding, ``identity`` or ``*`` ``str``'s as
          keys, and qvalue ``float``'s as values
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (content-coding/``identity``/``*``, qvalue) ``tuple``
          or ``list``
        * an :class:`AcceptEncodingValidHeader`,
          :class:`AcceptEncodingNoHeader`, or
          :class:`AcceptEncodingInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an
        :class:`AcceptEncodingValidHeader` instance, a new
        :class:`AcceptEncodingValidHeader` instance with the valid header value
        is returned.

        If `other` is ``None``, an :class:`AcceptEncodingNoHeader` instance, an
        invalid header value, or an :class:`AcceptEncodingInvalidHeader`
        instance, a new :class:`AcceptEncodingNoHeader` instance is returned.
        """
        if isinstance(other, AcceptEncodingValidHeader):
            return AcceptEncodingValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptEncodingNoHeader, AcceptEncodingInvalidHeader)):
            return self.__class__()

        return self._add_instance_and_non_accept_encoding_type(
            instance=self, other=other
        )

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptEncodingNoHeader.__add__`.
        """
        return self.__add__(other=other)

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    def __str__(self):
        """Return the ``str`` ``'<no header in request>'``."""

        return "<no header in request>"

    def _add_instance_and_non_accept_encoding_type(self, instance, other):
        if other is None:
            return self.__class__()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptEncodingValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__()


class AcceptEncodingInvalidHeader(_AcceptEncodingInvalidOrNoHeader):
    """
    Represent an invalid ``Accept-Encoding`` header.

    An invalid header is one that does not conform to
    :rfc:`7231#section-5.3.4`.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept-Encoding`` header has an invalid value. This implementation
    disregards the header, and treats it as if there is no ``Accept-Encoding``
    header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptEncodingInvalidHeader.__add__`).
    """

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As the header is invalid and cannot be parsed, this is ``None``.
        """

        return self._parsed

    def __init__(self, header_value):
        """
        Create an :class:`AcceptEncodingInvalidHeader` instance.
        """
        self._header_value = header_value
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with content-coding, ``identity`` or ``*`` ``str``'s as
          keys, and qvalue ``float``'s as values
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (content-coding/``identity``/``*``, qvalue) ``tuple``
          or ``list``
        * an :class:`AcceptEncodingValidHeader`,
          :class:`AcceptEncodingNoHeader`, or
          :class:`AcceptEncodingInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an
        :class:`AcceptEncodingValidHeader` instance, then a new
        :class:`AcceptEncodingValidHeader` instance with the valid header value
        is returned.

        If `other` is ``None``, an :class:`AcceptEncodingNoHeader` instance, an
        invalid header value, or an :class:`AcceptEncodingInvalidHeader`
        instance, a new :class:`AcceptEncodingNoHeader` instance is returned.
        """

        if isinstance(other, AcceptEncodingValidHeader):
            return AcceptEncodingValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptEncodingNoHeader, AcceptEncodingInvalidHeader)):
            return AcceptEncodingNoHeader()

        return self._add_instance_and_non_accept_encoding_type(
            instance=self, other=other
        )

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptEncodingValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_encoding_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)
        # We do not display the header_value, as it is untrusted input. The
        # header_value could always be easily obtained from the .header_value
        # property.

    def __str__(self):
        """Return the ``str`` ``'<invalid header value>'``."""

        return "<invalid header value>"

    def _add_instance_and_non_accept_encoding_type(
        self, instance, other, instance_on_the_right=False
    ):
        if other is None:
            return AcceptEncodingNoHeader()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptEncodingValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return AcceptEncodingNoHeader()


def create_accept_encoding_header(header_value):
    """
    Create an object representing the ``Accept-Encoding`` header in a request.

    :param header_value: (``str``) header value
    :return: If `header_value` is ``None``, an :class:`AcceptEncodingNoHeader`
             instance.

             | If `header_value` is a valid ``Accept-Encoding`` header, an
               :class:`AcceptEncodingValidHeader` instance.

             | If `header_value` is an invalid ``Accept-Encoding`` header, an
               :class:`AcceptEncodingInvalidHeader` instance.
    """

    if header_value is None:
        return AcceptEncodingNoHeader()
    if isinstance(header_value, AcceptEncoding):
        return header_value.copy()
    try:
        return AcceptEncodingValidHeader(header_value=header_value)
    except ValueError:
        return AcceptEncodingInvalidHeader(header_value=header_value)


def accept_encoding_property():
    doc = """
        Property representing the ``Accept-Encoding`` header.

        (:rfc:`RFC 7231, section 5.3.4 <7231#section-5.3.4>`)

        The header value in the request environ is parsed and a new object
        representing the header is created every time we *get* the value of the
        property. (*set* and *del* change the header value in the request
        environ, and do not involve parsing.)
    """

    ENVIRON_KEY = "HTTP_ACCEPT_ENCODING"

    def fget(request):
        """Get an object representing the header in the request."""

        return create_accept_encoding_header(
            header_value=request.environ.get(ENVIRON_KEY)
        )

    def fset(request, value):
        """
        Set the corresponding key in the request environ.

        `value` can be:

        * ``None``
        * a ``str`` header value
        * a ``dict``, with content-coding, ``identity`` or ``*`` ``str``'s as
          keys, and qvalue ``float``'s as values
        * a ``tuple`` or ``list``, where each item is either a header element
          ``str``, or a (content-coding/``identity``/``*``, qvalue) ``tuple``
          or ``list``
        * an :class:`AcceptEncodingValidHeader`,
          :class:`AcceptEncodingNoHeader`, or
          :class:`AcceptEncodingInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``
        """

        if value is None or isinstance(value, AcceptEncodingNoHeader):
            fdel(request=request)
        else:
            if isinstance(
                value, (AcceptEncodingValidHeader, AcceptEncodingInvalidHeader)
            ):
                header_value = value.header_value
            else:
                header_value = AcceptEncoding._python_value_to_header_str(value=value)
            request.environ[ENVIRON_KEY] = header_value

    def fdel(request):
        """Delete the corresponding key from the request environ."""
        try:
            del request.environ[ENVIRON_KEY]
        except KeyError:
            pass

    return property(fget, fset, fdel, textwrap.dedent(doc))


class AcceptLanguage:
    """
    Represent an ``Accept-Language`` header.

    Base class for :class:`AcceptLanguageValidHeader`,
    :class:`AcceptLanguageNoHeader`, and :class:`AcceptLanguageInvalidHeader`.
    """

    # RFC 7231 Section 5.3.5 "Accept-Language":
    # Accept-Language = 1#( language-range [ weight ] )
    # language-range  =
    #           <language-range, see [RFC4647], Section 2.1>
    # RFC 4647 Section 2.1 "Basic Language Range":
    # language-range   = (1*8ALPHA *("-" 1*8alphanum)) / "*"
    # alphanum         = ALPHA / DIGIT
    lang_range_re = r"\*|" "(?:" "[A-Za-z]{1,8}" "(?:-[A-Za-z0-9]{1,8})*" ")"
    lang_range_n_weight_re = _item_n_weight_re(item_re=lang_range_re)
    lang_range_n_weight_compiled_re = re.compile(lang_range_n_weight_re)
    accept_language_compiled_re = _list_1_or_more__compiled_re(
        element_re=lang_range_n_weight_re
    )

    @classmethod
    def _python_value_to_header_str(cls, value):
        if isinstance(value, str):
            header_str = value
        else:
            if hasattr(value, "items"):
                value = sorted(value.items(), key=lambda item: item[1], reverse=True)

            if isinstance(value, (tuple, list)):
                result = []

                for element in value:
                    if isinstance(element, (tuple, list)):
                        element = _item_qvalue_pair_to_header_element(pair=element)
                    result.append(element)
                header_str = ", ".join(result)
            else:
                header_str = str(value)

        return header_str

    @classmethod
    def parse(cls, value):
        """
        Parse an ``Accept-Language`` header.

        :param value: (``str``) header value
        :return: If `value` is a valid ``Accept-Language`` header, returns an
                 iterator of (language range, quality value) tuples, as parsed
                 from the header from left to right.
        :raises ValueError: if `value` is an invalid header
        """
        # Check if header is valid
        # Using Python stdlib's `re` module, there is currently no way to check
        # the match *and* get all the groups using the same regex, so we have
        # to use one regex to check the match, and another to get the groups.

        if cls.accept_language_compiled_re.match(value) is None:
            raise ValueError("Invalid value for an Accept-Language header.")

        def generator(value):
            for match in cls.lang_range_n_weight_compiled_re.finditer(value):
                lang_range = match.group(1)
                qvalue = match.group(2)
                qvalue = float(qvalue) if qvalue else 1.0
                yield (lang_range, qvalue)

        return generator(value=value)


class AcceptLanguageValidHeader(AcceptLanguage):
    """
    Represent a valid ``Accept-Language`` header.

    A valid header is one that conforms to :rfc:`RFC 7231, section 5.3.5
    <7231#section-5.3.5>`.

    We take the reference from the ``language-range`` syntax rule in :rfc:`RFC
    7231, section 5.3.5 <7231#section-5.3.5>` to :rfc:`RFC 4647, section 2.1
    <4647#section-2.1>` to mean that only basic language ranges (and not
    extended language ranges) are expected in the ``Accept-Language`` header.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptLanguageValidHeader.__add__`).
    """

    def __init__(self, header_value):
        """
        Create an :class:`AcceptLanguageValidHeader` instance.

        :param header_value: (``str``) header value.
        :raises ValueError: if `header_value` is an invalid value for an
                            ``Accept-Language`` header.
        """
        self._header_value = header_value
        self._parsed = list(self.parse(header_value))
        self._parsed_nonzero = [item for item in self.parsed if item[1]]
        # item[1] is the qvalue

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        A list of (language range, quality value) tuples.
        """

        return self._parsed

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str``
        * a ``dict``, with language ranges as keys and qvalues as values
        * a ``tuple`` or ``list``, of language range ``str``'s or of ``tuple``
          or ``list`` (language range, qvalue) pairs (``str``'s and pairs can
          be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptLanguageValidHeader`,
          :class:`AcceptLanguageNoHeader`, or
          :class:`AcceptLanguageInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or another
        :class:`AcceptLanguageValidHeader` instance, the two header values are
        joined with ``', '``, and a new :class:`AcceptLanguageValidHeader`
        instance with the new header value is returned.

        If `other` is ``None``, an :class:`AcceptLanguageNoHeader` instance, an
        invalid header value, or an :class:`AcceptLanguageInvalidHeader`
        instance, a new :class:`AcceptLanguageValidHeader` instance with the
        same header value as ``self`` is returned.
        """

        if isinstance(other, AcceptLanguageValidHeader):
            return create_accept_language_header(
                header_value=self.header_value + ", " + other.header_value
            )

        if isinstance(other, (AcceptLanguageNoHeader, AcceptLanguageInvalidHeader)):
            return self.__class__(header_value=self.header_value)

        return self._add_instance_and_non_accept_language_type(
            instance=self, other=other
        )

    def __nonzero__(self):
        """
        Return whether ``self`` represents a valid ``Accept-Language`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``True``.
        """

        return True

    __bool__ = __nonzero__  # Python 3

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of :meth:`AcceptLanguageValidHeader.__contains__` is
           currently being maintained for backward compatibility, but it will
           change in the future to better conform to the RFC.

           What is 'acceptable' depends on the needs of your application.
           :rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>` suggests three
           matching schemes from :rfc:`RFC 4647 <4647>`, two of which WebOb
           supports with :meth:`AcceptLanguageValidHeader.basic_filtering` and
           :meth:`AcceptLanguageValidHeader.lookup` (we interpret the RFC to
           mean that Extended Filtering cannot apply for the
           ``Accept-Language`` header, as the header only accepts basic
           language ranges.) If these are not suitable for the needs of your
           application, you may need to write your own matching using
           :attr:`AcceptLanguageValidHeader.parsed`.

        :param offer: (``str``) language tag offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        This uses the old criterion of a match in
        :meth:`AcceptLanguageValidHeader._old_match`, which does not conform to
        :rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>` or any of the
        matching schemes suggested there. It also does not properly take into
        account ranges with ``q=0`` in the header::

            >>> 'en-gb' in AcceptLanguageValidHeader('en, en-gb;q=0')
            True
            >>> 'en' in AcceptLanguageValidHeader('en;q=0, *')
            True

        (See the docstring for :meth:`AcceptLanguageValidHeader._old_match` for
        other problems with the old criterion for a match.)
        """
        warnings.warn(
            "The behavior of AcceptLanguageValidHeader.__contains__ is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )

        for mask, _quality in self._parsed_nonzero:
            if self._old_match(mask, offer):
                return True

        return False

    def __iter__(self):
        """
        Return all the ranges with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the language ranges in the header with non-0
                 qvalues, in descending order of qvalue. If two ranges have the
                 same qvalue, they are returned in the order of their positions
                 in the header, from left to right.

        Please note that this is a simple filter for the ranges in the header
        with non-0 qvalues, and is not necessarily the same as what the client
        prefers, e.g. ``'en-gb;q=0, *'`` means 'everything but British
        English', but ``list(instance)`` would return only ``['*']``.
        """
        warnings.warn(
            "The behavior of AcceptLanguageValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )

        for mask, _quality in sorted(
            self._parsed_nonzero, key=lambda i: i[1], reverse=True
        ):
            yield mask

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptLanguageValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_language_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{} ({!r})>".format(self.__class__.__name__, str(self))

    def __str__(self):
        r"""
        Return a tidied up version of the header value.

        e.g. If the ``header_value`` is ``', \t,de;q=0.000 \t, es;q=1.000, zh,
        jp;q=0.210  ,'``, ``str(instance)`` returns ``'de;q=0, es, zh,
        jp;q=0.21'``.
        """
        return ", ".join(
            _item_qvalue_pair_to_header_element(pair=tuple_) for tuple_ in self.parsed
        )

    def _add_instance_and_non_accept_language_type(
        self, instance, other, instance_on_the_right=False
    ):
        if not other:
            return self.__class__(header_value=instance.header_value)

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            self.parse(value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__(header_value=instance.header_value)

        new_header_value = (
            (other_header_value + ", " + instance.header_value)
            if instance_on_the_right
            else (instance.header_value + ", " + other_header_value)
        )
        return self.__class__(header_value=new_header_value)

    def _old_match(self, mask, item):
        """
        Return whether a language tag matches a language range.

        .. warning::

           This is maintained for backward compatibility, and will be
           deprecated in the future.

        This method was WebOb's old criterion for deciding whether a language
        tag matches a language range, used in

        - :meth:`AcceptLanguageValidHeader.__contains__`
        - :meth:`AcceptLanguageValidHeader.best_match`
        - :meth:`AcceptLanguageValidHeader.quality`

        It does not conform to :rfc:`RFC 7231, section 5.3.5
        <7231#section-5.3.5>`, or any of the matching schemes suggested there.

        :param mask: (``str``)

                     | language range

        :param item: (``str``)

                     | language tag. Subtags in language tags are separated by
                       ``-`` (hyphen). If there are underscores (``_``) in this
                       argument, they will be converted to hyphens before
                       checking the match.

        :return: (``bool``) whether the tag in `item` matches the range in
                 `mask`.

        `mask` and `item` are a match if:

        - ``mask == *``.
        - ``mask == item``.
        - If the first subtag of `item` equals `mask`, or if the first subtag
          of `mask` equals `item`.
          This means that::

              >>> instance._old_match(mask='en-gb', item='en')
              True
              >>> instance._old_match(mask='en', item='en-gb')
              True

          Which is different from any of the matching schemes suggested in
          :rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>`, in that none of
          those schemes match both more *and* less specific tags.

          However, this method appears to be only designed for language tags
          and ranges with at most two subtags. So with an `item`/language tag
          with more than two subtags like ``zh-Hans-CN``::

              >>> instance._old_match(mask='zh', item='zh-Hans-CN')
              True
              >>> instance._old_match(mask='zh-Hans', item='zh-Hans-CN')
              False

          From commit history, this does not appear to have been from a
          decision to match only the first subtag, but rather because only
          language ranges and tags with at most two subtags were expected.
        """
        item = item.replace("_", "-").lower()
        mask = mask.lower()
        return (
            mask == "*"
            or item == mask
            or item.split("-")[0] == mask
            or item == mask.split("-")[0]
        )

    def basic_filtering(self, language_tags):
        """
        Return the tags that match the header, using Basic Filtering.

        This is an implementation of the Basic Filtering matching scheme,
        suggested as a matching scheme for the ``Accept-Language`` header in
        :rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>`, and defined in
        :rfc:`RFC 4647, section 3.3.1 <4647#section-3.3.1>`. It filters the
        tags in the `language_tags` argument and returns the ones that match
        the header according to the matching scheme.

        :param language_tags: (``iterable``) language tags
        :return: A list of tuples of the form (language tag, qvalue), in
                 descending order of qvalue. If two or more tags have the same
                 qvalue, they are returned in the same order as that in the
                 header of the ranges they matched. If the matched range is the
                 same for two or more tags (i.e. their matched ranges have the
                 same qvalue and the same position in the header), then they
                 are returned in the same order as that in the `language_tags`
                 argument. If `language_tags` is unordered, e.g. if it is a set
                 or a dict, then that order may not be reliable.

        For each tag in `language_tags`:

        1. If the tag matches a non-``*`` language range in the header with
           ``q=0`` (meaning "not acceptable", see :rfc:`RFC 7231, section 5.3.1
           <7231#section-5.3.1>`), the tag is filtered out.
        2. The non-``*`` language ranges in the header that do not have ``q=0``
           are considered in descending order of qvalue; where two or more
           language ranges have the same qvalue, they are considered in the
           order in which they appear in the header.
        3. A language range 'matches a particular language tag if, in a
           case-insensitive comparison, it exactly equals the tag, or if it
           exactly equals a prefix of the tag such that the first character
           following the prefix is "-".' (:rfc:`RFC 4647, section 3.3.1
           <4647#section-3.3.1>`)
        4. If the tag does not match any of the non-``*`` language ranges, and
           there is a ``*`` language range in the header, then if the ``*``
           language range has ``q=0``, the language tag is filtered out,
           otherwise the tag is considered a match.

        (If a range (``*`` or non-``*``) appears in the header more than once
        -- this would not make sense, but is nonetheless a valid header
        according to the RFC -- the first in the header is used for matching,
        and the others are ignored.)
        """
        # The Basic Filtering matching scheme as applied to the Accept-Language
        # header is very under-specified by RFCs 7231 and 4647. This
        # implementation combines the description of the matching scheme in RFC
        # 4647 and the rules of the Accept-Language header in RFC 7231 to
        # arrive at an algorithm for Basic Filtering as applied to the
        # Accept-Language header.

        lowercased_parsed = [
            (range_.lower(), qvalue) for (range_, qvalue) in self.parsed
        ]
        lowercased_tags = [tag.lower() for tag in language_tags]

        not_acceptable_ranges = set()
        acceptable_ranges = dict()
        asterisk_qvalue = None

        for position_in_header, (range_, qvalue) in enumerate(lowercased_parsed):
            if range_ == "*":
                if asterisk_qvalue is None:
                    asterisk_qvalue = qvalue
                    asterisk_position = position_in_header
            elif (
                range_ not in acceptable_ranges
                and range_ not in not_acceptable_ranges
                # if we have not already encountered this range in the header
            ):
                if qvalue == 0.0:
                    not_acceptable_ranges.add(range_)
                else:
                    acceptable_ranges[range_] = (qvalue, position_in_header)
        acceptable_ranges = [
            (range_, qvalue, position_in_header)
            for range_, (qvalue, position_in_header) in acceptable_ranges.items()
        ]
        # Sort acceptable_ranges by position_in_header, ascending order
        acceptable_ranges.sort(key=lambda tuple_: tuple_[2])
        # Sort acceptable_ranges by qvalue, descending order
        acceptable_ranges.sort(key=lambda tuple_: tuple_[1], reverse=True)
        # Sort guaranteed to be stable with Python >= 2.2, so position in
        # header is tiebreaker when two ranges have the same qvalue

        def match(tag, range_):
            # RFC 4647, section 2.1: 'A language range matches a particular
            # language tag if, in a case-insensitive comparison, it exactly
            # equals the tag, or if it exactly equals a prefix of the tag such
            # that the first character following the prefix is "-".'
            return (tag == range_) or tag.startswith(range_ + "-")
            # We can assume here that the language tags are valid tags, so we
            # do not have to worry about them being malformed and ending with
            # '-'.

        filtered_tags = []
        for index, tag in enumerate(lowercased_tags):
            # If tag matches a non-* range with q=0, it is filtered out
            if any((match(tag=tag, range_=range_) for range_ in not_acceptable_ranges)):
                continue

            matched_range_qvalue = None
            for range_, qvalue, position_in_header in acceptable_ranges:
                # acceptable_ranges is in descending order of qvalue, and tied
                # ranges are in ascending order of position_in_header, so the
                # first range_ that matches the tag is the best match
                if match(tag=tag, range_=range_):
                    matched_range_qvalue = qvalue
                    matched_range_position = position_in_header
                    break
            else:
                if asterisk_qvalue:
                    # From RFC 4647, section 3.3.1: '...HTTP/1.1 [RFC2616]
                    # specifies that the range "*" matches only languages not
                    # matched by any other range within an "Accept-Language"
                    # header.' (Though RFC 2616 is obsolete, and there is no
                    # mention of the meaning of "*" in RFC 7231, as the
                    # ``language-range`` syntax rule in RFC 7231 section 5.3.1
                    # directs us to RFC 4647, we can only assume that the
                    # meaning of "*" in the Accept-Language header remains the
                    # same).
                    matched_range_qvalue = asterisk_qvalue
                    matched_range_position = asterisk_position
            if matched_range_qvalue is not None:  # if there was a match
                filtered_tags.append(
                    (language_tags[index], matched_range_qvalue, matched_range_position)
                )

        # sort by matched_range_position, ascending
        filtered_tags.sort(key=lambda tuple_: tuple_[2])
        # When qvalues are tied, matched range position in the header is the
        # tiebreaker.

        # sort by qvalue, descending
        filtered_tags.sort(key=lambda tuple_: tuple_[1], reverse=True)

        return [(item[0], item[1]) for item in filtered_tags]
        # (tag, qvalue), dropping the matched_range_position

        # We return a list of tuples with qvalues, instead of just a set or
        # a list of language tags, because
        # RFC 4647 section 3.3: "If the language priority list contains more
        # than one range, the content returned is typically ordered in
        # descending level of preference, but it MAY be unordered, according to
        # the needs of the application or protocol."
        # We return the filtered tags in order of preference, each paired with
        # the qvalue of the range that was their best match, as the ordering
        # and the qvalues may well be needed in some applications, and a simple
        # set or list of language tags can always be easily obtained from the
        # returned list if the qvalues are not required. One use for qvalues,
        # for example, would be to indicate that two tags are equally preferred
        # (same qvalue), which we would not be able to do easily with a set or
        # a list without e.g. making a member of the set or list a sequence.

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of language tag `offers`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

           :meth:`AcceptLanguageValidHeader.best_match` uses its own algorithm
           (one not specified in :rfc:`RFC 7231 <7231>`) to determine what is a
           best match. The algorithm has many issues, and does not conform to
           :rfc:`RFC 7231 <7231>`.

           :meth:`AcceptLanguageValidHeader.lookup` is a possible alternative

           for finding a best match -- it conforms to, and is suggested as a
           matching scheme for the ``Accept-Language`` header in, :rfc:`RFC
           7231, section 5.3.5 <7231#section-5.3.5>` -- but please be aware
           that there are differences in how it determines what is a best
           match. If that is not suitable for the needs of your application,
           you may need to write your own matching using
           :attr:`AcceptLanguageValidHeader.parsed`.

        Each language tag in `offers` is checked against each non-0 range in
        the header. If the two are a match according to WebOb's old criterion

        for a match, the quality value of the match is the qvalue of the
        language range from the header multiplied by the server quality value
        of the offer (if the server quality value is not supplied, it is 1).

        The offer in the match with the highest quality value is the best
        match. If there is more than one match with the highest qvalue, the
        match where the language range has a lower number of '*'s is the best
        match. If the two have the same number of '*'s, the one that shows up
        first in `offers` is the best match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` language
                         tag, or a (language tag, server quality value)
                         ``tuple`` or ``list``. (The two may be mixed in the
                         iterable.)

        :param default_match: (optional, any type) the value to be returned if
                              there is no match

        :return: (``str``, or the type of `default_match`)

                 | The language tag that is the best match. If there is no
                   match, the value of `default_match` is returned.


        **Issues**:

        - Incorrect tiebreaking when quality values of two matches are the same
          (https://github.com/Pylons/webob/issues/256)::

              >>> header = AcceptLanguageValidHeader(
              ...     header_value='en-gb;q=1, en;q=0.8'
              ... )
              >>> header.best_match(offers=['en', 'en-GB'])
              'en'
              >>> header.best_match(offers=['en-GB', 'en'])
              'en-GB'

              >>> header = AcceptLanguageValidHeader(header_value='en-gb, en')
              >>> header.best_match(offers=['en', 'en-gb'])
              'en'
              >>> header.best_match(offers=['en-gb', 'en'])
              'en-gb'

        - Incorrect handling of ``q=0``::

              >>> header = AcceptLanguageValidHeader(header_value='en;q=0, *')
              >>> header.best_match(offers=['en'])
              'en'

              >>> header = AcceptLanguageValidHeader(header_value='fr, en;q=0')
              >>> header.best_match(offers=['en-gb'], default_match='en')
              'en'

        - Matching only takes into account the first subtag when matching a
          range with more specific or less specific tags::

              >>> header = AcceptLanguageValidHeader(header_value='zh')
              >>> header.best_match(offers=['zh-Hans-CN'])
              'zh-Hans-CN'
              >>> header = AcceptLanguageValidHeader(header_value='zh-Hans')
              >>> header.best_match(offers=['zh-Hans-CN'])
              >>> header.best_match(offers=['zh-Hans-CN']) is None
              True

              >>> header = AcceptLanguageValidHeader(header_value='zh-Hans-CN')
              >>> header.best_match(offers=['zh'])
              'zh'
              >>> header.best_match(offers=['zh-Hans'])
              >>> header.best_match(offers=['zh-Hans']) is None
              True

        """
        warnings.warn(
            "The behavior of AcceptLanguageValidHeader.best_match is "
            "currently being maintained for backward compatibility, but it "
            "will be deprecated in the future as it does not conform to the "
            "RFC.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        matched_by = "*/*"
        # [We can see that this was written for the ``Accept`` header and not
        # the ``Accept-Language`` header, as there are no '/'s in a valid
        # ``Accept-Language`` header.]
        for offer in offers:
            if isinstance(offer, (tuple, list)):
                offer, server_quality = offer
            else:
                server_quality = 1
            for mask, quality in self._parsed_nonzero:
                possible_quality = server_quality * quality
                if possible_quality < best_quality:
                    continue
                elif possible_quality == best_quality:
                    # 'text/plain' overrides 'message/*' overrides '*/*'
                    # (if all match w/ the same q=)
                    if matched_by.count("*") <= mask.count("*"):
                        continue
                    # [This tiebreaking was written for the `Accept` header. A
                    # basic language range in a valid ``Accept-Language``
                    # header can only be either '*' or a range with no '*' in
                    # it. This happens to work here, but is not sufficient as a
                    # tiebreaker.
                    #
                    # A best match here, given this algorithm uses
                    # self._old_match() which matches both more *and* less
                    # specific tags, should be the match where the absolute
                    # value of the difference between the subtag counts of
                    # `mask` and `offer` is the lowest.]
                if self._old_match(mask, offer):
                    best_quality = possible_quality
                    best_offer = offer
                    matched_by = mask
        return best_offer

    def lookup(self, language_tags, default_range=None, default_tag=None, default=None):
        """
        Return the language tag that best matches the header, using Lookup.

        This is an implementation of the Lookup matching scheme,
        suggested as a matching scheme for the ``Accept-Language`` header in
        :rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>`, and described in
        :rfc:`RFC 4647, section 3.4 <4647#section-3.4>`.

        Each language range in the header is considered in turn, by descending
        order of qvalue; where qvalues are tied, ranges are considered from
        left to right.

        Each language range in the header represents the most specific tag that
        is an acceptable match: Lookup progressively truncates subtags from the
        end of the range until a matching language tag is found. An example is
        given in :rfc:`RFC 4647, section 3.4 <4647#section-3.4>`, under
        "Example of a Lookup Fallback Pattern":

        ::

            Range to match: zh-Hant-CN-x-private1-private2
            1. zh-Hant-CN-x-private1-private2
            2. zh-Hant-CN-x-private1
            3. zh-Hant-CN
            4. zh-Hant
            5. zh
            6. (default)

        :param language_tags: (``iterable``) language tags

        :param default_range: (optional, ``None`` or ``str``)

                              | If Lookup finds no match using the ranges in
                                the header, and this argument is not None,
                                Lookup will next attempt to match the range in
                                this argument, using the same subtag
                                truncation.

                              | `default_range` cannot be '*', as '*' is
                                skipped in Lookup. See :ref:`note
                                <acceptparse-lookup-asterisk-note>`.

                              | This parameter corresponds to the functionality
                                described in :rfc:`RFC 4647, section 3.4.1
                                <4647#section-3.4.1>`, in the paragraph
                                starting with "One common way to provide for a
                                default is to allow a specific language range
                                to be set as the default..."

        :param default_tag: (optional, ``None`` or ``str``)

                            | At least one of `default_tag` or `default` must
                              be supplied as an argument to the method, to
                              define the defaulting behaviour.

                            | If Lookup finds no match using the ranges in the
                              header and `default_range`, this argument is not
                              ``None``, and it does not match any range in the
                              header with ``q=0`` (exactly, with no subtag
                              truncation), then this value is returned.

                            | This parameter corresponds to "return a
                              particular language tag designated for the
                              operation", one of the examples of "defaulting
                              behavior" described in :rfc:`RFC 4647, section
                              3.4.1 <4647#section-3.4.1>`.

        :param default: (optional, ``None`` or any type, including a callable)

                        | At least one of `default_tag` or `default` must be
                          supplied as an argument to the method, to define the
                          defaulting behaviour.

                        | If Lookup finds no match using the ranges in the
                          header and `default_range`, and `default_tag` is
                          ``None`` or not acceptable because it matches a
                          ``q=0`` range in the header, then Lookup will next
                          examine the `default` argument.

                        | If `default` is a callable, it will be called, and
                          the callable's return value will be returned.

                        | If `default` is not a callable, the value itself will
                          be returned.

                        | The difference between supplying a ``str`` to
                          `default_tag` and `default` is that `default_tag` is
                          checked against ``q=0`` ranges in the header to see
                          if it matches one of the ranges specified as not
                          acceptable, whereas a ``str`` for the `default`
                          argument is simply returned.

                        | This parameter corresponds to the "defaulting
                          behavior" described in :rfc:`RFC 4647, section 3.4.1
                          <4647#section-3.4.1>`

        :return: (``str``, ``None``, or any type)

                 | The best match according to the Lookup matching scheme, or a
                   return value from one of the default arguments.

        **Notes**:

        .. _acceptparse-lookup-asterisk-note:

        - Lookup's behaviour with '*' language ranges in the header may be
          surprising. From :rfc:`RFC 4647, section 3.4 <4647#section-3.4>`:

              In the lookup scheme, this range does not convey enough
              information by itself to determine which language tag is most
              appropriate, since it matches everything.  If the language range
              "*" is followed by other language ranges, it is skipped.  If the
              language range "*" is the only one in the language priority list
              or if no other language range follows, the default value is
              computed and returned.

          So

          ::

              >>> header = AcceptLanguageValidHeader('de, zh, *')
              >>> header.lookup(language_tags=['ja', 'en'], default='default')
              'default'

        - Any tags in `language_tags` and `default_tag` and any tag matched
          during the subtag truncation search for `default_range`, that are an
          exact match for a non-``*`` range with ``q=0`` in the header, are
          considered not acceptable and ruled out.

        - If there is a ``*;q=0`` in the header, then `default_range` and
          `default_tag` have no effect, as ``*;q=0`` means that all languages
          not already matched by other ranges within the header are
          unacceptable.
        """
        if default_tag is None and default is None:
            raise TypeError(
                "`default_tag` and `default` arguments cannot both be None."
            )

        # We need separate `default_tag` and `default` arguments because if we
        # only had the `default` argument, there would be no way to tell
        # whether a str is a language tag (in which case we have to check
        # whether it has been specified as not acceptable with a q=0 range in
        # the header) or not (in which case we can just return the value).

        if default_range == "*":
            raise ValueError("default_range cannot be *.")

        parsed = list(self.parsed)

        tags = language_tags
        not_acceptable_ranges = []
        acceptable_ranges = []

        asterisk_q0_found = False
        # Whether there is a '*' range in the header with q=0
        # While '*' is skipped in Lookup because it "does not convey enough
        # information by itself to determine which language tag is most
        # appropriate" (RFC 4647, section 3.4), '*;q=0' is clear in meaning:
        # languages not matched by any other range within the header are not
        # acceptable.

        for range_, qvalue in parsed:
            if range_ == "*":
                if qvalue == 0.0:
                    asterisk_q0_found = True
            elif qvalue == 0.0:
                not_acceptable_ranges.append(range_.lower())
            else:
                acceptable_ranges.append((range_, qvalue))
                # range_ is .lower()ed later
        # Sort acceptable_ranges by qvalue, descending order
        acceptable_ranges.sort(key=lambda tuple_: tuple_[1], reverse=True)
        # Sort guaranteed to be stable with Python >= 2.2, so position in
        # header is tiebreaker when two ranges have the same qvalue

        acceptable_ranges = [tuple_[0] for tuple_ in acceptable_ranges]
        lowered_tags = [tag.lower() for tag in tags]

        def best_match(range_):
            subtags = range_.split("-")
            while True:
                for index, tag in enumerate(lowered_tags):
                    if tag in not_acceptable_ranges:
                        continue
                        # We think a non-'*' range with q=0 represents only
                        # itself as a tag, and there should be no falling back
                        # with subtag truncation. For example, with
                        # 'en-gb;q=0', it should not mean 'en;q=0': the client
                        # is unlikely to expect that specifying 'en-gb' as not
                        # acceptable would mean that 'en' is also not
                        # acceptable. There is no guidance on this at all in
                        # the RFCs, so it is left to us to decide how it should
                        # work.

                    if tag == range_:
                        return tags[index]  # return the pre-lowered tag

                try:
                    subtag_before_this = subtags[-2]
                except IndexError:  # len(subtags) == 1
                    break
                # len(subtags) >= 2
                if len(subtag_before_this) == 1 and (
                    subtag_before_this.isdigit() or subtag_before_this.isalpha()
                ):  # if subtag_before_this is a single-letter or -digit subtag
                    subtags.pop(-1)  # pop twice instead of once
                subtags.pop(-1)
                range_ = "-".join(subtags)

        for range_ in acceptable_ranges:
            match = best_match(range_=range_.lower())
            if match is not None:
                return match

        if not asterisk_q0_found:
            if default_range is not None:
                lowered_default_range = default_range.lower()
                match = best_match(range_=lowered_default_range)
                if match is not None:
                    return match

            if default_tag is not None:
                lowered_default_tag = default_tag.lower()
                if lowered_default_tag not in not_acceptable_ranges:
                    return default_tag

        try:
            return default()
        except TypeError:  # default is not a callable
            return default

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future.

           :meth:`AcceptLanguageValidHeader.quality` uses its own algorithm
           (one not specified in :rfc:`RFC 7231 <7231>`) to determine what is a
           best match. The algorithm has many issues, and does not conform to
           :rfc:`RFC 7231 <7231>`.

           What should be considered a match depends on the needs of your
           application (for example, should a language range in the header
           match a more specific language tag offer, or a less specific tag
           offer?) :rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>` suggests
           three matching schemes from :rfc:`RFC 4647 <4647>`, two of which
           WebOb supports with
           :meth:`AcceptLanguageValidHeader.basic_filtering` and
           :meth:`AcceptLanguageValidHeader.lookup` (we interpret the RFC to
           mean that Extended Filtering cannot apply for the
           ``Accept-Language`` header, as the header only accepts basic
           language ranges.) :meth:`AcceptLanguageValidHeader.basic_filtering`
           returns quality values with the matched language tags.
           :meth:`AcceptLanguageValidHeader.lookup` returns a language tag
           without the quality value, but the quality value is less likely to
           be useful when we are looking for a best match.

           If these are not suitable or sufficient for the needs of your
           application, you may need to write your own matching using
           :attr:`AcceptLanguageValidHeader.parsed`.

        :param offer: (``str``) language tag offer
        :return: (``float`` or ``None``)

                 | The highest quality value from the language range(s) that
                   match the `offer`, or ``None`` if there is no match.


        **Issues**:

        - Incorrect handling of ``q=0`` and ``*``::

              >>> header = AcceptLanguageValidHeader(header_value='en;q=0, *')
              >>> header.quality(offer='en')
              1.0

        - Matching only takes into account the first subtag when matching a
          range with more specific or less specific tags::

              >>> header = AcceptLanguageValidHeader(header_value='zh')
              >>> header.quality(offer='zh-Hans-CN')
              1.0
              >>> header = AcceptLanguageValidHeader(header_value='zh-Hans')
              >>> header.quality(offer='zh-Hans-CN')
              >>> header.quality(offer='zh-Hans-CN') is None
              True

              >>> header = AcceptLanguageValidHeader(header_value='zh-Hans-CN')
              >>> header.quality(offer='zh')
              1.0
              >>> header.quality(offer='zh-Hans')
              >>> header.quality(offer='zh-Hans') is None
              True

        """
        warnings.warn(
            "The behavior of AcceptLanguageValidHeader.quality is"
            "currently being maintained for backward compatibility, but it "
            "will be deprecated in the future as it does not conform to the "
            "RFC.",
            DeprecationWarning,
        )
        bestq = 0
        for mask, q in self.parsed:
            if self._old_match(mask, offer):
                bestq = max(bestq, q)
        return bestq or None


class _AcceptLanguageInvalidOrNoHeader(AcceptLanguage):
    """
    Represent when an ``Accept-Language`` header is invalid or not in request.

    This is the base class for the behaviour that
    :class:`.AcceptLanguageInvalidHeader` and :class:`.AcceptLanguageNoHeader`
    have in common.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept-Language`` header has an invalid value. This implementation
    disregards the header when the header is invalid, so
    :class:`.AcceptLanguageInvalidHeader` and :class:`.AcceptLanguageNoHeader`
    have much behaviour in common.
    """

    def __nonzero__(self):
        """
        Return whether ``self`` represents a valid ``Accept-Language`` header.

        Return ``True`` if ``self`` represents a valid header, and ``False`` if
        it represents an invalid header, or the header not being in the
        request.

        For this class, it always returns ``False``.
        """
        return False

    __bool__ = __nonzero__  # Python 3

    def __contains__(self, offer):
        """
        Return ``bool`` indicating whether `offer` is acceptable.

        .. warning::

           The behavior of ``.__contains__`` for the ``AcceptLanguage`` classes
           is currently being maintained for backward compatibility, but it
           will change in the future to better conform to the RFC.

        :param offer: (``str``) language tag offer
        :return: (``bool``) Whether ``offer`` is acceptable according to the
                 header.

        For this class, either there is no ``Accept-Language`` header in the
        request, or the header is invalid, so any language tag is acceptable,
        and this always returns ``True``.
        """
        warnings.warn(
            "The behavior of .__contains__ for the AcceptLanguage classes is "
            "currently being maintained for backward compatibility, but it "
            "will change in the future to better conform to the RFC.",
            DeprecationWarning,
        )
        return True

    def __iter__(self):
        """
        Return all the ranges with non-0 qvalues, in order of preference.

        .. warning::

           The behavior of this method is currently maintained for backward
           compatibility, but will change in the future.

        :return: iterator of all the language ranges in the header with non-0
                 qvalues, in descending order of qvalue. If two ranges have the
                 same qvalue, they are returned in the order of their positions
                 in the header, from left to right.

        For this class, either there is no ``Accept-Language`` header in the
        request, or the header is invalid, so there are no language ranges, and
        this always returns an empty iterator.
        """
        warnings.warn(
            "The behavior of AcceptLanguageValidHeader.__iter__ is currently "
            "maintained for backward compatibility, but will change in the "
            "future.",
            DeprecationWarning,
        )
        return iter(())

    def basic_filtering(self, language_tags):
        """
        Return the tags that match the header, using Basic Filtering.

        :param language_tags: (``iterable``) language tags
        :return: A list of tuples of the form (language tag, qvalue), in
                 descending order of preference.

        When the header is invalid and when the header is not in the request,
        there are no matches, so this method always returns an empty list.
        """
        return []

    def best_match(self, offers, default_match=None):
        """
        Return the best match from the sequence of language tag `offers`.

        This is the ``.best_match()`` method for when the header is invalid or
        not found in the request, corresponding to
        :meth:`AcceptLanguageValidHeader.best_match`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptLanguageValidHeader.best_match`).

        When the header is invalid, or there is no `Accept-Language` header in
        the request, any of the language tags in `offers` are considered
        acceptable, so the best match is the tag in `offers` with the highest
        server quality value (if the server quality value is not supplied, it
        is 1).

        If more than one language tags in `offers` have the same highest server
        quality value, then the one that shows up first in `offers` is the best
        match.

        :param offers: (iterable)

                       | Each item in the iterable may be a ``str`` language
                         tag, or a (language tag, server quality value)
                         ``tuple`` or ``list``. (The two may be mixed in the
                         iterable.)

        :param default_match: (optional, any type) the value to be returned if
                              `offers` is empty.

        :return: (``str``, or the type of `default_match`)

                 | The language tag that has the highest server quality value.
                   If `offers` is empty, the value of `default_match` is
                   returned.
        """
        warnings.warn(
            "The behavior of .best_match for the AcceptLanguage classes is "
            "currently being maintained for backward compatibility, but the "
            "method will be deprecated in the future, as its behavior is not "
            "specified in (and currently does not conform to) RFC 7231.",
            DeprecationWarning,
        )
        best_quality = -1
        best_offer = default_match
        for offer in offers:
            if isinstance(offer, (list, tuple)):
                offer, quality = offer
            else:
                quality = 1
            if quality > best_quality:
                best_offer = offer
                best_quality = quality
        return best_offer

    def lookup(
        self, language_tags=None, default_range=None, default_tag=None, default=None
    ):
        """
        Return the language tag that best matches the header, using Lookup.

        When the header is invalid, or there is no ``Accept-Language`` header
        in the request, all language tags are considered acceptable, so it is
        as if the header is '*'. As specified for the Lookup matching scheme in
        :rfc:`RFC 4647, section 3.4 <4647#section-3.4>`, when the header is
        '*', the default value is to be computed and returned. So this method
        will ignore the `language_tags` and `default_range` arguments, and
        proceed to `default_tag`, then `default`.

        :param language_tags: (optional, any type)

                              | This argument is ignored, and is only used as a
                                placeholder so that the method signature
                                corresponds to that of
                                :meth:`AcceptLanguageValidHeader.lookup`.

        :param default_range: (optional, any type)

                              | This argument is ignored, and is only used as a
                                placeholder so that the method signature
                                corresponds to that of
                                :meth:`AcceptLanguageValidHeader.lookup`.

        :param default_tag: (optional, ``None`` or ``str``)

                            | At least one of `default_tag` or `default` must
                              be supplied as an argument to the method, to
                              define the defaulting behaviour.

                            | If this argument is not ``None``, then it is
                              returned.

                            | This parameter corresponds to "return a
                              particular language tag designated for the
                              operation", one of the examples of "defaulting
                              behavior" described in :rfc:`RFC 4647, section
                              3.4.1 <4647#section-3.4.1>`.

        :param default: (optional, ``None`` or any type, including a callable)

                        | At least one of `default_tag` or `default` must be
                          supplied as an argument to the method, to define the
                          defaulting behaviour.

                        | If `default_tag` is ``None``, then Lookup will next
                          examine the `default` argument.

                        | If `default` is a callable, it will be called, and
                          the callable's return value will be returned.

                        | If `default` is not a callable, the value itself will
                          be returned.

                        | This parameter corresponds to the "defaulting
                          behavior" described in :rfc:`RFC 4647, section 3.4.1
                          <4647#section-3.4.1>`

        :return: (``str``, or any type)

                 | the return value from `default_tag` or `default`.
        """
        if default_tag is None and default is None:
            raise TypeError(
                "`default_tag` and `default` arguments cannot both be None."
            )

        if default_tag is not None:
            return default_tag

        try:
            return default()
        except TypeError:  # default is not a callable
            return default

    def quality(self, offer):
        """
        Return quality value of given offer, or ``None`` if there is no match.

        This is the ``.quality()`` method for when the header is invalid or not
        found in the request, corresponding to
        :meth:`AcceptLanguageValidHeader.quality`.

        .. warning::

           This is currently maintained for backward compatibility, and will be
           deprecated in the future (see the documentation for
           :meth:`AcceptLanguageValidHeader.quality`).

        :param offer: (``str``) language tag offer
        :return: (``float``) ``1.0``.

        When the ``Accept-Language`` header is invalid or not in the request,
        all offers are equally acceptable, so 1.0 is always returned.
        """
        warnings.warn(
            "The behavior of .quality for the AcceptLanguage classes is "
            "currently being maintained for backward compatibility, but the "
            "method will be deprecated in the future, as its behavior is not "
            "specified in (and currently does not conform to) RFC 7231.",
            DeprecationWarning,
        )
        return 1.0


class AcceptLanguageNoHeader(_AcceptLanguageInvalidOrNoHeader):
    """
    Represent when there is no ``Accept-Language`` header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptLanguageNoHeader.__add__`).
    """

    def __init__(self):
        """
        Create an :class:`AcceptLanguageNoHeader` instance.
        """
        self._header_value = None
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__()

    @property
    def header_value(self):
        """
        (``str`` or ``None``) The header value.

        As there is no header in the request, this is ``None``.
        """
        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As there is no header in the request, this is ``None``.
        """
        return self._parsed

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str``
        * a ``dict``, with language ranges as keys and qvalues as values
        * a ``tuple`` or ``list``, of language range ``str``'s or of ``tuple``
          or ``list`` (language range, qvalue) pairs (``str``'s and pairs can be
          mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptLanguageValidHeader`,
          :class:`AcceptLanguageNoHeader`, or
          :class:`AcceptLanguageInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an
        :class:`AcceptLanguageValidHeader` instance, a new
        :class:`AcceptLanguageValidHeader` instance with the valid header value
        is returned.

        If `other` is ``None``, an :class:`AcceptLanguageNoHeader` instance, an
        invalid header value, or an :class:`AcceptLanguageInvalidHeader`
        instance, a new :class:`AcceptLanguageNoHeader` instance is returned.
        """
        if isinstance(other, AcceptLanguageValidHeader):
            return AcceptLanguageValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptLanguageNoHeader, AcceptLanguageInvalidHeader)):
            return self.__class__()

        return self._add_instance_and_non_accept_language_type(
            instance=self, other=other
        )

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptLanguageNoHeader.__add__`.
        """
        return self.__add__(other=other)

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    def __str__(self):
        """Return the ``str`` ``'<no header in request>'``."""

        return "<no header in request>"

    def _add_instance_and_non_accept_language_type(self, instance, other):
        if not other:
            return self.__class__()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptLanguageValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return self.__class__()


class AcceptLanguageInvalidHeader(_AcceptLanguageInvalidOrNoHeader):
    """
    Represent an invalid ``Accept-Language`` header.

    An invalid header is one that does not conform to
    :rfc:`7231#section-5.3.5`. As specified in the RFC, an empty header is an
    invalid ``Accept-Language`` header.

    :rfc:`7231` does not provide any guidance on what should happen if the
    ``Accept-Language`` header has an invalid value. This implementation
    disregards the header, and treats it as if there is no ``Accept-Language``
    header in the request.

    This object should not be modified. To add to the header, we can use the
    addition operators (``+`` and ``+=``), which return a new object (see the
    docstring for :meth:`AcceptLanguageInvalidHeader.__add__`).
    """

    def __init__(self, header_value):
        """
        Create an :class:`AcceptLanguageInvalidHeader` instance.
        """
        self._header_value = header_value
        self._parsed = None
        self._parsed_nonzero = None

    def copy(self):
        """
        Create a copy of the header object.

        """
        return self.__class__(self._header_value)

    @property
    def header_value(self):
        """(``str`` or ``None``) The header value."""

        return self._header_value

    @property
    def parsed(self):
        """
        (``list`` or ``None``) Parsed form of the header.

        As the header is invalid and cannot be parsed, this is ``None``.
        """

        return self._parsed

    def __add__(self, other):
        """
        Add to header, creating a new header object.

        `other` can be:

        * ``None``
        * a ``str``
        * a ``dict``, with language ranges as keys and qvalues as values
        * a ``tuple`` or ``list``, of language range ``str``'s or of ``tuple``
          or ``list`` (language range, qvalue) pairs (``str``'s and pairs can
          be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptLanguageValidHeader`,
          :class:`AcceptLanguageNoHeader`, or
          :class:`AcceptLanguageInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``

        If `other` is a valid header value or an
        :class:`AcceptLanguageValidHeader` instance, a new
        :class:`AcceptLanguageValidHeader` instance with the valid header value
        is returned.

        If `other` is ``None``, an :class:`AcceptLanguageNoHeader` instance, an
        invalid header value, or an :class:`AcceptLanguageInvalidHeader`
        instance, a new :class:`AcceptLanguageNoHeader` instance is returned.
        """

        if isinstance(other, AcceptLanguageValidHeader):
            return AcceptLanguageValidHeader(header_value=other.header_value)

        if isinstance(other, (AcceptLanguageNoHeader, AcceptLanguageInvalidHeader)):
            return AcceptLanguageNoHeader()

        return self._add_instance_and_non_accept_language_type(
            instance=self, other=other
        )

    def __radd__(self, other):
        """
        Add to header, creating a new header object.

        See the docstring for :meth:`AcceptLanguageValidHeader.__add__`.
        """

        return self._add_instance_and_non_accept_language_type(
            instance=self, other=other, instance_on_the_right=True
        )

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)
        # We do not display the header_value, as it is untrusted input. The
        # header_value could always be easily obtained from the .header_value
        # property.

    def __str__(self):
        """Return the ``str`` ``'<invalid header value>'``."""

        return "<invalid header value>"

    def _add_instance_and_non_accept_language_type(
        self, instance, other, instance_on_the_right=False
    ):
        if not other:
            return AcceptLanguageNoHeader()

        other_header_value = self._python_value_to_header_str(value=other)

        try:
            return AcceptLanguageValidHeader(header_value=other_header_value)
        except ValueError:  # invalid header value
            return AcceptLanguageNoHeader()


def create_accept_language_header(header_value):
    """
    Create an object representing the ``Accept-Language`` header in a request.

    :param header_value: (``str``) header value
    :return: If `header_value` is ``None``, an :class:`AcceptLanguageNoHeader`
             instance.

             | If `header_value` is a valid ``Accept-Language`` header, an
               :class:`AcceptLanguageValidHeader` instance.

             | If `header_value` is an invalid ``Accept-Language`` header, an
               :class:`AcceptLanguageInvalidHeader` instance.
    """

    if header_value is None:
        return AcceptLanguageNoHeader()
    if isinstance(header_value, AcceptLanguage):
        return header_value.copy()
    try:
        return AcceptLanguageValidHeader(header_value=header_value)
    except ValueError:
        return AcceptLanguageInvalidHeader(header_value=header_value)


def accept_language_property():
    doc = """
        Property representing the ``Accept-Language`` header.

        (:rfc:`RFC 7231, section 5.3.5 <7231#section-5.3.5>`)

        The header value in the request environ is parsed and a new object
        representing the header is created every time we *get* the value of the
        property. (*set* and *del* change the header value in the request
        environ, and do not involve parsing.)
    """

    ENVIRON_KEY = "HTTP_ACCEPT_LANGUAGE"

    def fget(request):
        """Get an object representing the header in the request."""

        return create_accept_language_header(
            header_value=request.environ.get(ENVIRON_KEY)
        )

    def fset(request, value):
        """
        Set the corresponding key in the request environ.

        `value` can be:

        * ``None``
        * a ``str``
        * a ``dict``, with language ranges as keys and qvalues as values
        * a ``tuple`` or ``list``, of language range ``str``'s or of ``tuple``
          or ``list`` (language range, qvalue) pairs (``str``'s and pairs can
          be mixed within the ``tuple`` or ``list``)
        * an :class:`AcceptLanguageValidHeader`,
          :class:`AcceptLanguageNoHeader`, or
          :class:`AcceptLanguageInvalidHeader` instance
        * object of any other type that returns a value for ``__str__``
        """

        if value is None or isinstance(value, AcceptLanguageNoHeader):
            fdel(request=request)
        else:
            if isinstance(
                value, (AcceptLanguageValidHeader, AcceptLanguageInvalidHeader)
            ):
                header_value = value.header_value
            else:
                header_value = AcceptLanguage._python_value_to_header_str(value=value)
            request.environ[ENVIRON_KEY] = header_value

    def fdel(request):
        """Delete the corresponding key from the request environ."""
        try:
            del request.environ[ENVIRON_KEY]
        except KeyError:
            pass

    return property(fget, fset, fdel, textwrap.dedent(doc))