Skip to content

CardList

Bases: UserList

Represents a collection of cards.

Note

This is ultimately a superclass of list, and thus supports all common list methods.

Attributes:

Name Type Description
data list[Card]

The raw list of Card objects contained within the object.

Source code in fab/card.py
 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
class CardList(UserList):
    '''
    Represents a collection of cards.

    Note:
      This is ultimately a superclass of `list`, and thus supports all common
      `list` methods.

    Attributes:
      data: The raw `list` of `Card` objects contained within the object.
    '''
    data: list[Card]

    def actions(self) -> CardList:
        '''
        Returns the set of all action cards in this card list.

        Returns:
          The set of all action cards in the card list.
        '''
        return CardList([card for card in self.data if card.is_action()])

    def attacks(self) -> CardList:
        '''
        Returns the set of all attack cards in this card list.

        Returns:
          The set of all attack cards in the card list.
        '''
        return CardList([card for card in self.data if card.is_attack()])

    def attack_reactions(self) -> CardList:
        '''
        Returns the set of all attack reaction cards in this card list.

        Returns:
          The set of all attack reaction cards in the card list.
        '''
        return CardList([card for card in self.data if card.is_attack_reaction()])

    def auras(self) -> CardList:
        '''
        Returns the set of all aura cards in this card list.

        Returns:
          The set of all aura cards in the card list.
        '''
        return CardList([card for card in self.data if card.is_aura()])

    def costs(self) -> list[int]:
        '''
        Returns the set of all card costs associated with this list of cards.

        Tip: Warning
          This excludes cards with no cost or with variable cost.

        Returns:
          The set of all card costs in the card list.
        '''
        res = []
        for card in self.data:
            if isinstance(card.cost, int): res.append(card.cost)
        return sorted(list(set(res)))

    def counts(self) -> dict[str, int]:
        '''
        Computes a `dict` of card counts, where keys correspond to the
        `full_name` of `Card` objects.

        Returns:
          A `dict` of card counts by full name.
        '''
        counts = {}
        for card in self.data:
            if card.full_name in counts:
                counts[card.full_name] += 1
            else:
                counts[card.full_name] = 1
        return counts

    def defense_reactions(self) -> CardList:
        '''
        Returns the set of all defense reaction cards in this card list.

        Returns:
          The set of all defense reaction cards in the card list.
        '''
        return CardList([card for card in self.data if card.is_defense_reaction()])

    def defense_values(self) -> list[int]:
        '''
        Returns the set of all card defense values associated with this list of
        cards.

        Tip: Warning
          This excludes cards with no defense or with variable defense.

        Returns:
          A unique `list` of card defense values associated with the list of cards.
        '''
        res = []
        for card in self.data:
            if isinstance(card.defense, int): res.append(card.defense)
        return sorted(list(set(res)))

    def draw(self, num: int, order: int = -1, remove: bool = False) -> CardList:
        '''
        Draws the specified number of cards from the list, optionally removing
        the cards drawn.

        Note:
          If `order` is set to `-1`, then cards will be drawn from the _end_ of
          the list, as if calling `list.pop()`. When `order` is `1`, cards are
          drawn from the beginning of the list. If `order` is `0`, then cards
          are drawn from random positions. Even when `remove` is `False`, when
          drawing with `order=0`, this method will ensure that the same card
          will not be drawn more times than it actually exists in the list.

        Args:
          num: The number of cards to draw from the list.
          order: Specifies the method/order in which cards are drawn from the list (see note).
          remove: Whether to remove the cards drawn from the list.

        Returns:
          The list of cards drawn.
        '''
        if num <= 0:
            raise Exception('specified number of cards must be a positive integer')
        res = []
        if order == -1:
            if remove:
                for _ in range(0, num):
                    res.append(self.pop())
            else:
                res = self.data[-num:]
        elif order == 0:
            if remove:
                for _ in range(0, num):
                    res.append(self.pop(random.randrange(len(self.data))))
            else:
                potential = [c for c in self.data]
                for _ in range(0, num):
                    res.append(potential.pop(random.randrange(len(potential))))
        elif order == 1:
            if remove:
                for _ in range(0, num):
                    res.append(self.pop(0))
            else:
                res = self.data[num:]
        else:
            raise Exception('specified "order" must be -1, 0, or 1')
        return CardList(res)

    @staticmethod
    def empty() -> CardList:
        '''
        Returns a new empty card list containing no cards.

        Returns:
          An empty card list.
        '''
        return CardList([])

    def equipment(self) -> CardList:
        '''
        Returns the set of all equipment cards in this card list.

        Returns:
          The set of all equipment cards in the card list.
        '''
        return CardList([card for card in self.data if card.is_equipment()])

    def filter(
            self,
            body: Optional[Any] = None,
            cost: Optional[Any] = None,
            defense: Optional[Any] = None,
            full_name: Optional[Any] = None,
            grants: Optional[Any] = None,
            health: Optional[Any] = None,
            intelligence: Optional[Any] = None,
            keywords: Optional[Any] = None,
            legality: Optional[Any] = None,
            name: Optional[Any] = None,
            negate: bool = False,
            pitch: Optional[Any] = None,
            power: Optional[Any] = None,
            rarities: Optional[Any] = None,
            sets: Optional[Any] = None,
            tags: Optional[Any] = None,
            type_text: Optional[Any] = None,
            types: Optional[Any] = None
    ) -> CardList:
        '''
        Filters a list of cards according to a function against a particular
        `Card` field.

        In addition to functions/lambdas, you can also specify:

        * A `str` for the `body`, `full_name`, `name`, or `type_text` keyword
          arguments. These comparisons are case-insensitive and will match
          substrings.
        * An `int` for the `cost`, `defense`, `health`, `intelligence`,
          `pitch`, or `power` keyword arguments. `None` and `str` values
          will not be included in the results.
        * A `tuple[int, int]` for the `cost`, `defense`, `health`,
          `intelligence`, `pitch`, or `power` keyword arguments. This defines
          a range of values to include (inclusive).
        * A `list[str]` for the `grants`, `keywords`, `rarities`, `sets`,
          `tags`, and `types` keyword arguments. At least one value of the
          list must be present for an item to be included.
        * A `str` for the `grants`, `keywords`, `rarities`, `sets`, `tags`,
          and `types` keyword arguments. This is the same as passing in a
          single-element list.
        * A `str` for the `legality` keyword argument, corresponding to a format
          code that the card must be legal in to be included.
        * The strings `r`, `red`, `y`, `yellow`, `b`, or `blue` for the `pitch`
          keyword argument, corresponding to the color of the card
          (case-insensitive).

        Args:
          body: A `str` or function to filter by `body`.
          cost: An `int`, `tuple[int, int]`, or function to filter by `cost`.
          defense: An `int`, `tuple[int, int]`, or function to filter by `defense`.
          full_name: A `str` or function to filter by `full_name`.
          grants: A `str`, `list[str]`, or function to filter by `grants`.
          health: An `int`, `tuple[int, int]`, or function to filter by `health`.
          intelligence: An `int`, `tuple[int, int]`, or function to filter by `intelligence`.
          keywords: A `str`, `list[str]`, or function to filter by `keywords`.
          legality: A `str` or function to filter by `legality`.
          name: A `str` or function to filter by `name`.
          negate: Whether to invert the filter specification.
          pitch: An `int`, `str`, `tuple[int, int]`, or function to filter by `pitch`.
          power: An `int`, `tuple[int, int]`, or function to filter by `power`.
          rarities: A `str`, `list[str]` or function to filter by `rarities`.
          sets: A `str`, `list[str]`, or function to filter by `sets`.
          tags: A `str`, `list[str]`, or function to filter by `tags`.
          type_text: A `str` or function to filter by `type_text`.
          types: A `str`, `list[str]`, or function to filter by `types`.

        Returns:
          A new `CardList` containing copies of `Card` objects that meet the filtering requirements.
        '''
        if len(self.data) < 2: return copy.deepcopy(self)
        filtered = []
        for c in self:
            if not body is None:
                if isinstance(body, str):
                    if negate:
                        if body.lower() in str(c.body).lower(): continue
                    else:
                        if not body.lower() in str(c.body).lower(): continue
                else:
                    if negate:
                        if body(c.body): continue
                    else:
                        if not body(c.body): continue
            if not cost is None:
                if isinstance(cost, int):
                    if negate:
                        if isinstance(c.cost, int) and cost == c.cost: continue
                    else:
                        if not isinstance(c.cost, int) or cost != c.cost: continue
                elif isinstance(cost, tuple):
                    if negate:
                        if isinstance(c.cost, int) and c.cost >= cost[0] and c.cost <= cost[1]: continue
                    else:
                        if not isinstance(c.cost, int) or c.cost < cost[0] or c.cost > cost[1]: continue
                else:
                    if negate:
                        if cost(c.cost): continue
                    else:
                        if not cost(c.cost): continue
            if not defense is None:
                if isinstance(defense, int):
                    if negate:
                        if isinstance(c.defense, int) and defense == c.defense: continue
                    else:
                        if not isinstance(c.defense, int) or defense != c.defense: continue
                elif isinstance(defense, tuple):
                    if negate:
                        if isinstance(c.defense, int) and c.defense >= defense[0] and c.defense <= defense[1]: continue
                    else:
                        if not isinstance(c.defense, int) or c.defense < defense[0] or c.defense > defense[1]: continue
                else:
                    if negate:
                        if defense(c.defense): continue
                    else:
                        if not defense(c.defense): continue
            if not full_name is None:
                if isinstance(full_name, str):
                    if negate:
                        if full_name.lower() in c.full_name.lower(): continue
                    else:
                        if not full_name.lower() in c.full_name.lower(): continue
                else:
                    if negate:
                        if full_name(c.full_name): continue
                    else:
                        if not full_name(c.full_name): continue
            if not grants is None:
                if isinstance(grants, str):
                    if negate:
                        if grants in c.grants: continue
                    else:
                        if not grants in c.grants: continue
                elif isinstance(grants, list):
                    if negate:
                        if True in [(x in c.grants) for x in grants]: continue
                    else:
                        if not (True in [(x in c.grants) for x in grants]): continue
                else:
                    if negate:
                        if grants(c.grants): continue
                    else:
                        if not grants(c.grants): continue
            if not health is None:
                if isinstance(health, int):
                    if negate:
                        if isinstance(c.health, int) and health == c.health: continue
                    else:
                        if not isinstance(c.health, int) or health != c.health: continue
                elif isinstance(health, tuple):
                    if negate:
                        if isinstance(c.health, int) and c.health >= health[0] and c.health <= health[1]: continue
                    else:
                        if not isinstance(c.health, int) or c.health < health[0] or c.health > health[1]: continue
                else:
                    if negate:
                        if health(c.health): continue
                    else:
                        if not health(c.health): continue
            if not intelligence is None:
                if isinstance(intelligence, int):
                    if negate:
                        if isinstance(c.intelligence, int) and intelligence == c.intelligence: continue
                    else:
                        if not isinstance(c.intelligence, int) or intelligence != c.intelligence: continue
                elif isinstance(intelligence, tuple):
                    if negate:
                        if isinstance(c.intelligence, int) and c.intelligence >= intelligence[0] and c.intelligence <= intelligence[1]: continue
                    else:
                        if not isinstance(c.intelligence, int) or c.intelligence < intelligence[0] or c.intelligence > intelligence[1]: continue
                else:
                    if negate:
                        if intelligence(c.intelligence): continue
                    else:
                        if not intelligence(c.intelligence): continue
            if not keywords is None:
                if isinstance(keywords, str):
                    if negate:
                        if keywords in c.keywords: continue
                    else:
                        if not keywords in c.keywords: continue
                elif isinstance(keywords, list):
                    if negate:
                        if True in [(x in c.keywords) for x in keywords]: continue
                    else:
                        if not (True in [(x in c.keywords) for x in keywords]): continue
                else:
                    if negate:
                        if keywords(c.keywords): continue
                    else:
                        if not keywords(c.keywords): continue
            if not legality is None:
                if isinstance(legality, str):
                    if negate:
                        if c.legality[legality]: continue
                    else:
                        if not c.legality[legality]: continue
                else:
                    if negate:
                        if legality(c.legality): continue
                    else:
                        if not legality(c.legality): continue
            if not name is None:
                if isinstance(name, str):
                    if negate:
                        if name.lower() in c.name.lower(): continue
                    else:
                        if not name.lower() in c.name.lower(): continue
                else:
                    if negate:
                        if name(c.name): continue
                    else:
                        if not name(c.name): continue
            if not pitch is None:
                if isinstance(pitch, int):
                    if negate:
                        if isinstance(c.pitch, int) and pitch == c.pitch: continue
                    else:
                        if not isinstance(c.pitch, int) or pitch != c.pitch: continue
                elif isinstance(pitch, str):
                    pl = pitch.lower()
                    if not pl in ['r', 'red', 'y', 'yellow', 'b', 'blue']:
                        raise Exception(f'unknown pitch filter string "{pitch}"')
                    if negate:
                        if pl.startswith('b') and c.is_blue(): continue
                        elif pl.startswith('r') and c.is_red(): continue
                        elif pl.startswith('y') and c.is_yellow(): continue
                    else:
                        if pl.startswith('b') and not c.is_blue(): continue
                        elif pl.startswith('r') and not c.is_red(): continue
                        elif pl.startswith('y') and not c.is_yellow(): continue
                elif isinstance(pitch, tuple):
                    if negate:
                        if isinstance(c.pitch, int) and c.pitch >= pitch[0] and c.pitch <= pitch[1]: continue
                    else:
                        if not isinstance(c.pitch, int) or c.pitch < pitch[0] or c.pitch > pitch[1]: continue
                else:
                    if negate:
                        if pitch(c.pitch): continue
                    else:
                        if not pitch(c.pitch): continue
            if not power is None:
                if isinstance(power, int):
                    if negate:
                        if isinstance(c.power, int) and power == c.power: continue
                    else:
                        if not isinstance(c.power, int) or power != c.power: continue
                elif isinstance(power, tuple):
                    if negate:
                        if isinstance(c.power, int) and c.power >= power[0] and c.power <= power[1]: continue
                    else:
                        if not isinstance(c.power, int) or c.power < power[0] or c.power > power[1]: continue
                else:
                    if negate:
                        if power(c.power): continue
                    else:
                        if not power(c.power): continue
            if not rarities is None:
                if isinstance(rarities, str):
                    if negate:
                        if rarities in c.rarities: continue
                    else:
                        if not rarities in c.rarities: continue
                elif isinstance(rarities, list):
                    if negate:
                        if True in [(x in c.rarities) for x in rarities]: continue
                    else:
                        if not (True in [(x in c.rarities) for x in rarities]): continue
                else:
                    if negate:
                        if rarities(c.rarities): continue
                    else:
                        if not rarities(c.rarities): continue
            if not sets is None:
                if isinstance(sets, str):
                    if negate:
                        if sets in c.sets: continue
                    else:
                        if not sets in c.sets: continue
                elif isinstance(sets, list):
                    if negate:
                        if True in [(x in c.sets) for x in sets]: continue
                    else:
                        if not (True in [(x in c.sets) for x in sets]): continue
                else:
                    if negate:
                        if sets(c.sets): continue
                    else:
                        if not sets(c.sets): continue
            if not tags is None:
                if isinstance(tags, str):
                    if negate:
                        if tags in c.tags: continue
                    else:
                        if not tags in c.tags: continue
                elif isinstance(tags, list):
                    if negate:
                        if True in [(x in c.tags) for x in tags]: continue
                    else:
                        if not (True in [(x in c.tags) for x in tags]): continue
                else:
                    if negate:
                        if tags(c.tags): continue
                    else:
                        if not tags(c.tags): continue
            if not type_text is None:
                if isinstance(type_text, str):
                    if negate:
                        if type_text.lower() in c.type_text.lower(): continue
                    else:
                        if not type_text.lower() in c.type_text.lower(): continue
                else:
                    if negate:
                        if type_text(c.type_text): continue
                    else:
                        if not type_text(c.type_text): continue
            if not types is None:
                if isinstance(types, str):
                    if negate:
                        if types in c.types: continue
                    else:
                        if not types in c.types: continue
                elif isinstance(types, list):
                    if negate:
                        if True in [(x in c.types) for x in types]: continue
                    else:
                        if not (True in [(x in c.types) for x in types]): continue
                else:
                    if negate:
                        if types(c.types): continue
                    else:
                        if not types(c.types): continue
            filtered.append(copy.deepcopy(c))
        return CardList(filtered)

    @staticmethod
    def from_csv(csvstr: str, delimiter: str = '\t') -> CardList:
        '''
        Creates a new list of cards given a CSV string representation.

        Args:
          csvstr: The CSV string representation to parse.
          delimiter: An alternative primary delimiter to pass to `csv.DictReader`.

        Returns:
          A new `CardList` object from the parsed data.
        '''
        try:
            csv_data = csv.DictReader(io.StringIO(csvstr), delimiter = delimiter)
        except Exception as e:
            raise Exception(f'unable to parse CSV content - {e}')
        def int_str_or_none(inputstr: str) -> int | str | None:
            '''
            A helper function for building out stuff like `cost`, etc.
            '''
            if not inputstr:
                return None
            elif inputstr.isdigit():
                return int(inputstr)
            else:
                return inputstr
        def image_url_parser(inputstr: str) -> list[str]:
            '''
            A helper function for parsing our the image URL list.
            '''
            if not inputstr: return []
            result = []
            if ',' in inputstr:
                for substrings in [x.split(' - ', 1) for x in unidecode(inputstr).split(',') if ' - ' in x]:
                    url = substrings[0].strip()
                    result.append(url)
            elif ' - ' in inputstr:
                url = unidecode(inputstr).split(' - ', 1)[0].strip()
                result.append(url)
            return result
        def legality_parser(csv_entry: dict[str, Any]) -> dict[str, bool]:
            '''
            A helper function for parsing card legality.
            '''
            res = {}
            blitz_legal = not csv_entry['Blitz Legal'].lower() in ['no', 'false']
            blitz_ll = True if csv_entry['Blitz Living Legend'] else False
            blitz_banned = True if csv_entry['Blitz Banned'] else False
            cc_legal = not csv_entry['CC Legal'].lower() in ['no', 'false']
            cc_ll = True if csv_entry['CC Living Legend'] else False
            cc_banned = True if csv_entry['CC Banned'] else False
            commoner_legal = not csv_entry['Commoner Legal'].lower() in ['no', 'false']
            commoner_banned = True if csv_entry['Commoner Banned'] else False
            res['B'] = blitz_legal and not blitz_ll and not blitz_banned
            res['CC'] = cc_legal and not cc_ll and not cc_banned
            res['C'] = commoner_legal and not commoner_banned
            res['UPF'] = res['CC']
            return res
        cards = []
        for entry in csv_data:
            try:
              cards.append(Card(
                  body         = unidecode(entry['Functional Text'].strip()) if entry['Functional Text'] else None,
                  cost         = int_str_or_none(entry['Cost']),
                  defense      = int_str_or_none(entry['Defense']),
                  flavor_text  = unidecode(entry['Flavor Text'].strip()) if entry['Flavor Text'] else None,
                  full_name    = unidecode(entry['Name'].strip()) + (f" ({entry['Pitch']})" if entry['Pitch'].isdigit() else ''),
                  grants       = [x.strip() for x in entry['Granted Keywords'].split(',')] if entry['Granted Keywords'] else [],
                  health       = int(entry['Health']) if entry['Health'].isdigit() else None,
                  identifiers  = [x.strip() for x in entry['Identifiers'].split(',')],
                  intelligence = int(entry['Intelligence']) if entry['Intelligence'].isdigit() else None,
                  image_urls   = image_url_parser(entry['Image URLs']),
                  keywords     = list(set(([x.strip() for x in entry['Card Keywords'].split(',')] if entry['Card Keywords'] else []) + ([x.strip() for x in entry['Ability and Effect Keywords'].split(',')] if entry['Ability and Effect Keywords'] else []))),
                  legality     = legality_parser(entry),
                  name         = unidecode(entry['Name'].strip()),
                  pitch        = int(entry['Pitch']) if entry['Pitch'].isdigit() else None,
                  power        = int_str_or_none(entry['Power']),
                  rarities     = [x.strip() for x in entry['Rarity'].split(',')],
                  sets         = [x.strip() for x in entry['Set Identifiers'].split(',')],
                  tags         = [],
                  type_text    = unidecode(entry['Type Text'].strip()),
                  types        = [x.strip() for x in entry['Types'].split(',')]
               ))
            except Exception as e:
                raise Exception(f'unable to parse intermediate card data - {e} - {entry}')
        return CardList(cards)

    @staticmethod
    def from_json(jsonstr: str) -> CardList:
        '''
        Creates a new list of cards given a JSON string representation.

        Args:
          jsonstr: The JSON string representation to parse into a card list.

        Returns:
          A new `CardList` object from the parsed data.
        '''
        cards = []
        for jcard in json.loads(jsonstr):
            cards.append(Card(**jcard))
        return CardList(cards)

    def full_names(self) -> list[str]:
        '''
        Returns the set of all full card names within this list of cards.

        Returns:
          A unique `list` of all full card names within the list of cards.
        '''
        return sorted(list(set([card.full_name for card in self.data])))

    def grants(self) -> list[str]:
        '''
        Returns the set of all card grant keywords within this list of cards.

        Returns:
          A unique `list` of all card grant keywords within the list of cards.
        '''
        res = []
        for card in self.data:
            res.extend(card.grants)
        return sorted(list(set(res)))

    def group(self, by: str = 'type_text') -> dict[int | str, CardList]:
        '''
        Groups cards by the specified (singular form) of the `Card` field.

        Note:
          The keys of the resulting `dict` take on the `type` described below:

          * `str`: `full_name`, `grants`, `keyword`, `name`, `rarity`, `set`, `type`, `type_text`
          * `int`: `cost`, `defense`, `health`, `intelligence`, `pitch`, `power`

          Certain values of `by` accept their plural forms, such as `rarity` or
          `rarities`.

        Tip: Warning
          When grouping by `cost`, `defense`, `health`, `intelligence`, `pitch`,
          or `power`, cards with `str` or `None` values for the corresponding
          field will be excluded from the result.

        Args:
          by: The `Card` field to group by.

        Returns:
          A `dict` of `CardList` objects grouped by the specified `Card` field.
        '''
        if len(self.data) < 1: return {}
        res = {}
        # str keys
        if by == 'full_name':
            for full_name in self.full_names():
                res[full_name] = CardList([card for card in self if card.full_name == full_name]).sort()
        elif by == 'grants':
            for grants in self.grants():
                res[grants] = CardList([card for card in self if grants in card.grants]).sort()
        elif by in ['keyword', 'keywords']:
            for keyword in self.keywords():
                res[keyword] = CardList([card for card in self if keyword in card.keywords]).sort()
        elif by == 'name':
            for name in self.names():
                res[name] = CardList([card for card in self if card.name == name]).sort()
        elif by in ['rarity', 'rarities']:
            for rarity in self.rarities():
                res[rarity] = CardList([card for card in self if rarity in card.rarities]).sort()
        elif by in ['set', 'sets']:
            for card_set in self.sets():
                res[card_set] = CardList([card for card in self if card_set in card.sets]).sort()
        elif by in ['type', 'types']:
            for type_val in self.types():
                res[type_val] = CardList([card for card in self if type_val in card.types]).sort()
        elif by == 'type_text':
            for type_text in self.type_texts():
                res[type_text] = CardList([card for card in self if card.type_text == type_text]).sort()
        # int keys
        elif by == 'cost':
            for cost in self.costs():
                res[cost] = CardList([card for card in self if isinstance(card.cost, int) and card.cost == cost]).sort()
        elif by == 'defense':
            for defense in self.defense_values():
                res[defense] = CardList([card for card in self if isinstance(card.defense, int) and card.defense == defense]).sort()
        elif by == 'health':
            for health in self.health_values():
                res[health] = CardList([card for card in self if isinstance(card.health, int) and card.health == health]).sort()
        elif by == 'intelligence':
            for intelligence in self.intelligence_values():
                res[intelligence] = CardList([card for card in self if isinstance(card.intelligence, int) and card.intelligence == intelligence]).sort()
        elif by == 'pitch':
            for pitch in self.pitch_values():
                res[pitch] = CardList([card for card in self if isinstance(card.pitch, int) and card.pitch == pitch]).sort()
        elif by == 'power':
            for power in self.power_values():
                res[power] = CardList([card for card in self if isinstance(card.power, int) and card.power == power]).sort()
        return res

    def health_values(self) -> list[int]:
        '''
        Returns the set of all card health values associated with this list of
        cards.

        Tip: Warning
          This excludes cards with no health or with variable health.

        Returns:
          The unique `list` of all card health values within the card list.
        '''
        res = []
        for card in self.data:
            if isinstance(card.health, int): res.append(card.health)
        return sorted(list(set(res)))

    @staticmethod
    def _hero_filter_related(hero: Card, cards: CardList, catalog: Optional[CardList] = None, include_generic: bool = True) -> CardList:
        '''
        A helper function for filtering cards based on a hero. Do not call this
        function directly, instead use `Deck.filter_related`.

        Note:
          This function needs a card catalog to work properly and will fall back
          to `card.CARD_CATALOG`.

        Args:
          hero: The hero card to filter with.
          cards: The collection of cards to filter.
          catalog: A catalog of cards representing all cards in the game.
          include_generic: Whether to include _Generic_ cards in the result.

        Returns:
          The list of cards that work with the specified hero.
        '''
        _catalog = CARD_CATALOG if catalog is None else catalog
        if _catalog is None:
            raise Exception('specified card catalog (or default card catalog) has not been initialized')
        if 'Shapeshifter' in hero.types: return cards
        other_hero_types = _catalog.filter(types='Hero').filter(full_name=hero.name, negate=True).types()
        relevant = [t for t in other_hero_types if not t in hero.types]
        filtered = cards.filter(
            types = [t for t in hero.types if not t in ['Hero', 'Young']] + (['Generic'] if include_generic else [])
        ).filter(
            types = lambda card_types: not any(t in relevant for t in card_types)
        )
        final = []
        for card in filtered.data:
            if any('Specialization' in k for k in card.keywords):
                spec = next(k for k in card.keywords if 'Specialization' in k).replace('Specialization', '').strip()
                if spec.lower() in hero.full_name.lower():
                    final.append(card)
            else:
                final.append(card)
        return CardList(copy.deepcopy(final))

    def heroes(self) -> CardList:
        '''
        Returns the set of all hero cards in this card list.

        Returns:
          The set of all hero cards within the card list.
        '''
        return CardList([card for card in self.data if card.is_hero()])

    def identifiers(self) -> list[str]:
        '''
        Returns the set of all card identifiers in this card list.

        Returns:
          The unique `list` of all card identifiers within the card list.
        '''
        res = []
        for card in self.data:
            res.extend(card.identifiers)
        return sorted(list(set(res)))

    def instants(self) -> CardList:
        '''
        Returns the set of all instant cards in this card list.

        Returns:
          The set of all instant cards within the card list.
        '''
        return CardList([card for card in self.data if card.is_instant()])

    def intelligence_values(self) -> list[int]:
        '''
        Returns the set of all card intelligence values associated with this
        list of cards.

        Tip: Warning
          This excludes cards with no intelligence or with variable
          intelligence.

        Returns:
          A unique `list` of all card intelligence values within the list of cards.
        '''
        res = []
        for card in self.data:
            if isinstance(card.intelligence, int): res.append(card.intelligence)
        return sorted(list(set(res)))

    def item_cards(self) -> CardList:
        '''
        Returns the set of all item cards in this card list.

        Returns:
          The set of all item cards within the list of cards.
        '''
        return CardList([card for card in self.data if card.is_item()])

    def keywords(self) -> list[str]:
        '''
        Returns the set of all keywords in this card list.

        Returns:
          A unique `list` of all keywords within the list of cards.
        '''
        res = []
        for card in self.data:
            res.extend(card.keywords)
        return sorted(list(set(res)))

    def legality(self) -> dict[str, bool]:
        '''
        Computes the legality of this list of cards for each game format.

        Note:
          A `CardList` is not considered legal for a format if it contains _any_
          cards not legal for that format.

        Returns:
          A `dict` of game format `str` keys and their `bool` legal status.
        '''
        res = {}
        for f in GAME_FORMATS.keys():
            res[f] = not (False in [card.is_legal(f) for card in self.data])
        return res

    @staticmethod
    def load(file_path: str, set_catalog: bool = False) -> CardList:
        '''
        Loads a list of cards from the specified `.json` or `.csv` file.

        Note:
          If `set_catalog` is set to `True`, then a copy of the loaded card list
          will also be set as the default `card.CARD_CATALOG`.

        Args:
          file_path: The file path to load from.
          set_catalog: Whether to also set the loaded data as the default card catalog.

        Returns:
          A new `CardList` object.
        '''
        with open(os.path.expanduser(file_path), 'r') as f:
            if file_path.endswith('.json'):
                res = CardList.from_json(f.read())
            elif file_path.endswith('.csv'):
                res = CardList.from_csv(f.read())
            else:
                raise Exception('specified file is not a CSV or JSON file')
        if set_catalog:
            global CARD_CATALOG
            CARD_CATALOG = copy.deepcopy(res)
        return res

    def max_cost(self) -> int:
        '''
        Computes the maximum card cost within this card list.

        Tip: Warning
          Cards with variable or no cost are ignored.

        Returns:
          The maximum card cost within the list of cards.
        '''
        if len(self.data) < 1: return 0
        array = [x.cost for x in self.data if isinstance(x.cost, int)]
        if array:
            return max(array)
        else:
            return 0

    def max_defense(self) -> int:
        '''
        Computes the maximum card defense within this card list.

        Tip: Warning
          Cards with variable or no defense are ignored.

        Returns:
          The maximum card defense value within the list of cards.
        '''
        if len(self.data) < 1: return 0
        array = [x.defense for x in self.data if isinstance(x.defense, int)]
        if array:
            return max(array)
        else:
            return 0

    def max_health(self) -> int:
        '''
        Computes the maximum card health within this card list.

        Tip: Warning
          Cards with variable or no health are ignored.

        Returns:
          The maximum card health value within the list of cards.
        '''
        if len(self.data) < 1: return 0
        array = [x.health for x in self.data if isinstance(x.health, int)]
        if array:
            return max(array)
        else:
            return 0

    def max_intelligence(self) -> int:
        '''
        Computes the maximum card intelligence within this card list.

        Tip: Warning
          Cards with variable or no intelligence are ignored.

        Returns:
          The maximum card intelligence value within the list of cards.
        '''
        if len(self.data) < 1: return 0
        array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
        if array:
            return max(array)
        else:
            return 0

    def max_pitch(self) -> int:
        '''
        Computes the maximum card pitch within this card list.

        Tip: Warning
          Cards with variable or no pitch are ignored.

        Returns:
          The maximum card pitch value within this list of cards.
        '''
        if len(self.data) < 1: return 0
        array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
        if array:
            return max(array)
        else:
            return 0

    def max_power(self) -> int:
        '''
        Computes the maximum card power within this card list.

        Tip: Warning
          Cards with variable or no power are ignored.

        Returns:
          The maximum card power value within this list of cards.
        '''
        if len(self.data) < 1: return 0
        array = [x.power for x in self.data if isinstance(x.power, int)]
        if array:
            return max(array)
        else:
            return 0

    def mean_cost(self, precision: int = 2) -> float:
        '''
        Computes the mean card cost within this card list.

        Tip: Warning
          Cards with variable or no cost are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The mean card cost of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.cost for x in self.data if isinstance(x.cost, int)]
        if array:
            return round(mean(array), precision)
        else:
            return 0.0

    def mean_defense(self, precision: int = 2) -> float:
        '''
        Computes the mean card defense within this card list.

        Tip: Warning
          Cards with variable or no defense are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The mean defense of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.defense for x in self.data if isinstance(x.defense, int)]
        if array:
            return round(mean(array), precision)
        else:
            return 0.0

    def mean_health(self, precision: int = 2) -> float:
        '''
        Computes the mean card health within this card list.

        Tip: Warning
          Cards with variable or no health are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The mean health of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.health for x in self.data if isinstance(x.health, int)]
        if array:
            return round(mean(array), precision)
        else:
            return 0.0

    def mean_intelligence(self, precision: int = 2) -> float:
        '''
        Computes the mean card intelligence within this card list.

        Tip: Warning
          Cards with variable or no intelligence are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The mean intelligence of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
        if array:
            return round(mean(array), precision)
        else:
            return 0.0

    def mean_pitch(self, precision: int = 2) -> float:
        '''
        Computes the mean card pitch within this card list.

        Tip: Warning
          Cards with variable or no pitch are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The mean pitch value of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
        if array:
            return round(mean(array), precision)
        else:
            return 0.0

    def mean_power(self, precision: int = 2) -> float:
        '''
        Computes the mean card power within this card list.

        Tip: Warning
          Cards with variable or no power are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The mean power of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.power for x in self.data if isinstance(x.power, int)]
        if array:
            return round(mean(array), precision)
        else:
            return 0.0

    def median_cost(self, precision: int = 2) -> float:
        '''
        Computes the median card cost within this card list.

        Tip: Warning
          Cards with variable or no cost are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The median resource cost of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.cost for x in self.data if isinstance(x.cost, int)]
        if array:
            return round(median(array), precision)
        else:
            return 0.0

    def median_defense(self, precision: int = 2) -> float:
        '''
        Computes the median card defense within this card list.

        Tip: Warning
          Cards with variable or no defense are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The median defense value of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.defense for x in self.data if isinstance(x.defense, int)]
        if array:
            return round(median(array), precision)
        else:
            return 0.0

    def median_health(self, precision: int = 2) -> float:
        '''
        Computes the median card health within this card list.

        Tip: Warning
          Cards with variable or no health are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The median health of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.health for x in self if isinstance(x.health, int)]
        if array:
            return round(median(array), precision)
        else:
            return 0.0

    def median_intelligence(self, precision: int = 2) -> float:
        '''
        Computes the median card intelligence within this card list.

        Tip: Warning
          Cards with variable or no intelligence are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The median intelligence of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
        if array:
            return round(median(array), precision)
        else:
            return 0.0

    def median_pitch(self, precision: int = 2) -> float:
        '''
        Computes the median card pitch within this card list.

        Tip: Warning
          Cards with variable or no pitch are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The median pitch vlaue of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
        if array:
            return round(median(array), precision)
        else:
            return 0.0

    def median_power(self, precision: int = 2) -> float:
        '''
        Computes the median card power within this card list.

        Tip: Warning
          Cards with variable or no power are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The median attack power of cards in the list.
        '''
        if len(self.data) < 1: return 0.0
        array = [x.power for x in self.data if isinstance(x.power, int)]
        if array:
            return round(median(array), precision)
        else:
            return 0.0

    @staticmethod
    def merge(*args: CardList, unique: bool = False) -> CardList:
        '''
        Merges two or more card lists into a single one.

        Args:
          *args: The `CardList` objects to merge.
          unique: Whether duplicate `Card` objects should be deleted.

        Returns:
          The merged collection of cards.
        '''
        merged = []
        for card_list in args:
            if card_list is None: continue
            for card in card_list:
                if unique and not card in merged:
                    merged.append(card)
                elif not unique:
                    merged.append(card)
        return CardList(merged)

    def min_cost(self) -> int:
        '''
        Computes the minimum card cost within this card list.

        Tip: Warning
          Cards with variable or no cost are ignored.

        Returns:
          The minimum card cost within the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.cost for x in self.data if isinstance(x.cost, int)]
        if array:
            return min(array)
        else:
            return 0

    def min_defense(self) -> int:
        '''
        Computes the minimum card defense within this card list.

        Tip: Warning
          Cards with variable or no defense are ignored.

        Returns:
          The minimum card defense value within the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.defense for x in self.data if isinstance(x.defense, int)]
        if array:
            return min(array)
        else:
            return 0

    def min_health(self) -> int:
        '''
        Computes the minimum card health within this card list.

        Tip: Warning
          Cards with variable or no health are ignored.

        Returns:
          The minimum card health in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.health for x in self.data if isinstance(x.health, int)]
        if array:
            return min(array)
        else:
            return 0

    def min_intelligence(self) -> int:
        '''
        Computes the minimum card intelligence within this card list.

        Tip: Warning
          Cards with variable or no intelligence are ignored.

        Returns:
          The minimum intelligence in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
        if array:
            return min(array)
        else:
            return 0

    def min_pitch(self) -> int:
        '''
        Computes the minimum card pitch within this card list.

        Tip: Warning
          Cards with variable or no pitch are ignored.

        Returns:
          The minimum pitch value in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
        if array:
            return min(array)
        else:
            return 0

    def min_power(self) -> int:
        '''
        Computes the minimum card power within this card list.

        Tip: Warning
          Cards with variable or no power are ignored.

        Returns:
          The minimum attack power in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.power for x in self.data if isinstance(x.power, int)]
        if array:
            return min(array)
        else:
            return 0

    def names(self) -> list[str]:
        '''
        Returns the set of all card names in this card list.

        Returns:
          The unique `list` of card names within the list of cards.
        '''
        return sorted(list(set([card.name for card in self.data])))

    def num_blue(self) -> int:
        '''
        Returns the number of "blue" cards (pitch 3) in this card list.

        Returns:
          The number of cards in this card list that pitch for 3 resources.
        '''
        return len(self.filter(pitch=3))

    def num_red(self) -> int:
        '''
        Returns the number of "red" cards (pitch 1) in this card list.

        Returns:
          The number of cards in this card list that pitch for 1 resource.
        '''
        return len(self.filter(pitch=1))

    def num_yellow(self) -> int:
        '''
        Returns the number of "yellow" cards (pitch 2) in this card list.

        Returns:
          The number of cards in this card list that pitch for 2 resources.
        '''
        return len(self.filter(pitch=2))

    def pitch_cost_difference(self) -> int:
        '''
        Returns the difference between the pitch and cost values of all cards.

        Note:
          A positive integer indicates that on average one generates more pitch
          value than consumes it.

        Tip: Warning
          This calculation does not take into effect any additional pitch/cost a
          card might incur in its body text.

        Returns:
          The pitch-cost difference of the list of cards.
        '''
        return self.total_pitch() - self.total_cost()

    def pitch_values(self) -> list[int]:
        '''
        Returns the set of all card pitch values associated with this list of
        cards.

        Tip: Warning
          This excludes cards with no pitch or with variable pitch.

        Returns:
          The unique `list` of card pitch values within the list of cards.
        '''
        res = []
        for card in self.data:
            if isinstance(card.pitch, int): res.append(card.pitch)
        return sorted(list(set(res)))

    def power_defense_difference(self) -> int:
        '''
        Returns the difference between the power and defense values of all
        cards.

        Note:
          A positive integer indicates the deck prefers an offensive strategy.

        Tip: Warning
          This calculation does not take into effect any additional power/defense
          a card might incur in its body text.

        Returns:
          The power-defense difference of the list of cards.
        '''
        return self.total_power() - self.total_defense()

    def power_values(self) -> list[int]:
        '''
        Returns the set of all card power values associated with this list of
        cards.

        Tip: Warning
          This excludes cards with no power or with variable power.

        Returns:
          The unique `list` of power values within the list of cards.
        '''
        res = []
        for card in self.data:
            if isinstance(card.power, int): res.append(card.power)
        return sorted(list(set(res)))

    def save(self, file_path: str):
        '''
        Saves the list of cards to the specified file path.

        Args:
          file_path: The file path to save to.
        '''
        with open(os.path.expanduser(file_path), 'w') as f:
            if file_path.endswith('.json'):
                f.write(self.to_json())
            else:
                raise Exception('specified file path is not a JSON file')

    def sort(self, key: Any = 'name', reverse: bool = False) -> CardList:
        '''
        Sorts the list of cards, returning a new sorted collection.

        The `key` parameter may be:

        * A function/lambda on each card.
        * A string corresponding to the field to sort by (for example:
          `type_text`). Any `None` values will be shifted to the beginning of
          the resulting `CardList`, or at the end if `reverse` is equal to
          `True`. Note that when specifying `grants`, `keywords`, `tags` or
          `types`, the ordering is based on the _number_ of values within
          those lists. `rarities` is a special case where cards are sorted by
          their highest/lowest rarity value. `identifiers` and `sets` are
          sorted by their first element.

        Args:
          key: The `Card` field to sort by.
          reverse: Whether to reverse the sort order.

        Returns:
          A new, sorted `CardList` object.
        '''
        if isinstance(key, str):
            contains_none = []
            to_sort = []
            for card in self.data:
                if card[key] is None:
                    contains_none.append(copy.deepcopy(card))
                elif isinstance(card[key], str) and key in ['cost', 'defense', 'health', 'intelligence', 'pitch', 'power']:
                    contains_none.append(copy.deepcopy(card))
                else:
                    to_sort.append(copy.deepcopy(card))
            if key in ['identifiers', 'sets']:
                sorted_part = sorted(to_sort, key = lambda x: x[key][0], reverse = reverse)
            elif key in ['grants', 'keywords', 'tags', 'types']:
                sorted_part = sorted(to_sort, key = lambda x: len(x[key]), reverse = reverse)
            elif key == 'rarities':
                sorted_part = sorted(to_sort, key = lambda x: sorted(RARITY_VALUE[y] for y in x[key])[-1] if x[key] else -1, reverse = reverse)
            else:
                sorted_part = sorted(to_sort, key = lambda x: x[key], reverse = reverse)
            if reverse:
                return CardList(sorted_part + contains_none)
            else:
                return CardList(contains_none + sorted_part)
        else:
            return CardList(sorted(copy.deepcopy(self.data), key = key, reverse = reverse))

    def rarities(self) -> list[str]:
        '''
        Returns the set of all card rarities in this card list.

        Returns:
          A unique `list` of card rarities in the list of cards.
        '''
        res = []
        for card in self.data:
            res.extend(card.rarities)
        return sorted(list(set(res)))

    def reactions(self) -> CardList:
        '''
        Returns the set of all attack and defense reaction cards in this card
        list.

        Returns:
          A list of all attack and defense reaction cards within the card list.
        '''
        return CardList([card for card in self.data if card.is_reaction()])

    def sets(self) -> list[str]:
        '''
        Returns the set of all card sets in this list.

        Returns:
          A unique `list` of all card sets within the list of cards.
        '''
        card_sets = []
        for card in self.data:
            card_sets.extend(card.sets)
        return sorted(list(set(card_sets)))

    def shuffle(self) -> None:
        '''
        Shuffles this list of cards in-place.
        '''
        random.shuffle(self.data)

    def statistics(self, precision: int = 2) -> dict[str, int | float]:
        '''
        Computes helpful statistics associated with this collection of cards.

        Note:
          See the source of this method to get an idea of what the output `dict`
          looks like.

        Tip: Warning
          Cards with variable or no value for certain fields will be excluded
          from that field's calculations.

        Args:
          precision: Specifies the number of decimal places any `float` result will be rounded to.

        Returns:
          A `dict` containing the results of various statistical functions.
        '''
        return {
            'count': len(self.data),
            'max_cost': self.max_cost(),
            'max_defense': self.max_defense(),
            'max_health': self.max_health(),
            'max_intelligence': self.max_intelligence(),
            'max_pitch': self.max_pitch(),
            'max_power': self.max_power(),
            'mean_cost': self.mean_cost(precision),
            'mean_defense': self.mean_defense(precision),
            'mean_health': self.mean_health(precision),
            'mean_intelligence': self.mean_intelligence(precision),
            'mean_pitch': self.mean_pitch(precision),
            'mean_power': self.mean_power(precision),
            'median_cost': self.median_cost(precision),
            'median_defense': self.median_defense(precision),
            'median_health': self.median_health(precision),
            'median_intelligence': self.median_intelligence(precision),
            'median_pitch': self.median_pitch(precision),
            'median_power': self.median_power(precision),
            'min_cost': self.min_cost(),
            'min_defense': self.min_defense(),
            'min_health': self.min_health(),
            'min_intelligence': self.min_intelligence(),
            'min_pitch': self.min_pitch(),
            'min_power': self.min_power(),
            'num_blue': self.num_blue(),
            'num_red': self.num_red(),
            'num_yellow': self.num_yellow(),
            'pitch_cost_difference': self.pitch_cost_difference(),
            'power_defense_difference': self.power_defense_difference(),
            'stdev_cost': self.stdev_cost(precision),
            'stdev_defense': self.stdev_defense(precision),
            'stdev_health': self.stdev_health(precision),
            'stdev_intelligence': self.stdev_intelligence(precision),
            'stdev_pitch': self.stdev_pitch(precision),
            'stdev_power': self.stdev_power(precision),
            'total_cost': self.total_cost(),
            'total_defense': self.total_defense(),
            'total_health': self.total_health(),
            'total_intelligence': self.total_intelligence(),
            'total_pitch': self.total_pitch(),
            'total_power': self.total_power(),
        }

    def stdev_cost(self, precision: int = 2) -> float:
        '''
        Computes the standard deviation of card cost within this card list.

        Tip: Warning
          Cards with variable or no cost are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The standard deviation of card cost in the list.
        '''
        if len(self.data) < 2: return 0.0
        array = [x.cost for x in self.data if isinstance(x.cost, int)]
        if len(array) >= 2:
            return round(stdev(array), precision)
        else:
            return 0.0

    def stdev_defense(self, precision: int = 2) -> float:
        '''
        Computes the standard deviation of card defense within this card list.

        Tip: Warning
          Cards with variable or no defense are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The standard deviation of card defense in the list.
        '''
        if len(self.data) < 2: return 0.0
        array = [x.defense for x in self.data if isinstance(x.defense, int)]
        if len(array) >= 2:
            return round(stdev(array), precision)
        else:
            return 0.0

    def stdev_health(self, precision: int = 2) -> float:
        '''
        Computes the standard deviation of card health within this card list.

        Tip: Warning
          Cards with variable or no health are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The standard deviation of health in the list.
        '''
        if len(self.data) < 2: return 0.0
        array = [x.health for x in self.data if isinstance(x.health, int)]
        if len(array) >= 2:
            return round(stdev(array), precision)
        else:
            return 0.0

    def stdev_intelligence(self, precision: int = 2) -> float:
        '''
        Computes the standard deviation of card intelligence within this card list.

        Tip: Warning
          Cards with variable or no intelligence are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The standard deviation of intelligence in the list.
        '''
        if len(self.data) < 2: return 0.0
        array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
        if len(array) >= 2:
            return round(stdev(array), precision)
        else:
            return 0.0

    def stdev_pitch(self, precision: int = 2) -> float:
        '''
        Computes the standard deviation of card pitch within this card list.

        Tip: Warning
          Cards with variable or no pitch are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The standard deviation of pitch value in the list.
        '''
        if len(self.data) < 2: return 0.0
        array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
        if len(array) >= 2:
            return round(stdev(array), precision)
        else:
            return 0.0

    def stdev_power(self, precision: int = 2) -> float:
        '''
        Computes the standard deviation of card power within this card list.

        Tip: Warning
          Cards with variable or no power are ignored.

        Args:
          precision: Specifies the number of decimal places the result will be rounded to.

        Returns:
          The standard deviation of attack power in the list.
        '''
        if len(self.data) < 2: return 0.0
        array = [x.power for x in self.data if isinstance(x.power, int)]
        if len(array) >= 2:
            return round(stdev(array), precision)
        else:
            return 0.0

    def to_dataframe(self) -> DataFrame:
        '''
        Converts the list of cards into a [pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html).

        Returns:
          A pandas `DataFrame` object representing the list of cards.
        '''
        return DataFrame(self.data)

    def to_json(self) -> str:
        '''
        Converts the list of cards to a JSON string representation.

        Returns:
          A JSON string representation of the list of cards.
        '''
        return json.dumps(self.to_list(), indent=JSON_INDENT)

    def to_list(self) -> list[dict[str, Any]]:
        '''
        Converts the list of cards into a raw Python list with nested
        dictionaries.

        Returns:
          A `list` of `dict` objects containing only Python primitives.
        '''
        return [card.to_dict() for card in self.data]

    def tokens(self) -> CardList:
        '''
        Returns the set of all token cards in this card list.

        Returns:
          The set of token cards in the list.
        '''
        return CardList([card for card in self.data if card.is_token()])

    def total_cost(self) -> int:
        '''
        Computes the total card cost within this card list.

        Tip: Warning
          Cards with variable or no cost are ignored.

        Returns:
          The total cost of all cards in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.cost for x in self.data if isinstance(x.cost, int)]
        if array:
            return sum(array)
        else:
            return 0

    def total_defense(self) -> int:
        '''
        Computes the total card defense within this card list.

        Tip: Warning
          Cards with variable or no defense are ignored.

        Returns:
          The total defense of all cards in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.defense for x in self.data if isinstance(x.defense, int)]
        if array:
            return sum(array)
        else:
            return 0

    def total_health(self) -> int:
        '''
        Computes the total card health within this card list.

        Tip: Warning
          Cards with variable or no health are ignored.

        Returns:
          The total health of all cards in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.health for x in self.data if isinstance(x.health, int)]
        if array:
            return sum(array)
        else:
            return 0

    def total_intelligence(self) -> int:
        '''
        Computes the total card intelligence within this card list.

        Tip: Warning
          Cards with variable or no intelligence are ignored.

        Returns:
          The total intelligence of all cards in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
        if array:
            return sum(array)
        else:
            return 0

    def total_pitch(self) -> int:
        '''
        Computes the total card pitch within this card list.

        Tip: Warning
          Cards with variable or no pitch are ignored.

        Returns:
          The total pitch value of all cards in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
        if array:
            return sum(array)
        else:
            return 0

    def total_power(self) -> int:
        '''
        Computes the total card power within this card list.

        Tip: Warning
          Cards with variable or no power are ignored.

        Returns:
          The total attack power of all cards in the list.
        '''
        if len(self.data) < 1: return 0
        array = [x.power for x in self.data if isinstance(x.power, int)]
        if array:
            return sum(array)
        else:
            return 0

    def types(self) -> list[str]:
        '''
        Returns the set of all card types in this card list.

        Returns:
          The unique `list` of all card types in the list.
        '''
        res = []
        for card in self.data:
            res.extend(card.types)
        return sorted(list(set(res)))

    def type_texts(self) -> list[str]:
        '''
        Returns the set of all type texts in this card list.

        Returns:
          The unique `list` of all card types in the list.
        '''
        return sorted(list(set([card.type_text for card in self.data])))

    def weapons(self) -> CardList:
        '''
        Returns the set of all weapon cards in this card list.

        Returns:
          The set of all weapon cards in the list.
        '''
        return CardList([card for card in self.data if card.is_weapon()])

actions()

Returns the set of all action cards in this card list.

Returns:

Type Description
CardList

The set of all action cards in the card list.

Source code in fab/card.py
474
475
476
477
478
479
480
481
def actions(self) -> CardList:
    '''
    Returns the set of all action cards in this card list.

    Returns:
      The set of all action cards in the card list.
    '''
    return CardList([card for card in self.data if card.is_action()])

attack_reactions()

Returns the set of all attack reaction cards in this card list.

Returns:

Type Description
CardList

The set of all attack reaction cards in the card list.

Source code in fab/card.py
492
493
494
495
496
497
498
499
def attack_reactions(self) -> CardList:
    '''
    Returns the set of all attack reaction cards in this card list.

    Returns:
      The set of all attack reaction cards in the card list.
    '''
    return CardList([card for card in self.data if card.is_attack_reaction()])

attacks()

Returns the set of all attack cards in this card list.

Returns:

Type Description
CardList

The set of all attack cards in the card list.

Source code in fab/card.py
483
484
485
486
487
488
489
490
def attacks(self) -> CardList:
    '''
    Returns the set of all attack cards in this card list.

    Returns:
      The set of all attack cards in the card list.
    '''
    return CardList([card for card in self.data if card.is_attack()])

auras()

Returns the set of all aura cards in this card list.

Returns:

Type Description
CardList

The set of all aura cards in the card list.

Source code in fab/card.py
501
502
503
504
505
506
507
508
def auras(self) -> CardList:
    '''
    Returns the set of all aura cards in this card list.

    Returns:
      The set of all aura cards in the card list.
    '''
    return CardList([card for card in self.data if card.is_aura()])

costs()

Returns the set of all card costs associated with this list of cards.

Warning

This excludes cards with no cost or with variable cost.

Returns:

Type Description
list[int]

The set of all card costs in the card list.

Source code in fab/card.py
510
511
512
513
514
515
516
517
518
519
520
521
522
523
def costs(self) -> list[int]:
    '''
    Returns the set of all card costs associated with this list of cards.

    Tip: Warning
      This excludes cards with no cost or with variable cost.

    Returns:
      The set of all card costs in the card list.
    '''
    res = []
    for card in self.data:
        if isinstance(card.cost, int): res.append(card.cost)
    return sorted(list(set(res)))

counts()

Computes a dict of card counts, where keys correspond to the full_name of Card objects.

Returns:

Type Description
dict[str, int]

A dict of card counts by full name.

Source code in fab/card.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def counts(self) -> dict[str, int]:
    '''
    Computes a `dict` of card counts, where keys correspond to the
    `full_name` of `Card` objects.

    Returns:
      A `dict` of card counts by full name.
    '''
    counts = {}
    for card in self.data:
        if card.full_name in counts:
            counts[card.full_name] += 1
        else:
            counts[card.full_name] = 1
    return counts

defense_reactions()

Returns the set of all defense reaction cards in this card list.

Returns:

Type Description
CardList

The set of all defense reaction cards in the card list.

Source code in fab/card.py
541
542
543
544
545
546
547
548
def defense_reactions(self) -> CardList:
    '''
    Returns the set of all defense reaction cards in this card list.

    Returns:
      The set of all defense reaction cards in the card list.
    '''
    return CardList([card for card in self.data if card.is_defense_reaction()])

defense_values()

Returns the set of all card defense values associated with this list of cards.

Warning

This excludes cards with no defense or with variable defense.

Returns:

Type Description
list[int]

A unique list of card defense values associated with the list of cards.

Source code in fab/card.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def defense_values(self) -> list[int]:
    '''
    Returns the set of all card defense values associated with this list of
    cards.

    Tip: Warning
      This excludes cards with no defense or with variable defense.

    Returns:
      A unique `list` of card defense values associated with the list of cards.
    '''
    res = []
    for card in self.data:
        if isinstance(card.defense, int): res.append(card.defense)
    return sorted(list(set(res)))

draw(num, order=-1, remove=False)

Draws the specified number of cards from the list, optionally removing the cards drawn.

Note

If order is set to -1, then cards will be drawn from the end of the list, as if calling list.pop(). When order is 1, cards are drawn from the beginning of the list. If order is 0, then cards are drawn from random positions. Even when remove is False, when drawing with order=0, this method will ensure that the same card will not be drawn more times than it actually exists in the list.

Parameters:

Name Type Description Default
num int

The number of cards to draw from the list.

required
order int

Specifies the method/order in which cards are drawn from the list (see note).

-1
remove bool

Whether to remove the cards drawn from the list.

False

Returns:

Type Description
CardList

The list of cards drawn.

Source code in fab/card.py
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
def draw(self, num: int, order: int = -1, remove: bool = False) -> CardList:
    '''
    Draws the specified number of cards from the list, optionally removing
    the cards drawn.

    Note:
      If `order` is set to `-1`, then cards will be drawn from the _end_ of
      the list, as if calling `list.pop()`. When `order` is `1`, cards are
      drawn from the beginning of the list. If `order` is `0`, then cards
      are drawn from random positions. Even when `remove` is `False`, when
      drawing with `order=0`, this method will ensure that the same card
      will not be drawn more times than it actually exists in the list.

    Args:
      num: The number of cards to draw from the list.
      order: Specifies the method/order in which cards are drawn from the list (see note).
      remove: Whether to remove the cards drawn from the list.

    Returns:
      The list of cards drawn.
    '''
    if num <= 0:
        raise Exception('specified number of cards must be a positive integer')
    res = []
    if order == -1:
        if remove:
            for _ in range(0, num):
                res.append(self.pop())
        else:
            res = self.data[-num:]
    elif order == 0:
        if remove:
            for _ in range(0, num):
                res.append(self.pop(random.randrange(len(self.data))))
        else:
            potential = [c for c in self.data]
            for _ in range(0, num):
                res.append(potential.pop(random.randrange(len(potential))))
    elif order == 1:
        if remove:
            for _ in range(0, num):
                res.append(self.pop(0))
        else:
            res = self.data[num:]
    else:
        raise Exception('specified "order" must be -1, 0, or 1')
    return CardList(res)

empty() staticmethod

Returns a new empty card list containing no cards.

Returns:

Type Description
CardList

An empty card list.

Source code in fab/card.py
614
615
616
617
618
619
620
621
622
@staticmethod
def empty() -> CardList:
    '''
    Returns a new empty card list containing no cards.

    Returns:
      An empty card list.
    '''
    return CardList([])

equipment()

Returns the set of all equipment cards in this card list.

Returns:

Type Description
CardList

The set of all equipment cards in the card list.

Source code in fab/card.py
624
625
626
627
628
629
630
631
def equipment(self) -> CardList:
    '''
    Returns the set of all equipment cards in this card list.

    Returns:
      The set of all equipment cards in the card list.
    '''
    return CardList([card for card in self.data if card.is_equipment()])

filter(body=None, cost=None, defense=None, full_name=None, grants=None, health=None, intelligence=None, keywords=None, legality=None, name=None, negate=False, pitch=None, power=None, rarities=None, sets=None, tags=None, type_text=None, types=None)

Filters a list of cards according to a function against a particular Card field.

In addition to functions/lambdas, you can also specify:

  • A str for the body, full_name, name, or type_text keyword arguments. These comparisons are case-insensitive and will match substrings.
  • An int for the cost, defense, health, intelligence, pitch, or power keyword arguments. None and str values will not be included in the results.
  • A tuple[int, int] for the cost, defense, health, intelligence, pitch, or power keyword arguments. This defines a range of values to include (inclusive).
  • A list[str] for the grants, keywords, rarities, sets, tags, and types keyword arguments. At least one value of the list must be present for an item to be included.
  • A str for the grants, keywords, rarities, sets, tags, and types keyword arguments. This is the same as passing in a single-element list.
  • A str for the legality keyword argument, corresponding to a format code that the card must be legal in to be included.
  • The strings r, red, y, yellow, b, or blue for the pitch keyword argument, corresponding to the color of the card (case-insensitive).

Parameters:

Name Type Description Default
body Optional[Any]

A str or function to filter by body.

None
cost Optional[Any]

An int, tuple[int, int], or function to filter by cost.

None
defense Optional[Any]

An int, tuple[int, int], or function to filter by defense.

None
full_name Optional[Any]

A str or function to filter by full_name.

None
grants Optional[Any]

A str, list[str], or function to filter by grants.

None
health Optional[Any]

An int, tuple[int, int], or function to filter by health.

None
intelligence Optional[Any]

An int, tuple[int, int], or function to filter by intelligence.

None
keywords Optional[Any]

A str, list[str], or function to filter by keywords.

None
legality Optional[Any]

A str or function to filter by legality.

None
name Optional[Any]

A str or function to filter by name.

None
negate bool

Whether to invert the filter specification.

False
pitch Optional[Any]

An int, str, tuple[int, int], or function to filter by pitch.

None
power Optional[Any]

An int, tuple[int, int], or function to filter by power.

None
rarities Optional[Any]

A str, list[str] or function to filter by rarities.

None
sets Optional[Any]

A str, list[str], or function to filter by sets.

None
tags Optional[Any]

A str, list[str], or function to filter by tags.

None
type_text Optional[Any]

A str or function to filter by type_text.

None
types Optional[Any]

A str, list[str], or function to filter by types.

None

Returns:

Type Description
CardList

A new CardList containing copies of Card objects that meet the filtering requirements.

Source code in fab/card.py
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
def filter(
        self,
        body: Optional[Any] = None,
        cost: Optional[Any] = None,
        defense: Optional[Any] = None,
        full_name: Optional[Any] = None,
        grants: Optional[Any] = None,
        health: Optional[Any] = None,
        intelligence: Optional[Any] = None,
        keywords: Optional[Any] = None,
        legality: Optional[Any] = None,
        name: Optional[Any] = None,
        negate: bool = False,
        pitch: Optional[Any] = None,
        power: Optional[Any] = None,
        rarities: Optional[Any] = None,
        sets: Optional[Any] = None,
        tags: Optional[Any] = None,
        type_text: Optional[Any] = None,
        types: Optional[Any] = None
) -> CardList:
    '''
    Filters a list of cards according to a function against a particular
    `Card` field.

    In addition to functions/lambdas, you can also specify:

    * A `str` for the `body`, `full_name`, `name`, or `type_text` keyword
      arguments. These comparisons are case-insensitive and will match
      substrings.
    * An `int` for the `cost`, `defense`, `health`, `intelligence`,
      `pitch`, or `power` keyword arguments. `None` and `str` values
      will not be included in the results.
    * A `tuple[int, int]` for the `cost`, `defense`, `health`,
      `intelligence`, `pitch`, or `power` keyword arguments. This defines
      a range of values to include (inclusive).
    * A `list[str]` for the `grants`, `keywords`, `rarities`, `sets`,
      `tags`, and `types` keyword arguments. At least one value of the
      list must be present for an item to be included.
    * A `str` for the `grants`, `keywords`, `rarities`, `sets`, `tags`,
      and `types` keyword arguments. This is the same as passing in a
      single-element list.
    * A `str` for the `legality` keyword argument, corresponding to a format
      code that the card must be legal in to be included.
    * The strings `r`, `red`, `y`, `yellow`, `b`, or `blue` for the `pitch`
      keyword argument, corresponding to the color of the card
      (case-insensitive).

    Args:
      body: A `str` or function to filter by `body`.
      cost: An `int`, `tuple[int, int]`, or function to filter by `cost`.
      defense: An `int`, `tuple[int, int]`, or function to filter by `defense`.
      full_name: A `str` or function to filter by `full_name`.
      grants: A `str`, `list[str]`, or function to filter by `grants`.
      health: An `int`, `tuple[int, int]`, or function to filter by `health`.
      intelligence: An `int`, `tuple[int, int]`, or function to filter by `intelligence`.
      keywords: A `str`, `list[str]`, or function to filter by `keywords`.
      legality: A `str` or function to filter by `legality`.
      name: A `str` or function to filter by `name`.
      negate: Whether to invert the filter specification.
      pitch: An `int`, `str`, `tuple[int, int]`, or function to filter by `pitch`.
      power: An `int`, `tuple[int, int]`, or function to filter by `power`.
      rarities: A `str`, `list[str]` or function to filter by `rarities`.
      sets: A `str`, `list[str]`, or function to filter by `sets`.
      tags: A `str`, `list[str]`, or function to filter by `tags`.
      type_text: A `str` or function to filter by `type_text`.
      types: A `str`, `list[str]`, or function to filter by `types`.

    Returns:
      A new `CardList` containing copies of `Card` objects that meet the filtering requirements.
    '''
    if len(self.data) < 2: return copy.deepcopy(self)
    filtered = []
    for c in self:
        if not body is None:
            if isinstance(body, str):
                if negate:
                    if body.lower() in str(c.body).lower(): continue
                else:
                    if not body.lower() in str(c.body).lower(): continue
            else:
                if negate:
                    if body(c.body): continue
                else:
                    if not body(c.body): continue
        if not cost is None:
            if isinstance(cost, int):
                if negate:
                    if isinstance(c.cost, int) and cost == c.cost: continue
                else:
                    if not isinstance(c.cost, int) or cost != c.cost: continue
            elif isinstance(cost, tuple):
                if negate:
                    if isinstance(c.cost, int) and c.cost >= cost[0] and c.cost <= cost[1]: continue
                else:
                    if not isinstance(c.cost, int) or c.cost < cost[0] or c.cost > cost[1]: continue
            else:
                if negate:
                    if cost(c.cost): continue
                else:
                    if not cost(c.cost): continue
        if not defense is None:
            if isinstance(defense, int):
                if negate:
                    if isinstance(c.defense, int) and defense == c.defense: continue
                else:
                    if not isinstance(c.defense, int) or defense != c.defense: continue
            elif isinstance(defense, tuple):
                if negate:
                    if isinstance(c.defense, int) and c.defense >= defense[0] and c.defense <= defense[1]: continue
                else:
                    if not isinstance(c.defense, int) or c.defense < defense[0] or c.defense > defense[1]: continue
            else:
                if negate:
                    if defense(c.defense): continue
                else:
                    if not defense(c.defense): continue
        if not full_name is None:
            if isinstance(full_name, str):
                if negate:
                    if full_name.lower() in c.full_name.lower(): continue
                else:
                    if not full_name.lower() in c.full_name.lower(): continue
            else:
                if negate:
                    if full_name(c.full_name): continue
                else:
                    if not full_name(c.full_name): continue
        if not grants is None:
            if isinstance(grants, str):
                if negate:
                    if grants in c.grants: continue
                else:
                    if not grants in c.grants: continue
            elif isinstance(grants, list):
                if negate:
                    if True in [(x in c.grants) for x in grants]: continue
                else:
                    if not (True in [(x in c.grants) for x in grants]): continue
            else:
                if negate:
                    if grants(c.grants): continue
                else:
                    if not grants(c.grants): continue
        if not health is None:
            if isinstance(health, int):
                if negate:
                    if isinstance(c.health, int) and health == c.health: continue
                else:
                    if not isinstance(c.health, int) or health != c.health: continue
            elif isinstance(health, tuple):
                if negate:
                    if isinstance(c.health, int) and c.health >= health[0] and c.health <= health[1]: continue
                else:
                    if not isinstance(c.health, int) or c.health < health[0] or c.health > health[1]: continue
            else:
                if negate:
                    if health(c.health): continue
                else:
                    if not health(c.health): continue
        if not intelligence is None:
            if isinstance(intelligence, int):
                if negate:
                    if isinstance(c.intelligence, int) and intelligence == c.intelligence: continue
                else:
                    if not isinstance(c.intelligence, int) or intelligence != c.intelligence: continue
            elif isinstance(intelligence, tuple):
                if negate:
                    if isinstance(c.intelligence, int) and c.intelligence >= intelligence[0] and c.intelligence <= intelligence[1]: continue
                else:
                    if not isinstance(c.intelligence, int) or c.intelligence < intelligence[0] or c.intelligence > intelligence[1]: continue
            else:
                if negate:
                    if intelligence(c.intelligence): continue
                else:
                    if not intelligence(c.intelligence): continue
        if not keywords is None:
            if isinstance(keywords, str):
                if negate:
                    if keywords in c.keywords: continue
                else:
                    if not keywords in c.keywords: continue
            elif isinstance(keywords, list):
                if negate:
                    if True in [(x in c.keywords) for x in keywords]: continue
                else:
                    if not (True in [(x in c.keywords) for x in keywords]): continue
            else:
                if negate:
                    if keywords(c.keywords): continue
                else:
                    if not keywords(c.keywords): continue
        if not legality is None:
            if isinstance(legality, str):
                if negate:
                    if c.legality[legality]: continue
                else:
                    if not c.legality[legality]: continue
            else:
                if negate:
                    if legality(c.legality): continue
                else:
                    if not legality(c.legality): continue
        if not name is None:
            if isinstance(name, str):
                if negate:
                    if name.lower() in c.name.lower(): continue
                else:
                    if not name.lower() in c.name.lower(): continue
            else:
                if negate:
                    if name(c.name): continue
                else:
                    if not name(c.name): continue
        if not pitch is None:
            if isinstance(pitch, int):
                if negate:
                    if isinstance(c.pitch, int) and pitch == c.pitch: continue
                else:
                    if not isinstance(c.pitch, int) or pitch != c.pitch: continue
            elif isinstance(pitch, str):
                pl = pitch.lower()
                if not pl in ['r', 'red', 'y', 'yellow', 'b', 'blue']:
                    raise Exception(f'unknown pitch filter string "{pitch}"')
                if negate:
                    if pl.startswith('b') and c.is_blue(): continue
                    elif pl.startswith('r') and c.is_red(): continue
                    elif pl.startswith('y') and c.is_yellow(): continue
                else:
                    if pl.startswith('b') and not c.is_blue(): continue
                    elif pl.startswith('r') and not c.is_red(): continue
                    elif pl.startswith('y') and not c.is_yellow(): continue
            elif isinstance(pitch, tuple):
                if negate:
                    if isinstance(c.pitch, int) and c.pitch >= pitch[0] and c.pitch <= pitch[1]: continue
                else:
                    if not isinstance(c.pitch, int) or c.pitch < pitch[0] or c.pitch > pitch[1]: continue
            else:
                if negate:
                    if pitch(c.pitch): continue
                else:
                    if not pitch(c.pitch): continue
        if not power is None:
            if isinstance(power, int):
                if negate:
                    if isinstance(c.power, int) and power == c.power: continue
                else:
                    if not isinstance(c.power, int) or power != c.power: continue
            elif isinstance(power, tuple):
                if negate:
                    if isinstance(c.power, int) and c.power >= power[0] and c.power <= power[1]: continue
                else:
                    if not isinstance(c.power, int) or c.power < power[0] or c.power > power[1]: continue
            else:
                if negate:
                    if power(c.power): continue
                else:
                    if not power(c.power): continue
        if not rarities is None:
            if isinstance(rarities, str):
                if negate:
                    if rarities in c.rarities: continue
                else:
                    if not rarities in c.rarities: continue
            elif isinstance(rarities, list):
                if negate:
                    if True in [(x in c.rarities) for x in rarities]: continue
                else:
                    if not (True in [(x in c.rarities) for x in rarities]): continue
            else:
                if negate:
                    if rarities(c.rarities): continue
                else:
                    if not rarities(c.rarities): continue
        if not sets is None:
            if isinstance(sets, str):
                if negate:
                    if sets in c.sets: continue
                else:
                    if not sets in c.sets: continue
            elif isinstance(sets, list):
                if negate:
                    if True in [(x in c.sets) for x in sets]: continue
                else:
                    if not (True in [(x in c.sets) for x in sets]): continue
            else:
                if negate:
                    if sets(c.sets): continue
                else:
                    if not sets(c.sets): continue
        if not tags is None:
            if isinstance(tags, str):
                if negate:
                    if tags in c.tags: continue
                else:
                    if not tags in c.tags: continue
            elif isinstance(tags, list):
                if negate:
                    if True in [(x in c.tags) for x in tags]: continue
                else:
                    if not (True in [(x in c.tags) for x in tags]): continue
            else:
                if negate:
                    if tags(c.tags): continue
                else:
                    if not tags(c.tags): continue
        if not type_text is None:
            if isinstance(type_text, str):
                if negate:
                    if type_text.lower() in c.type_text.lower(): continue
                else:
                    if not type_text.lower() in c.type_text.lower(): continue
            else:
                if negate:
                    if type_text(c.type_text): continue
                else:
                    if not type_text(c.type_text): continue
        if not types is None:
            if isinstance(types, str):
                if negate:
                    if types in c.types: continue
                else:
                    if not types in c.types: continue
            elif isinstance(types, list):
                if negate:
                    if True in [(x in c.types) for x in types]: continue
                else:
                    if not (True in [(x in c.types) for x in types]): continue
            else:
                if negate:
                    if types(c.types): continue
                else:
                    if not types(c.types): continue
        filtered.append(copy.deepcopy(c))
    return CardList(filtered)

from_csv(csvstr, delimiter='\t') staticmethod

Creates a new list of cards given a CSV string representation.

Parameters:

Name Type Description Default
csvstr str

The CSV string representation to parse.

required
delimiter str

An alternative primary delimiter to pass to csv.DictReader.

'\t'

Returns:

Type Description
CardList

A new CardList object from the parsed data.

Source code in fab/card.py
 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
@staticmethod
def from_csv(csvstr: str, delimiter: str = '\t') -> CardList:
    '''
    Creates a new list of cards given a CSV string representation.

    Args:
      csvstr: The CSV string representation to parse.
      delimiter: An alternative primary delimiter to pass to `csv.DictReader`.

    Returns:
      A new `CardList` object from the parsed data.
    '''
    try:
        csv_data = csv.DictReader(io.StringIO(csvstr), delimiter = delimiter)
    except Exception as e:
        raise Exception(f'unable to parse CSV content - {e}')
    def int_str_or_none(inputstr: str) -> int | str | None:
        '''
        A helper function for building out stuff like `cost`, etc.
        '''
        if not inputstr:
            return None
        elif inputstr.isdigit():
            return int(inputstr)
        else:
            return inputstr
    def image_url_parser(inputstr: str) -> list[str]:
        '''
        A helper function for parsing our the image URL list.
        '''
        if not inputstr: return []
        result = []
        if ',' in inputstr:
            for substrings in [x.split(' - ', 1) for x in unidecode(inputstr).split(',') if ' - ' in x]:
                url = substrings[0].strip()
                result.append(url)
        elif ' - ' in inputstr:
            url = unidecode(inputstr).split(' - ', 1)[0].strip()
            result.append(url)
        return result
    def legality_parser(csv_entry: dict[str, Any]) -> dict[str, bool]:
        '''
        A helper function for parsing card legality.
        '''
        res = {}
        blitz_legal = not csv_entry['Blitz Legal'].lower() in ['no', 'false']
        blitz_ll = True if csv_entry['Blitz Living Legend'] else False
        blitz_banned = True if csv_entry['Blitz Banned'] else False
        cc_legal = not csv_entry['CC Legal'].lower() in ['no', 'false']
        cc_ll = True if csv_entry['CC Living Legend'] else False
        cc_banned = True if csv_entry['CC Banned'] else False
        commoner_legal = not csv_entry['Commoner Legal'].lower() in ['no', 'false']
        commoner_banned = True if csv_entry['Commoner Banned'] else False
        res['B'] = blitz_legal and not blitz_ll and not blitz_banned
        res['CC'] = cc_legal and not cc_ll and not cc_banned
        res['C'] = commoner_legal and not commoner_banned
        res['UPF'] = res['CC']
        return res
    cards = []
    for entry in csv_data:
        try:
          cards.append(Card(
              body         = unidecode(entry['Functional Text'].strip()) if entry['Functional Text'] else None,
              cost         = int_str_or_none(entry['Cost']),
              defense      = int_str_or_none(entry['Defense']),
              flavor_text  = unidecode(entry['Flavor Text'].strip()) if entry['Flavor Text'] else None,
              full_name    = unidecode(entry['Name'].strip()) + (f" ({entry['Pitch']})" if entry['Pitch'].isdigit() else ''),
              grants       = [x.strip() for x in entry['Granted Keywords'].split(',')] if entry['Granted Keywords'] else [],
              health       = int(entry['Health']) if entry['Health'].isdigit() else None,
              identifiers  = [x.strip() for x in entry['Identifiers'].split(',')],
              intelligence = int(entry['Intelligence']) if entry['Intelligence'].isdigit() else None,
              image_urls   = image_url_parser(entry['Image URLs']),
              keywords     = list(set(([x.strip() for x in entry['Card Keywords'].split(',')] if entry['Card Keywords'] else []) + ([x.strip() for x in entry['Ability and Effect Keywords'].split(',')] if entry['Ability and Effect Keywords'] else []))),
              legality     = legality_parser(entry),
              name         = unidecode(entry['Name'].strip()),
              pitch        = int(entry['Pitch']) if entry['Pitch'].isdigit() else None,
              power        = int_str_or_none(entry['Power']),
              rarities     = [x.strip() for x in entry['Rarity'].split(',')],
              sets         = [x.strip() for x in entry['Set Identifiers'].split(',')],
              tags         = [],
              type_text    = unidecode(entry['Type Text'].strip()),
              types        = [x.strip() for x in entry['Types'].split(',')]
           ))
        except Exception as e:
            raise Exception(f'unable to parse intermediate card data - {e} - {entry}')
    return CardList(cards)

from_json(jsonstr) staticmethod

Creates a new list of cards given a JSON string representation.

Parameters:

Name Type Description Default
jsonstr str

The JSON string representation to parse into a card list.

required

Returns:

Type Description
CardList

A new CardList object from the parsed data.

Source code in fab/card.py
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
@staticmethod
def from_json(jsonstr: str) -> CardList:
    '''
    Creates a new list of cards given a JSON string representation.

    Args:
      jsonstr: The JSON string representation to parse into a card list.

    Returns:
      A new `CardList` object from the parsed data.
    '''
    cards = []
    for jcard in json.loads(jsonstr):
        cards.append(Card(**jcard))
    return CardList(cards)

full_names()

Returns the set of all full card names within this list of cards.

Returns:

Type Description
list[str]

A unique list of all full card names within the list of cards.

Source code in fab/card.py
1072
1073
1074
1075
1076
1077
1078
1079
def full_names(self) -> list[str]:
    '''
    Returns the set of all full card names within this list of cards.

    Returns:
      A unique `list` of all full card names within the list of cards.
    '''
    return sorted(list(set([card.full_name for card in self.data])))

grants()

Returns the set of all card grant keywords within this list of cards.

Returns:

Type Description
list[str]

A unique list of all card grant keywords within the list of cards.

Source code in fab/card.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
def grants(self) -> list[str]:
    '''
    Returns the set of all card grant keywords within this list of cards.

    Returns:
      A unique `list` of all card grant keywords within the list of cards.
    '''
    res = []
    for card in self.data:
        res.extend(card.grants)
    return sorted(list(set(res)))

group(by='type_text')

Groups cards by the specified (singular form) of the Card field.

Note

The keys of the resulting dict take on the type described below:

  • str: full_name, grants, keyword, name, rarity, set, type, type_text
  • int: cost, defense, health, intelligence, pitch, power

Certain values of by accept their plural forms, such as rarity or rarities.

Warning

When grouping by cost, defense, health, intelligence, pitch, or power, cards with str or None values for the corresponding field will be excluded from the result.

Parameters:

Name Type Description Default
by str

The Card field to group by.

'type_text'

Returns:

Type Description
dict[int | str, CardList]

A dict of CardList objects grouped by the specified Card field.

Source code in fab/card.py
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
def group(self, by: str = 'type_text') -> dict[int | str, CardList]:
    '''
    Groups cards by the specified (singular form) of the `Card` field.

    Note:
      The keys of the resulting `dict` take on the `type` described below:

      * `str`: `full_name`, `grants`, `keyword`, `name`, `rarity`, `set`, `type`, `type_text`
      * `int`: `cost`, `defense`, `health`, `intelligence`, `pitch`, `power`

      Certain values of `by` accept their plural forms, such as `rarity` or
      `rarities`.

    Tip: Warning
      When grouping by `cost`, `defense`, `health`, `intelligence`, `pitch`,
      or `power`, cards with `str` or `None` values for the corresponding
      field will be excluded from the result.

    Args:
      by: The `Card` field to group by.

    Returns:
      A `dict` of `CardList` objects grouped by the specified `Card` field.
    '''
    if len(self.data) < 1: return {}
    res = {}
    # str keys
    if by == 'full_name':
        for full_name in self.full_names():
            res[full_name] = CardList([card for card in self if card.full_name == full_name]).sort()
    elif by == 'grants':
        for grants in self.grants():
            res[grants] = CardList([card for card in self if grants in card.grants]).sort()
    elif by in ['keyword', 'keywords']:
        for keyword in self.keywords():
            res[keyword] = CardList([card for card in self if keyword in card.keywords]).sort()
    elif by == 'name':
        for name in self.names():
            res[name] = CardList([card for card in self if card.name == name]).sort()
    elif by in ['rarity', 'rarities']:
        for rarity in self.rarities():
            res[rarity] = CardList([card for card in self if rarity in card.rarities]).sort()
    elif by in ['set', 'sets']:
        for card_set in self.sets():
            res[card_set] = CardList([card for card in self if card_set in card.sets]).sort()
    elif by in ['type', 'types']:
        for type_val in self.types():
            res[type_val] = CardList([card for card in self if type_val in card.types]).sort()
    elif by == 'type_text':
        for type_text in self.type_texts():
            res[type_text] = CardList([card for card in self if card.type_text == type_text]).sort()
    # int keys
    elif by == 'cost':
        for cost in self.costs():
            res[cost] = CardList([card for card in self if isinstance(card.cost, int) and card.cost == cost]).sort()
    elif by == 'defense':
        for defense in self.defense_values():
            res[defense] = CardList([card for card in self if isinstance(card.defense, int) and card.defense == defense]).sort()
    elif by == 'health':
        for health in self.health_values():
            res[health] = CardList([card for card in self if isinstance(card.health, int) and card.health == health]).sort()
    elif by == 'intelligence':
        for intelligence in self.intelligence_values():
            res[intelligence] = CardList([card for card in self if isinstance(card.intelligence, int) and card.intelligence == intelligence]).sort()
    elif by == 'pitch':
        for pitch in self.pitch_values():
            res[pitch] = CardList([card for card in self if isinstance(card.pitch, int) and card.pitch == pitch]).sort()
    elif by == 'power':
        for power in self.power_values():
            res[power] = CardList([card for card in self if isinstance(card.power, int) and card.power == power]).sort()
    return res

health_values()

Returns the set of all card health values associated with this list of cards.

Warning

This excludes cards with no health or with variable health.

Returns:

Type Description
list[int]

The unique list of all card health values within the card list.

Source code in fab/card.py
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def health_values(self) -> list[int]:
    '''
    Returns the set of all card health values associated with this list of
    cards.

    Tip: Warning
      This excludes cards with no health or with variable health.

    Returns:
      The unique `list` of all card health values within the card list.
    '''
    res = []
    for card in self.data:
        if isinstance(card.health, int): res.append(card.health)
    return sorted(list(set(res)))

heroes()

Returns the set of all hero cards in this card list.

Returns:

Type Description
CardList

The set of all hero cards within the card list.

Source code in fab/card.py
1221
1222
1223
1224
1225
1226
1227
1228
def heroes(self) -> CardList:
    '''
    Returns the set of all hero cards in this card list.

    Returns:
      The set of all hero cards within the card list.
    '''
    return CardList([card for card in self.data if card.is_hero()])

identifiers()

Returns the set of all card identifiers in this card list.

Returns:

Type Description
list[str]

The unique list of all card identifiers within the card list.

Source code in fab/card.py
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
def identifiers(self) -> list[str]:
    '''
    Returns the set of all card identifiers in this card list.

    Returns:
      The unique `list` of all card identifiers within the card list.
    '''
    res = []
    for card in self.data:
        res.extend(card.identifiers)
    return sorted(list(set(res)))

instants()

Returns the set of all instant cards in this card list.

Returns:

Type Description
CardList

The set of all instant cards within the card list.

Source code in fab/card.py
1242
1243
1244
1245
1246
1247
1248
1249
def instants(self) -> CardList:
    '''
    Returns the set of all instant cards in this card list.

    Returns:
      The set of all instant cards within the card list.
    '''
    return CardList([card for card in self.data if card.is_instant()])

intelligence_values()

Returns the set of all card intelligence values associated with this list of cards.

Warning

This excludes cards with no intelligence or with variable intelligence.

Returns:

Type Description
list[int]

A unique list of all card intelligence values within the list of cards.

Source code in fab/card.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
def intelligence_values(self) -> list[int]:
    '''
    Returns the set of all card intelligence values associated with this
    list of cards.

    Tip: Warning
      This excludes cards with no intelligence or with variable
      intelligence.

    Returns:
      A unique `list` of all card intelligence values within the list of cards.
    '''
    res = []
    for card in self.data:
        if isinstance(card.intelligence, int): res.append(card.intelligence)
    return sorted(list(set(res)))

item_cards()

Returns the set of all item cards in this card list.

Returns:

Type Description
CardList

The set of all item cards within the list of cards.

Source code in fab/card.py
1268
1269
1270
1271
1272
1273
1274
1275
def item_cards(self) -> CardList:
    '''
    Returns the set of all item cards in this card list.

    Returns:
      The set of all item cards within the list of cards.
    '''
    return CardList([card for card in self.data if card.is_item()])

keywords()

Returns the set of all keywords in this card list.

Returns:

Type Description
list[str]

A unique list of all keywords within the list of cards.

Source code in fab/card.py
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
def keywords(self) -> list[str]:
    '''
    Returns the set of all keywords in this card list.

    Returns:
      A unique `list` of all keywords within the list of cards.
    '''
    res = []
    for card in self.data:
        res.extend(card.keywords)
    return sorted(list(set(res)))

legality()

Computes the legality of this list of cards for each game format.

Note

A CardList is not considered legal for a format if it contains any cards not legal for that format.

Returns:

Type Description
dict[str, bool]

A dict of game format str keys and their bool legal status.

Source code in fab/card.py
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
def legality(self) -> dict[str, bool]:
    '''
    Computes the legality of this list of cards for each game format.

    Note:
      A `CardList` is not considered legal for a format if it contains _any_
      cards not legal for that format.

    Returns:
      A `dict` of game format `str` keys and their `bool` legal status.
    '''
    res = {}
    for f in GAME_FORMATS.keys():
        res[f] = not (False in [card.is_legal(f) for card in self.data])
    return res

load(file_path, set_catalog=False) staticmethod

Loads a list of cards from the specified .json or .csv file.

Note

If set_catalog is set to True, then a copy of the loaded card list will also be set as the default card.CARD_CATALOG.

Parameters:

Name Type Description Default
file_path str

The file path to load from.

required
set_catalog bool

Whether to also set the loaded data as the default card catalog.

False

Returns:

Type Description
CardList

A new CardList object.

Source code in fab/card.py
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
@staticmethod
def load(file_path: str, set_catalog: bool = False) -> CardList:
    '''
    Loads a list of cards from the specified `.json` or `.csv` file.

    Note:
      If `set_catalog` is set to `True`, then a copy of the loaded card list
      will also be set as the default `card.CARD_CATALOG`.

    Args:
      file_path: The file path to load from.
      set_catalog: Whether to also set the loaded data as the default card catalog.

    Returns:
      A new `CardList` object.
    '''
    with open(os.path.expanduser(file_path), 'r') as f:
        if file_path.endswith('.json'):
            res = CardList.from_json(f.read())
        elif file_path.endswith('.csv'):
            res = CardList.from_csv(f.read())
        else:
            raise Exception('specified file is not a CSV or JSON file')
    if set_catalog:
        global CARD_CATALOG
        CARD_CATALOG = copy.deepcopy(res)
    return res

max_cost()

Computes the maximum card cost within this card list.

Warning

Cards with variable or no cost are ignored.

Returns:

Type Description
int

The maximum card cost within the list of cards.

Source code in fab/card.py
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
def max_cost(self) -> int:
    '''
    Computes the maximum card cost within this card list.

    Tip: Warning
      Cards with variable or no cost are ignored.

    Returns:
      The maximum card cost within the list of cards.
    '''
    if len(self.data) < 1: return 0
    array = [x.cost for x in self.data if isinstance(x.cost, int)]
    if array:
        return max(array)
    else:
        return 0

max_defense()

Computes the maximum card defense within this card list.

Warning

Cards with variable or no defense are ignored.

Returns:

Type Description
int

The maximum card defense value within the list of cards.

Source code in fab/card.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
def max_defense(self) -> int:
    '''
    Computes the maximum card defense within this card list.

    Tip: Warning
      Cards with variable or no defense are ignored.

    Returns:
      The maximum card defense value within the list of cards.
    '''
    if len(self.data) < 1: return 0
    array = [x.defense for x in self.data if isinstance(x.defense, int)]
    if array:
        return max(array)
    else:
        return 0

max_health()

Computes the maximum card health within this card list.

Warning

Cards with variable or no health are ignored.

Returns:

Type Description
int

The maximum card health value within the list of cards.

Source code in fab/card.py
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
def max_health(self) -> int:
    '''
    Computes the maximum card health within this card list.

    Tip: Warning
      Cards with variable or no health are ignored.

    Returns:
      The maximum card health value within the list of cards.
    '''
    if len(self.data) < 1: return 0
    array = [x.health for x in self.data if isinstance(x.health, int)]
    if array:
        return max(array)
    else:
        return 0

max_intelligence()

Computes the maximum card intelligence within this card list.

Warning

Cards with variable or no intelligence are ignored.

Returns:

Type Description
int

The maximum card intelligence value within the list of cards.

Source code in fab/card.py
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
def max_intelligence(self) -> int:
    '''
    Computes the maximum card intelligence within this card list.

    Tip: Warning
      Cards with variable or no intelligence are ignored.

    Returns:
      The maximum card intelligence value within the list of cards.
    '''
    if len(self.data) < 1: return 0
    array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
    if array:
        return max(array)
    else:
        return 0

max_pitch()

Computes the maximum card pitch within this card list.

Warning

Cards with variable or no pitch are ignored.

Returns:

Type Description
int

The maximum card pitch value within this list of cards.

Source code in fab/card.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
def max_pitch(self) -> int:
    '''
    Computes the maximum card pitch within this card list.

    Tip: Warning
      Cards with variable or no pitch are ignored.

    Returns:
      The maximum card pitch value within this list of cards.
    '''
    if len(self.data) < 1: return 0
    array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
    if array:
        return max(array)
    else:
        return 0

max_power()

Computes the maximum card power within this card list.

Warning

Cards with variable or no power are ignored.

Returns:

Type Description
int

The maximum card power value within this list of cards.

Source code in fab/card.py
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
def max_power(self) -> int:
    '''
    Computes the maximum card power within this card list.

    Tip: Warning
      Cards with variable or no power are ignored.

    Returns:
      The maximum card power value within this list of cards.
    '''
    if len(self.data) < 1: return 0
    array = [x.power for x in self.data if isinstance(x.power, int)]
    if array:
        return max(array)
    else:
        return 0

mean_cost(precision=2)

Computes the mean card cost within this card list.

Warning

Cards with variable or no cost are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The mean card cost of cards in the list.

Source code in fab/card.py
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
def mean_cost(self, precision: int = 2) -> float:
    '''
    Computes the mean card cost within this card list.

    Tip: Warning
      Cards with variable or no cost are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The mean card cost of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.cost for x in self.data if isinstance(x.cost, int)]
    if array:
        return round(mean(array), precision)
    else:
        return 0.0

mean_defense(precision=2)

Computes the mean card defense within this card list.

Warning

Cards with variable or no defense are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The mean defense of cards in the list.

Source code in fab/card.py
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
def mean_defense(self, precision: int = 2) -> float:
    '''
    Computes the mean card defense within this card list.

    Tip: Warning
      Cards with variable or no defense are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The mean defense of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.defense for x in self.data if isinstance(x.defense, int)]
    if array:
        return round(mean(array), precision)
    else:
        return 0.0

mean_health(precision=2)

Computes the mean card health within this card list.

Warning

Cards with variable or no health are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The mean health of cards in the list.

Source code in fab/card.py
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
def mean_health(self, precision: int = 2) -> float:
    '''
    Computes the mean card health within this card list.

    Tip: Warning
      Cards with variable or no health are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The mean health of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.health for x in self.data if isinstance(x.health, int)]
    if array:
        return round(mean(array), precision)
    else:
        return 0.0

mean_intelligence(precision=2)

Computes the mean card intelligence within this card list.

Warning

Cards with variable or no intelligence are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The mean intelligence of cards in the list.

Source code in fab/card.py
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
def mean_intelligence(self, precision: int = 2) -> float:
    '''
    Computes the mean card intelligence within this card list.

    Tip: Warning
      Cards with variable or no intelligence are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The mean intelligence of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
    if array:
        return round(mean(array), precision)
    else:
        return 0.0

mean_pitch(precision=2)

Computes the mean card pitch within this card list.

Warning

Cards with variable or no pitch are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The mean pitch value of cards in the list.

Source code in fab/card.py
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
def mean_pitch(self, precision: int = 2) -> float:
    '''
    Computes the mean card pitch within this card list.

    Tip: Warning
      Cards with variable or no pitch are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The mean pitch value of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
    if array:
        return round(mean(array), precision)
    else:
        return 0.0

mean_power(precision=2)

Computes the mean card power within this card list.

Warning

Cards with variable or no power are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The mean power of cards in the list.

Source code in fab/card.py
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
def mean_power(self, precision: int = 2) -> float:
    '''
    Computes the mean card power within this card list.

    Tip: Warning
      Cards with variable or no power are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The mean power of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.power for x in self.data if isinstance(x.power, int)]
    if array:
        return round(mean(array), precision)
    else:
        return 0.0

median_cost(precision=2)

Computes the median card cost within this card list.

Warning

Cards with variable or no cost are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The median resource cost of cards in the list.

Source code in fab/card.py
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
def median_cost(self, precision: int = 2) -> float:
    '''
    Computes the median card cost within this card list.

    Tip: Warning
      Cards with variable or no cost are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The median resource cost of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.cost for x in self.data if isinstance(x.cost, int)]
    if array:
        return round(median(array), precision)
    else:
        return 0.0

median_defense(precision=2)

Computes the median card defense within this card list.

Warning

Cards with variable or no defense are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The median defense value of cards in the list.

Source code in fab/card.py
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
def median_defense(self, precision: int = 2) -> float:
    '''
    Computes the median card defense within this card list.

    Tip: Warning
      Cards with variable or no defense are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The median defense value of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.defense for x in self.data if isinstance(x.defense, int)]
    if array:
        return round(median(array), precision)
    else:
        return 0.0

median_health(precision=2)

Computes the median card health within this card list.

Warning

Cards with variable or no health are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The median health of cards in the list.

Source code in fab/card.py
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
def median_health(self, precision: int = 2) -> float:
    '''
    Computes the median card health within this card list.

    Tip: Warning
      Cards with variable or no health are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The median health of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.health for x in self if isinstance(x.health, int)]
    if array:
        return round(median(array), precision)
    else:
        return 0.0

median_intelligence(precision=2)

Computes the median card intelligence within this card list.

Warning

Cards with variable or no intelligence are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The median intelligence of cards in the list.

Source code in fab/card.py
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
def median_intelligence(self, precision: int = 2) -> float:
    '''
    Computes the median card intelligence within this card list.

    Tip: Warning
      Cards with variable or no intelligence are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The median intelligence of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
    if array:
        return round(median(array), precision)
    else:
        return 0.0

median_pitch(precision=2)

Computes the median card pitch within this card list.

Warning

Cards with variable or no pitch are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The median pitch vlaue of cards in the list.

Source code in fab/card.py
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
def median_pitch(self, precision: int = 2) -> float:
    '''
    Computes the median card pitch within this card list.

    Tip: Warning
      Cards with variable or no pitch are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The median pitch vlaue of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
    if array:
        return round(median(array), precision)
    else:
        return 0.0

median_power(precision=2)

Computes the median card power within this card list.

Warning

Cards with variable or no power are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The median attack power of cards in the list.

Source code in fab/card.py
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
def median_power(self, precision: int = 2) -> float:
    '''
    Computes the median card power within this card list.

    Tip: Warning
      Cards with variable or no power are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The median attack power of cards in the list.
    '''
    if len(self.data) < 1: return 0.0
    array = [x.power for x in self.data if isinstance(x.power, int)]
    if array:
        return round(median(array), precision)
    else:
        return 0.0

merge(*args, unique=False) staticmethod

Merges two or more card lists into a single one.

Parameters:

Name Type Description Default
*args CardList

The CardList objects to merge.

()
unique bool

Whether duplicate Card objects should be deleted.

False

Returns:

Type Description
CardList

The merged collection of cards.

Source code in fab/card.py
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
@staticmethod
def merge(*args: CardList, unique: bool = False) -> CardList:
    '''
    Merges two or more card lists into a single one.

    Args:
      *args: The `CardList` objects to merge.
      unique: Whether duplicate `Card` objects should be deleted.

    Returns:
      The merged collection of cards.
    '''
    merged = []
    for card_list in args:
        if card_list is None: continue
        for card in card_list:
            if unique and not card in merged:
                merged.append(card)
            elif not unique:
                merged.append(card)
    return CardList(merged)

min_cost()

Computes the minimum card cost within this card list.

Warning

Cards with variable or no cost are ignored.

Returns:

Type Description
int

The minimum card cost within the list.

Source code in fab/card.py
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
def min_cost(self) -> int:
    '''
    Computes the minimum card cost within this card list.

    Tip: Warning
      Cards with variable or no cost are ignored.

    Returns:
      The minimum card cost within the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.cost for x in self.data if isinstance(x.cost, int)]
    if array:
        return min(array)
    else:
        return 0

min_defense()

Computes the minimum card defense within this card list.

Warning

Cards with variable or no defense are ignored.

Returns:

Type Description
int

The minimum card defense value within the list.

Source code in fab/card.py
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
def min_defense(self) -> int:
    '''
    Computes the minimum card defense within this card list.

    Tip: Warning
      Cards with variable or no defense are ignored.

    Returns:
      The minimum card defense value within the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.defense for x in self.data if isinstance(x.defense, int)]
    if array:
        return min(array)
    else:
        return 0

min_health()

Computes the minimum card health within this card list.

Warning

Cards with variable or no health are ignored.

Returns:

Type Description
int

The minimum card health in the list.

Source code in fab/card.py
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
def min_health(self) -> int:
    '''
    Computes the minimum card health within this card list.

    Tip: Warning
      Cards with variable or no health are ignored.

    Returns:
      The minimum card health in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.health for x in self.data if isinstance(x.health, int)]
    if array:
        return min(array)
    else:
        return 0

min_intelligence()

Computes the minimum card intelligence within this card list.

Warning

Cards with variable or no intelligence are ignored.

Returns:

Type Description
int

The minimum intelligence in the list.

Source code in fab/card.py
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
def min_intelligence(self) -> int:
    '''
    Computes the minimum card intelligence within this card list.

    Tip: Warning
      Cards with variable or no intelligence are ignored.

    Returns:
      The minimum intelligence in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
    if array:
        return min(array)
    else:
        return 0

min_pitch()

Computes the minimum card pitch within this card list.

Warning

Cards with variable or no pitch are ignored.

Returns:

Type Description
int

The minimum pitch value in the list.

Source code in fab/card.py
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
def min_pitch(self) -> int:
    '''
    Computes the minimum card pitch within this card list.

    Tip: Warning
      Cards with variable or no pitch are ignored.

    Returns:
      The minimum pitch value in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
    if array:
        return min(array)
    else:
        return 0

min_power()

Computes the minimum card power within this card list.

Warning

Cards with variable or no power are ignored.

Returns:

Type Description
int

The minimum attack power in the list.

Source code in fab/card.py
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
def min_power(self) -> int:
    '''
    Computes the minimum card power within this card list.

    Tip: Warning
      Cards with variable or no power are ignored.

    Returns:
      The minimum attack power in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.power for x in self.data if isinstance(x.power, int)]
    if array:
        return min(array)
    else:
        return 0

names()

Returns the set of all card names in this card list.

Returns:

Type Description
list[str]

The unique list of card names within the list of cards.

Source code in fab/card.py
1799
1800
1801
1802
1803
1804
1805
1806
def names(self) -> list[str]:
    '''
    Returns the set of all card names in this card list.

    Returns:
      The unique `list` of card names within the list of cards.
    '''
    return sorted(list(set([card.name for card in self.data])))

num_blue()

Returns the number of "blue" cards (pitch 3) in this card list.

Returns:

Type Description
int

The number of cards in this card list that pitch for 3 resources.

Source code in fab/card.py
1808
1809
1810
1811
1812
1813
1814
1815
def num_blue(self) -> int:
    '''
    Returns the number of "blue" cards (pitch 3) in this card list.

    Returns:
      The number of cards in this card list that pitch for 3 resources.
    '''
    return len(self.filter(pitch=3))

num_red()

Returns the number of "red" cards (pitch 1) in this card list.

Returns:

Type Description
int

The number of cards in this card list that pitch for 1 resource.

Source code in fab/card.py
1817
1818
1819
1820
1821
1822
1823
1824
def num_red(self) -> int:
    '''
    Returns the number of "red" cards (pitch 1) in this card list.

    Returns:
      The number of cards in this card list that pitch for 1 resource.
    '''
    return len(self.filter(pitch=1))

num_yellow()

Returns the number of "yellow" cards (pitch 2) in this card list.

Returns:

Type Description
int

The number of cards in this card list that pitch for 2 resources.

Source code in fab/card.py
1826
1827
1828
1829
1830
1831
1832
1833
def num_yellow(self) -> int:
    '''
    Returns the number of "yellow" cards (pitch 2) in this card list.

    Returns:
      The number of cards in this card list that pitch for 2 resources.
    '''
    return len(self.filter(pitch=2))

pitch_cost_difference()

Returns the difference between the pitch and cost values of all cards.

Note

A positive integer indicates that on average one generates more pitch value than consumes it.

Warning

This calculation does not take into effect any additional pitch/cost a card might incur in its body text.

Returns:

Type Description
int

The pitch-cost difference of the list of cards.

Source code in fab/card.py
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
def pitch_cost_difference(self) -> int:
    '''
    Returns the difference between the pitch and cost values of all cards.

    Note:
      A positive integer indicates that on average one generates more pitch
      value than consumes it.

    Tip: Warning
      This calculation does not take into effect any additional pitch/cost a
      card might incur in its body text.

    Returns:
      The pitch-cost difference of the list of cards.
    '''
    return self.total_pitch() - self.total_cost()

pitch_values()

Returns the set of all card pitch values associated with this list of cards.

Warning

This excludes cards with no pitch or with variable pitch.

Returns:

Type Description
list[int]

The unique list of card pitch values within the list of cards.

Source code in fab/card.py
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
def pitch_values(self) -> list[int]:
    '''
    Returns the set of all card pitch values associated with this list of
    cards.

    Tip: Warning
      This excludes cards with no pitch or with variable pitch.

    Returns:
      The unique `list` of card pitch values within the list of cards.
    '''
    res = []
    for card in self.data:
        if isinstance(card.pitch, int): res.append(card.pitch)
    return sorted(list(set(res)))

power_defense_difference()

Returns the difference between the power and defense values of all cards.

Note

A positive integer indicates the deck prefers an offensive strategy.

Warning

This calculation does not take into effect any additional power/defense a card might incur in its body text.

Returns:

Type Description
int

The power-defense difference of the list of cards.

Source code in fab/card.py
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
def power_defense_difference(self) -> int:
    '''
    Returns the difference between the power and defense values of all
    cards.

    Note:
      A positive integer indicates the deck prefers an offensive strategy.

    Tip: Warning
      This calculation does not take into effect any additional power/defense
      a card might incur in its body text.

    Returns:
      The power-defense difference of the list of cards.
    '''
    return self.total_power() - self.total_defense()

power_values()

Returns the set of all card power values associated with this list of cards.

Warning

This excludes cards with no power or with variable power.

Returns:

Type Description
list[int]

The unique list of power values within the list of cards.

Source code in fab/card.py
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
def power_values(self) -> list[int]:
    '''
    Returns the set of all card power values associated with this list of
    cards.

    Tip: Warning
      This excludes cards with no power or with variable power.

    Returns:
      The unique `list` of power values within the list of cards.
    '''
    res = []
    for card in self.data:
        if isinstance(card.power, int): res.append(card.power)
    return sorted(list(set(res)))

rarities()

Returns the set of all card rarities in this card list.

Returns:

Type Description
list[str]

A unique list of card rarities in the list of cards.

Source code in fab/card.py
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
def rarities(self) -> list[str]:
    '''
    Returns the set of all card rarities in this card list.

    Returns:
      A unique `list` of card rarities in the list of cards.
    '''
    res = []
    for card in self.data:
        res.extend(card.rarities)
    return sorted(list(set(res)))

reactions()

Returns the set of all attack and defense reaction cards in this card list.

Returns:

Type Description
CardList

A list of all attack and defense reaction cards within the card list.

Source code in fab/card.py
1974
1975
1976
1977
1978
1979
1980
1981
1982
def reactions(self) -> CardList:
    '''
    Returns the set of all attack and defense reaction cards in this card
    list.

    Returns:
      A list of all attack and defense reaction cards within the card list.
    '''
    return CardList([card for card in self.data if card.is_reaction()])

save(file_path)

Saves the list of cards to the specified file path.

Parameters:

Name Type Description Default
file_path str

The file path to save to.

required
Source code in fab/card.py
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
def save(self, file_path: str):
    '''
    Saves the list of cards to the specified file path.

    Args:
      file_path: The file path to save to.
    '''
    with open(os.path.expanduser(file_path), 'w') as f:
        if file_path.endswith('.json'):
            f.write(self.to_json())
        else:
            raise Exception('specified file path is not a JSON file')

sets()

Returns the set of all card sets in this list.

Returns:

Type Description
list[str]

A unique list of all card sets within the list of cards.

Source code in fab/card.py
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
def sets(self) -> list[str]:
    '''
    Returns the set of all card sets in this list.

    Returns:
      A unique `list` of all card sets within the list of cards.
    '''
    card_sets = []
    for card in self.data:
        card_sets.extend(card.sets)
    return sorted(list(set(card_sets)))

shuffle()

Shuffles this list of cards in-place.

Source code in fab/card.py
1996
1997
1998
1999
2000
def shuffle(self) -> None:
    '''
    Shuffles this list of cards in-place.
    '''
    random.shuffle(self.data)

sort(key='name', reverse=False)

Sorts the list of cards, returning a new sorted collection.

The key parameter may be:

  • A function/lambda on each card.
  • A string corresponding to the field to sort by (for example: type_text). Any None values will be shifted to the beginning of the resulting CardList, or at the end if reverse is equal to True. Note that when specifying grants, keywords, tags or types, the ordering is based on the number of values within those lists. rarities is a special case where cards are sorted by their highest/lowest rarity value. identifiers and sets are sorted by their first element.

Parameters:

Name Type Description Default
key Any

The Card field to sort by.

'name'
reverse bool

Whether to reverse the sort order.

False

Returns:

Type Description
CardList

A new, sorted CardList object.

Source code in fab/card.py
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
def sort(self, key: Any = 'name', reverse: bool = False) -> CardList:
    '''
    Sorts the list of cards, returning a new sorted collection.

    The `key` parameter may be:

    * A function/lambda on each card.
    * A string corresponding to the field to sort by (for example:
      `type_text`). Any `None` values will be shifted to the beginning of
      the resulting `CardList`, or at the end if `reverse` is equal to
      `True`. Note that when specifying `grants`, `keywords`, `tags` or
      `types`, the ordering is based on the _number_ of values within
      those lists. `rarities` is a special case where cards are sorted by
      their highest/lowest rarity value. `identifiers` and `sets` are
      sorted by their first element.

    Args:
      key: The `Card` field to sort by.
      reverse: Whether to reverse the sort order.

    Returns:
      A new, sorted `CardList` object.
    '''
    if isinstance(key, str):
        contains_none = []
        to_sort = []
        for card in self.data:
            if card[key] is None:
                contains_none.append(copy.deepcopy(card))
            elif isinstance(card[key], str) and key in ['cost', 'defense', 'health', 'intelligence', 'pitch', 'power']:
                contains_none.append(copy.deepcopy(card))
            else:
                to_sort.append(copy.deepcopy(card))
        if key in ['identifiers', 'sets']:
            sorted_part = sorted(to_sort, key = lambda x: x[key][0], reverse = reverse)
        elif key in ['grants', 'keywords', 'tags', 'types']:
            sorted_part = sorted(to_sort, key = lambda x: len(x[key]), reverse = reverse)
        elif key == 'rarities':
            sorted_part = sorted(to_sort, key = lambda x: sorted(RARITY_VALUE[y] for y in x[key])[-1] if x[key] else -1, reverse = reverse)
        else:
            sorted_part = sorted(to_sort, key = lambda x: x[key], reverse = reverse)
        if reverse:
            return CardList(sorted_part + contains_none)
        else:
            return CardList(contains_none + sorted_part)
    else:
        return CardList(sorted(copy.deepcopy(self.data), key = key, reverse = reverse))

statistics(precision=2)

Computes helpful statistics associated with this collection of cards.

Note

See the source of this method to get an idea of what the output dict looks like.

Warning

Cards with variable or no value for certain fields will be excluded from that field's calculations.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places any float result will be rounded to.

2

Returns:

Type Description
dict[str, int | float]

A dict containing the results of various statistical functions.

Source code in fab/card.py
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
def statistics(self, precision: int = 2) -> dict[str, int | float]:
    '''
    Computes helpful statistics associated with this collection of cards.

    Note:
      See the source of this method to get an idea of what the output `dict`
      looks like.

    Tip: Warning
      Cards with variable or no value for certain fields will be excluded
      from that field's calculations.

    Args:
      precision: Specifies the number of decimal places any `float` result will be rounded to.

    Returns:
      A `dict` containing the results of various statistical functions.
    '''
    return {
        'count': len(self.data),
        'max_cost': self.max_cost(),
        'max_defense': self.max_defense(),
        'max_health': self.max_health(),
        'max_intelligence': self.max_intelligence(),
        'max_pitch': self.max_pitch(),
        'max_power': self.max_power(),
        'mean_cost': self.mean_cost(precision),
        'mean_defense': self.mean_defense(precision),
        'mean_health': self.mean_health(precision),
        'mean_intelligence': self.mean_intelligence(precision),
        'mean_pitch': self.mean_pitch(precision),
        'mean_power': self.mean_power(precision),
        'median_cost': self.median_cost(precision),
        'median_defense': self.median_defense(precision),
        'median_health': self.median_health(precision),
        'median_intelligence': self.median_intelligence(precision),
        'median_pitch': self.median_pitch(precision),
        'median_power': self.median_power(precision),
        'min_cost': self.min_cost(),
        'min_defense': self.min_defense(),
        'min_health': self.min_health(),
        'min_intelligence': self.min_intelligence(),
        'min_pitch': self.min_pitch(),
        'min_power': self.min_power(),
        'num_blue': self.num_blue(),
        'num_red': self.num_red(),
        'num_yellow': self.num_yellow(),
        'pitch_cost_difference': self.pitch_cost_difference(),
        'power_defense_difference': self.power_defense_difference(),
        'stdev_cost': self.stdev_cost(precision),
        'stdev_defense': self.stdev_defense(precision),
        'stdev_health': self.stdev_health(precision),
        'stdev_intelligence': self.stdev_intelligence(precision),
        'stdev_pitch': self.stdev_pitch(precision),
        'stdev_power': self.stdev_power(precision),
        'total_cost': self.total_cost(),
        'total_defense': self.total_defense(),
        'total_health': self.total_health(),
        'total_intelligence': self.total_intelligence(),
        'total_pitch': self.total_pitch(),
        'total_power': self.total_power(),
    }

stdev_cost(precision=2)

Computes the standard deviation of card cost within this card list.

Warning

Cards with variable or no cost are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The standard deviation of card cost in the list.

Source code in fab/card.py
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
def stdev_cost(self, precision: int = 2) -> float:
    '''
    Computes the standard deviation of card cost within this card list.

    Tip: Warning
      Cards with variable or no cost are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The standard deviation of card cost in the list.
    '''
    if len(self.data) < 2: return 0.0
    array = [x.cost for x in self.data if isinstance(x.cost, int)]
    if len(array) >= 2:
        return round(stdev(array), precision)
    else:
        return 0.0

stdev_defense(precision=2)

Computes the standard deviation of card defense within this card list.

Warning

Cards with variable or no defense are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The standard deviation of card defense in the list.

Source code in fab/card.py
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
def stdev_defense(self, precision: int = 2) -> float:
    '''
    Computes the standard deviation of card defense within this card list.

    Tip: Warning
      Cards with variable or no defense are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The standard deviation of card defense in the list.
    '''
    if len(self.data) < 2: return 0.0
    array = [x.defense for x in self.data if isinstance(x.defense, int)]
    if len(array) >= 2:
        return round(stdev(array), precision)
    else:
        return 0.0

stdev_health(precision=2)

Computes the standard deviation of card health within this card list.

Warning

Cards with variable or no health are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The standard deviation of health in the list.

Source code in fab/card.py
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
def stdev_health(self, precision: int = 2) -> float:
    '''
    Computes the standard deviation of card health within this card list.

    Tip: Warning
      Cards with variable or no health are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The standard deviation of health in the list.
    '''
    if len(self.data) < 2: return 0.0
    array = [x.health for x in self.data if isinstance(x.health, int)]
    if len(array) >= 2:
        return round(stdev(array), precision)
    else:
        return 0.0

stdev_intelligence(precision=2)

Computes the standard deviation of card intelligence within this card list.

Warning

Cards with variable or no intelligence are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The standard deviation of intelligence in the list.

Source code in fab/card.py
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
def stdev_intelligence(self, precision: int = 2) -> float:
    '''
    Computes the standard deviation of card intelligence within this card list.

    Tip: Warning
      Cards with variable or no intelligence are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The standard deviation of intelligence in the list.
    '''
    if len(self.data) < 2: return 0.0
    array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
    if len(array) >= 2:
        return round(stdev(array), precision)
    else:
        return 0.0

stdev_pitch(precision=2)

Computes the standard deviation of card pitch within this card list.

Warning

Cards with variable or no pitch are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The standard deviation of pitch value in the list.

Source code in fab/card.py
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
def stdev_pitch(self, precision: int = 2) -> float:
    '''
    Computes the standard deviation of card pitch within this card list.

    Tip: Warning
      Cards with variable or no pitch are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The standard deviation of pitch value in the list.
    '''
    if len(self.data) < 2: return 0.0
    array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
    if len(array) >= 2:
        return round(stdev(array), precision)
    else:
        return 0.0

stdev_power(precision=2)

Computes the standard deviation of card power within this card list.

Warning

Cards with variable or no power are ignored.

Parameters:

Name Type Description Default
precision int

Specifies the number of decimal places the result will be rounded to.

2

Returns:

Type Description
float

The standard deviation of attack power in the list.

Source code in fab/card.py
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
def stdev_power(self, precision: int = 2) -> float:
    '''
    Computes the standard deviation of card power within this card list.

    Tip: Warning
      Cards with variable or no power are ignored.

    Args:
      precision: Specifies the number of decimal places the result will be rounded to.

    Returns:
      The standard deviation of attack power in the list.
    '''
    if len(self.data) < 2: return 0.0
    array = [x.power for x in self.data if isinstance(x.power, int)]
    if len(array) >= 2:
        return round(stdev(array), precision)
    else:
        return 0.0

to_dataframe()

Converts the list of cards into a pandas DataFrame.

Returns:

Type Description
DataFrame

A pandas DataFrame object representing the list of cards.

Source code in fab/card.py
2185
2186
2187
2188
2189
2190
2191
2192
def to_dataframe(self) -> DataFrame:
    '''
    Converts the list of cards into a [pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html).

    Returns:
      A pandas `DataFrame` object representing the list of cards.
    '''
    return DataFrame(self.data)

to_json()

Converts the list of cards to a JSON string representation.

Returns:

Type Description
str

A JSON string representation of the list of cards.

Source code in fab/card.py
2194
2195
2196
2197
2198
2199
2200
2201
def to_json(self) -> str:
    '''
    Converts the list of cards to a JSON string representation.

    Returns:
      A JSON string representation of the list of cards.
    '''
    return json.dumps(self.to_list(), indent=JSON_INDENT)

to_list()

Converts the list of cards into a raw Python list with nested dictionaries.

Returns:

Type Description
list[dict[str, Any]]

A list of dict objects containing only Python primitives.

Source code in fab/card.py
2203
2204
2205
2206
2207
2208
2209
2210
2211
def to_list(self) -> list[dict[str, Any]]:
    '''
    Converts the list of cards into a raw Python list with nested
    dictionaries.

    Returns:
      A `list` of `dict` objects containing only Python primitives.
    '''
    return [card.to_dict() for card in self.data]

tokens()

Returns the set of all token cards in this card list.

Returns:

Type Description
CardList

The set of token cards in the list.

Source code in fab/card.py
2213
2214
2215
2216
2217
2218
2219
2220
def tokens(self) -> CardList:
    '''
    Returns the set of all token cards in this card list.

    Returns:
      The set of token cards in the list.
    '''
    return CardList([card for card in self.data if card.is_token()])

total_cost()

Computes the total card cost within this card list.

Warning

Cards with variable or no cost are ignored.

Returns:

Type Description
int

The total cost of all cards in the list.

Source code in fab/card.py
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
def total_cost(self) -> int:
    '''
    Computes the total card cost within this card list.

    Tip: Warning
      Cards with variable or no cost are ignored.

    Returns:
      The total cost of all cards in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.cost for x in self.data if isinstance(x.cost, int)]
    if array:
        return sum(array)
    else:
        return 0

total_defense()

Computes the total card defense within this card list.

Warning

Cards with variable or no defense are ignored.

Returns:

Type Description
int

The total defense of all cards in the list.

Source code in fab/card.py
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
def total_defense(self) -> int:
    '''
    Computes the total card defense within this card list.

    Tip: Warning
      Cards with variable or no defense are ignored.

    Returns:
      The total defense of all cards in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.defense for x in self.data if isinstance(x.defense, int)]
    if array:
        return sum(array)
    else:
        return 0

total_health()

Computes the total card health within this card list.

Warning

Cards with variable or no health are ignored.

Returns:

Type Description
int

The total health of all cards in the list.

Source code in fab/card.py
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
def total_health(self) -> int:
    '''
    Computes the total card health within this card list.

    Tip: Warning
      Cards with variable or no health are ignored.

    Returns:
      The total health of all cards in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.health for x in self.data if isinstance(x.health, int)]
    if array:
        return sum(array)
    else:
        return 0

total_intelligence()

Computes the total card intelligence within this card list.

Warning

Cards with variable or no intelligence are ignored.

Returns:

Type Description
int

The total intelligence of all cards in the list.

Source code in fab/card.py
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
def total_intelligence(self) -> int:
    '''
    Computes the total card intelligence within this card list.

    Tip: Warning
      Cards with variable or no intelligence are ignored.

    Returns:
      The total intelligence of all cards in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.intelligence for x in self.data if isinstance(x.intelligence, int)]
    if array:
        return sum(array)
    else:
        return 0

total_pitch()

Computes the total card pitch within this card list.

Warning

Cards with variable or no pitch are ignored.

Returns:

Type Description
int

The total pitch value of all cards in the list.

Source code in fab/card.py
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
def total_pitch(self) -> int:
    '''
    Computes the total card pitch within this card list.

    Tip: Warning
      Cards with variable or no pitch are ignored.

    Returns:
      The total pitch value of all cards in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.pitch for x in self.data if isinstance(x.pitch, int)]
    if array:
        return sum(array)
    else:
        return 0

total_power()

Computes the total card power within this card list.

Warning

Cards with variable or no power are ignored.

Returns:

Type Description
int

The total attack power of all cards in the list.

Source code in fab/card.py
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
def total_power(self) -> int:
    '''
    Computes the total card power within this card list.

    Tip: Warning
      Cards with variable or no power are ignored.

    Returns:
      The total attack power of all cards in the list.
    '''
    if len(self.data) < 1: return 0
    array = [x.power for x in self.data if isinstance(x.power, int)]
    if array:
        return sum(array)
    else:
        return 0

type_texts()

Returns the set of all type texts in this card list.

Returns:

Type Description
list[str]

The unique list of all card types in the list.

Source code in fab/card.py
2336
2337
2338
2339
2340
2341
2342
2343
def type_texts(self) -> list[str]:
    '''
    Returns the set of all type texts in this card list.

    Returns:
      The unique `list` of all card types in the list.
    '''
    return sorted(list(set([card.type_text for card in self.data])))

types()

Returns the set of all card types in this card list.

Returns:

Type Description
list[str]

The unique list of all card types in the list.

Source code in fab/card.py
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
def types(self) -> list[str]:
    '''
    Returns the set of all card types in this card list.

    Returns:
      The unique `list` of all card types in the list.
    '''
    res = []
    for card in self.data:
        res.extend(card.types)
    return sorted(list(set(res)))

weapons()

Returns the set of all weapon cards in this card list.

Returns:

Type Description
CardList

The set of all weapon cards in the list.

Source code in fab/card.py
2345
2346
2347
2348
2349
2350
2351
2352
def weapons(self) -> CardList:
    '''
    Returns the set of all weapon cards in this card list.

    Returns:
      The set of all weapon cards in the list.
    '''
    return CardList([card for card in self.data if card.is_weapon()])