Skip to content

Core

docstring_format_checker.core 🔗

Summary

Core docstring checking functionality.

SectionConfig dataclass 🔗

Summary

Configuration for a docstring section.

Source code in src/docstring_format_checker/config.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
@dataclass
class SectionConfig:
    """
    !!! note "Summary"
        Configuration for a docstring section.
    """

    name: str = field(
        metadata={
            "title": "Name",
            "description": "Name of the docstring section.",
        },
    )
    type: Literal["free_text", "list_name", "list_type", "list_name_and_type"] = field(
        metadata={
            "title": "Type",
            "description": "Type of the section content.",
        },
    )
    order: Optional[int] = field(
        default=None,
        metadata={
            "title": "Order",
            "description": "Order of the section in the docstring.",
        },
    )
    admonition: Union[bool, str] = field(
        default=False,
        metadata={
            "title": "Admonition",
            "description": "Admonition style for the section. Can be False (no admonition) or a string specifying the admonition type.",
        },
    )
    prefix: str = field(
        default="",
        metadata={
            "title": "Prefix",
            "description": "Prefix string for the admonition values.",
        },
    )
    required: bool = field(
        default=False,
        metadata={
            "title": "Required",
            "description": "Whether this section is required in the docstring.",
        },
    )
    message: str = field(
        default="",
        metadata={
            "title": "Message",
            "description": "Optional message for validation errors.",
        },
    )

    def __post_init__(self) -> None:
        """
        !!! note "Summary"
            Validate configuration after initialization.
        """
        self._validate_types()
        self._validate_admonition_prefix_combination()

    def _validate_types(self) -> None:
        """
        !!! note "Summary"
            Validate the 'type' field.
        """
        if self.type not in VALID_TYPES:
            raise InvalidTypeValuesError(f"Invalid section type: {self.type}. Valid types: {VALID_TYPES}")

    def _validate_admonition_prefix_combination(self) -> None:
        """
        !!! note "Summary"
            Validate admonition and prefix combination rules.
        """

        if isinstance(self.admonition, bool):
            # Rule: admonition cannot be True (only False or string)
            if self.admonition is True:
                raise ValueError(f"Section '{self.name}': admonition cannot be True, must be False or a string")

            # Rule: if admonition is False, prefix cannot be provided
            if self.admonition is False and self.prefix:
                raise ValueError(f"Section '{self.name}': when admonition=False, prefix cannot be provided")

        elif isinstance(self.admonition, str):
            # Rule: if admonition is a string, prefix must be provided
            if not self.prefix:
                raise ValueError(f"Section '{self.name}': when admonition is a string, prefix must be provided")

        else:
            raise ValueError(
                f"Section '{self.name}': admonition must be a boolean or string, got {type(self.admonition)}"
            )
name class-attribute instance-attribute 🔗
name: str = field(
    metadata={
        "title": "Name",
        "description": "Name of the docstring section.",
    }
)
type class-attribute instance-attribute 🔗
type: Literal[
    "free_text",
    "list_name",
    "list_type",
    "list_name_and_type",
] = field(
    metadata={
        "title": "Type",
        "description": "Type of the section content.",
    }
)
order class-attribute instance-attribute 🔗
order: Optional[int] = field(
    default=None,
    metadata={
        "title": "Order",
        "description": "Order of the section in the docstring.",
    },
)
admonition class-attribute instance-attribute 🔗
admonition: Union[bool, str] = field(
    default=False,
    metadata={
        "title": "Admonition",
        "description": "Admonition style for the section. Can be False (no admonition) or a string specifying the admonition type.",
    },
)
prefix class-attribute instance-attribute 🔗
prefix: str = field(
    default="",
    metadata={
        "title": "Prefix",
        "description": "Prefix string for the admonition values.",
    },
)
required class-attribute instance-attribute 🔗
required: bool = field(
    default=False,
    metadata={
        "title": "Required",
        "description": "Whether this section is required in the docstring.",
    },
)
message class-attribute instance-attribute 🔗
message: str = field(
    default="",
    metadata={
        "title": "Message",
        "description": "Optional message for validation errors.",
    },
)
__post_init__ 🔗
__post_init__() -> None

Summary

Validate configuration after initialization.

Source code in src/docstring_format_checker/config.py
211
212
213
214
215
216
217
def __post_init__(self) -> None:
    """
    !!! note "Summary"
        Validate configuration after initialization.
    """
    self._validate_types()
    self._validate_admonition_prefix_combination()
_validate_types 🔗
_validate_types() -> None

Summary

Validate the 'type' field.

Source code in src/docstring_format_checker/config.py
219
220
221
222
223
224
225
def _validate_types(self) -> None:
    """
    !!! note "Summary"
        Validate the 'type' field.
    """
    if self.type not in VALID_TYPES:
        raise InvalidTypeValuesError(f"Invalid section type: {self.type}. Valid types: {VALID_TYPES}")
_validate_admonition_prefix_combination 🔗
_validate_admonition_prefix_combination() -> None

Summary

Validate admonition and prefix combination rules.

Source code in src/docstring_format_checker/config.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def _validate_admonition_prefix_combination(self) -> None:
    """
    !!! note "Summary"
        Validate admonition and prefix combination rules.
    """

    if isinstance(self.admonition, bool):
        # Rule: admonition cannot be True (only False or string)
        if self.admonition is True:
            raise ValueError(f"Section '{self.name}': admonition cannot be True, must be False or a string")

        # Rule: if admonition is False, prefix cannot be provided
        if self.admonition is False and self.prefix:
            raise ValueError(f"Section '{self.name}': when admonition=False, prefix cannot be provided")

    elif isinstance(self.admonition, str):
        # Rule: if admonition is a string, prefix must be provided
        if not self.prefix:
            raise ValueError(f"Section '{self.name}': when admonition is a string, prefix must be provided")

    else:
        raise ValueError(
            f"Section '{self.name}': admonition must be a boolean or string, got {type(self.admonition)}"
        )
__init__ 🔗
__init__(
    name: str,
    type: Literal[
        "free_text",
        "list_name",
        "list_type",
        "list_name_and_type",
    ],
    order: Optional[int] = None,
    admonition: Union[bool, str] = False,
    prefix: str = "",
    required: bool = False,
    message: str = "",
) -> None

DocstringError 🔗

Bases: Exception

Summary

Exception raised when a docstring validation error occurs.

Source code in src/docstring_format_checker/utils/exceptions.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class DocstringError(Exception):
    """
    !!! note "Summary"
        Exception raised when a docstring validation error occurs.
    """

    def __init__(
        self,
        message: str,
        file_path: str,
        line_number: int,
        item_name: str,
        item_type: str,
    ) -> None:
        """
        !!! note "Summary"
            Initialize a DocstringError.
        """
        self.message: str = message
        self.file_path: str = file_path
        self.line_number: int = line_number
        self.item_name: str = item_name
        self.item_type: str = item_type
        super().__init__(f"Line {line_number}, {item_type} '{item_name}': {message}")
__init__ 🔗
__init__(
    message: str,
    file_path: str,
    line_number: int,
    item_name: str,
    item_type: str,
) -> None

Summary

Initialize a DocstringError.

Source code in src/docstring_format_checker/utils/exceptions.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def __init__(
    self,
    message: str,
    file_path: str,
    line_number: int,
    item_name: str,
    item_type: str,
) -> None:
    """
    !!! note "Summary"
        Initialize a DocstringError.
    """
    self.message: str = message
    self.file_path: str = file_path
    self.line_number: int = line_number
    self.item_name: str = item_name
    self.item_type: str = item_type
    super().__init__(f"Line {line_number}, {item_type} '{item_name}': {message}")
message instance-attribute 🔗
message: str = message
file_path instance-attribute 🔗
file_path: str = file_path
line_number instance-attribute 🔗
line_number: int = line_number
item_name instance-attribute 🔗
item_name: str = item_name
item_type instance-attribute 🔗
item_type: str = item_type

FunctionAndClassDetails 🔗

Bases: NamedTuple

Summary

Details about a function or class found in the AST.

Source code in src/docstring_format_checker/core.py
75
76
77
78
79
80
81
82
83
84
85
class FunctionAndClassDetails(NamedTuple):
    """
    !!! note "Summary"
        Details about a function or class found in the AST.
    """

    item_type: Literal["function", "class", "method"]
    name: str
    node: Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef]
    lineno: int
    parent_class: Optional[str] = None
item_type instance-attribute 🔗
item_type: Literal['function', 'class', 'method']
name instance-attribute 🔗
name: str
node instance-attribute 🔗
node: Union[FunctionDef, AsyncFunctionDef, ClassDef]
lineno instance-attribute 🔗
lineno: int
parent_class class-attribute instance-attribute 🔗
parent_class: Optional[str] = None

DocstringChecker 🔗

Summary

Main class for checking docstring format and completeness.

Source code in src/docstring_format_checker/core.py
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
class DocstringChecker:
    """
    !!! note "Summary"
        Main class for checking docstring format and completeness.
    """

    def __init__(self, config: Config) -> None:
        """
        !!! note "Summary"
            Initialize the docstring checker.

        Params:
            config (Config):
                Configuration object containing global settings and section definitions.
        """
        self.config: Config = config
        self.sections_config: list[SectionConfig] = config.sections
        self.required_sections: list[SectionConfig] = [s for s in config.sections if s.required]
        self.optional_sections: list[SectionConfig] = [s for s in config.sections if not s.required]

    def check_file(self, file_path: Union[str, Path]) -> list[DocstringError]:
        """
        !!! note "Summary"
            Check docstrings in a Python file.

        Params:
            file_path (Union[str, Path]):
                Path to the Python file to check.

        Raises:
            (FileNotFoundError):
                If the file doesn't exist.
            (InvalidFileError):
                If the file is not a Python file.
            (UnicodeError):
                If the file can't be decoded.
            (SyntaxError):
                If the file contains invalid Python syntax.

        Returns:
            (list[DocstringError]):
                List of DocstringError objects for any validation failures.
        """

        file_path = Path(file_path)
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")

        if file_path.suffix != ".py":
            raise InvalidFileError(f"File must be a Python file (.py): {file_path}")

        # Read and parse the file
        try:
            with open(file_path, encoding="utf-8") as f:
                content: str = f.read()
        except UnicodeDecodeError as e:
            raise UnicodeError(f"Cannot decode file {file_path}: {e}") from e

        try:
            tree: ast.Module = ast.parse(content)
        except SyntaxError as e:
            raise SyntaxError(f"Invalid Python syntax in {file_path}: {e}") from e

        # Extract all functions and classes
        items: list[FunctionAndClassDetails] = self._extract_items(tree)

        # Check each item
        errors: list[DocstringError] = []
        for item in items:
            try:
                self._check_single_docstring(item, str(file_path))
            except DocstringError as e:
                errors.append(e)

        return errors

    def _should_exclude_file(self, relative_path: Path, exclude_patterns: list[str]) -> bool:
        """
        !!! note "Summary"
            Check if a file should be excluded based on patterns.

        Params:
            relative_path (Path):
                The relative path of the file to check.
            exclude_patterns (list[str]):
                List of glob patterns to check against.

        Returns:
            (bool):
                True if the file matches any exclusion pattern.
        """
        for pattern in exclude_patterns:
            if fnmatch.fnmatch(str(relative_path), pattern):
                return True
        return False

    def _filter_python_files(
        self,
        python_files: list[Path],
        directory_path: Path,
        exclude_patterns: list[str],
    ) -> list[Path]:
        """
        !!! note "Summary"
            Filter Python files based on exclusion patterns.

        Params:
            python_files (list[Path]):
                List of Python files to filter.
            directory_path (Path):
                The base directory path for relative path calculation.
            exclude_patterns (list[str]):
                List of glob patterns to exclude.

        Returns:
            (list[Path]):
                Filtered list of Python files that don't match exclusion patterns.
        """
        filtered_files: list[Path] = []
        for file_path in python_files:
            relative_path: Path = file_path.relative_to(directory_path)
            if not self._should_exclude_file(relative_path, exclude_patterns):
                filtered_files.append(file_path)
        return filtered_files

    def _check_file_with_error_handling(self, file_path: Path) -> list[DocstringError]:
        """
        !!! note "Summary"
            Check a single file and handle exceptions gracefully.

        Params:
            file_path (Path):
                Path to the file to check.

        Returns:
            (list[DocstringError]):
                List of DocstringError objects found in the file.
        """
        try:
            return self.check_file(file_path)
        except (FileNotFoundError, ValueError, SyntaxError) as e:
            # Create a special error for file-level issues
            error = DocstringError(
                message=str(e),
                file_path=str(file_path),
                line_number=0,
                item_name="",
                item_type="file",
            )
            return [error]

    def check_directory(
        self,
        directory_path: Union[str, Path],
        exclude_patterns: Optional[list[str]] = None,
    ) -> dict[str, list[DocstringError]]:
        """
        !!! note "Summary"
            Check docstrings in all Python files in a directory recursively.

        Params:
            directory_path (Union[str, Path]):
                Path to the directory to check.
            exclude_patterns (Optional[list[str]]):
                List of glob patterns to exclude.

        Raises:
            (FileNotFoundError):
                If the directory doesn't exist.
            (DirectoryNotFoundError):
                If the path is not a directory.

        Returns:
            (dict[str, list[DocstringError]]):
                Dictionary mapping file paths to lists of DocstringError objects.
        """
        directory_path = Path(directory_path)
        if not directory_path.exists():
            raise FileNotFoundError(f"Directory not found: {directory_path}")

        if not directory_path.is_dir():
            raise DirectoryNotFoundError(f"Path is not a directory: {directory_path}")

        python_files: list[Path] = list(directory_path.glob("**/*.py"))

        # Filter out excluded patterns if provided
        if exclude_patterns:
            python_files = self._filter_python_files(python_files, directory_path, exclude_patterns)

        # Check each file and collect results
        results: dict[str, list[DocstringError]] = {}
        for file_path in python_files:
            errors: list[DocstringError] = self._check_file_with_error_handling(file_path)
            if errors:  # Only include files with errors
                results[str(file_path)] = errors

        return results

    def _is_overload_function(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool:
        """
        !!! note "Summary"
            Check if a function definition is decorated with @overload.

        Params:
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function node to check for @overload decorator.

        Returns:
            (bool):
                True if the function has @overload decorator, False otherwise.
        """

        for decorator in node.decorator_list:
            # Handle direct name reference: @overload
            if isinstance(decorator, ast.Name) and decorator.id == "overload":
                return True
            # Handle attribute reference: @typing.overload
            elif isinstance(decorator, ast.Attribute) and decorator.attr == "overload":
                return True
        return False

    def _extract_all_params(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> list[str]:
        """
        !!! note "Summary"
            Extract all parameter names from a function signature.

        ???+ abstract "Details"
            Extract all parameter types including:

            - Positional-only parameters (before `/`)
            - Regular positional parameters
            - Keyword-only parameters (after `*`)
            - Variable positional arguments (`*args`)
            - Variable keyword arguments (`**kwargs`)

            Exclude `self` and `cls` parameters (method context parameters).

        Params:
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function node to extract parameters from.

        Returns:
            (list[str]):
                List of all parameter names in the function signature.

        ???+ example "Examples"

            ```python
            def func(a, b, /, c, *args, d, **kwargs): ...


            # Returns: ['a', 'b', 'c', 'args', 'd', 'kwargs']
            ```
        """
        params: list[str] = []

        # Positional-only parameters (before /)
        for arg in node.args.posonlyargs:
            if arg.arg not in ("self", "cls"):
                params.append(arg.arg)

        # Regular positional parameters
        for arg in node.args.args:
            if arg.arg not in ("self", "cls"):
                params.append(arg.arg)

        # Variable positional arguments (*args)
        if node.args.vararg:
            params.append(node.args.vararg.arg)

        # Keyword-only parameters (after *)
        for arg in node.args.kwonlyargs:
            if arg.arg not in ("self", "cls"):
                params.append(arg.arg)

        # Variable keyword arguments (**kwargs)
        if node.args.kwarg:
            params.append(node.args.kwarg.arg)

        return params

    def _extract_items(self, tree: ast.AST) -> list[FunctionAndClassDetails]:
        """
        !!! note "Summary"
            Extract all functions and classes from the AST.

        Params:
            tree (ast.AST):
                The Abstract Syntax Tree (AST) to extract items from.

        Returns:
            (list[FunctionAndClassDetails]):
                A list of extracted function and class details.
        """

        items: list[FunctionAndClassDetails] = []

        class ItemVisitor(ast.NodeVisitor):
            """
            !!! note "Summary"
                AST visitor to extract function and class definitions
            """

            def __init__(self, checker: DocstringChecker) -> None:
                """
                !!! note "Summary"
                    Initialize the AST visitor.
                """
                self.class_stack: list[str] = []
                self.checker: DocstringChecker = checker

            def visit_ClassDef(self, node: ast.ClassDef) -> None:
                """
                !!! note "Summary"
                    Visit class definition node.
                """
                # Skip private classes unless check_private is enabled
                should_check: bool = self.checker.config.global_config.check_private or not node.name.startswith("_")
                if should_check:
                    items.append(
                        FunctionAndClassDetails(
                            item_type="class",
                            name=node.name,
                            node=node,
                            lineno=node.lineno,
                            parent_class=None,
                        )
                    )

                # Visit methods in this class
                self.class_stack.append(node.name)
                self.generic_visit(node)
                self.class_stack.pop()

            def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
                """
                !!! note "Summary"
                    Visit function definition node.
                """
                self._visit_function(node)

            def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
                """
                !!! note "Summary"
                    Visit async function definition node.
                """
                self._visit_function(node)

            def _visit_function(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> None:
                """
                !!! note "Summary"
                    Visit function definition node (sync or async).
                """

                # Skip private functions unless check_private is enabled
                should_check: bool = self.checker.config.global_config.check_private or not node.name.startswith("_")
                if should_check:
                    # Skip @overload functions - they don't need docstrings
                    if not self.checker._is_overload_function(node):
                        item_type: Literal["function", "method"] = "method" if self.class_stack else "function"
                        parent_class: Optional[str] = self.class_stack[-1] if self.class_stack else None

                        items.append(
                            FunctionAndClassDetails(
                                item_type=item_type,
                                name=node.name,
                                node=node,
                                lineno=node.lineno,
                                parent_class=parent_class,
                            )
                        )

                self.generic_visit(node)

        visitor = ItemVisitor(self)
        visitor.visit(tree)

        return items

    def _is_section_applicable_to_item(
        self,
        section: SectionConfig,
        item: FunctionAndClassDetails,
    ) -> bool:
        """
        !!! note "Summary"
            Check if a section configuration applies to the given item type.

        Params:
            section (SectionConfig):
                The section configuration to check.
            item (FunctionAndClassDetails):
                The function or class to check against.

        Returns:
            (bool):
                True if the section applies to this item type.
        """

        is_function: bool = isinstance(item.node, (ast.FunctionDef, ast.AsyncFunctionDef))

        # Free text sections apply only to functions and methods, not classes
        if section.type == "free_text":
            return is_function

        # List name and type sections have specific rules
        if section.type == "list_name_and_type":
            section_name_lower: str = section.name.lower()

            # Params only apply to functions/methods
            if section_name_lower == "params" and is_function:
                return True

            # Returns only apply to functions/methods
            if section_name_lower in ["returns", "return"] and is_function:
                return True

            return False

        # These sections apply to functions/methods that might have them
        if section.type in ["list_type", "list_name"]:
            return is_function

        return False

    def _get_applicable_required_sections(self, item: FunctionAndClassDetails) -> list[SectionConfig]:
        """
        !!! note "Summary"
            Get all required sections that apply to the given item.

        Params:
            item (FunctionAndClassDetails):
                The function or class to check.

        Returns:
            (list[SectionConfig]):
                List of section configurations that are required and apply to this item.
        """

        # Filter required sections based on item type
        applicable_sections: list[SectionConfig] = []
        for section in self.sections_config:
            if section.required and self._is_section_applicable_to_item(section, item):
                applicable_sections.append(section)
        return applicable_sections

    def _handle_missing_docstring(
        self,
        item: FunctionAndClassDetails,
        file_path: str,
        requires_docstring: bool,
    ) -> None:
        """
        !!! note "Summary"
            Handle the case where a docstring is missing.

        Params:
            item (FunctionAndClassDetails):
                The function or class without a docstring.
            file_path (str):
                The path to the file containing the item.
            requires_docstring (bool):
                Whether a docstring is required for this item.

        Raises:
            DocstringError: If docstring is required but missing.
        """

        # Raise error if docstring is required
        if requires_docstring and self.config.global_config.require_docstrings:
            message: str = f"Missing docstring for {item.item_type}"
            raise DocstringError(
                message=message,
                file_path=file_path,
                line_number=item.lineno,
                item_name=item.name,
                item_type=item.item_type,
            )

    def _check_single_docstring(self, item: FunctionAndClassDetails, file_path: str) -> None:
        """
        !!! note "Summary"
            Check a single function or class docstring.

        Params:
            item (FunctionAndClassDetails):
                The function or class to check.
            file_path (str):
                The path to the file containing the item.

        Returns:
            (None):
                Nothing is returned.
        """

        docstring: Optional[str] = ast.get_docstring(item.node)

        # Determine which required sections apply to this item type
        applicable_sections: list[SectionConfig] = self._get_applicable_required_sections(item)
        requires_docstring: bool = len(applicable_sections) > 0

        # Only require docstrings if the global flag is enabled
        if not docstring:
            self._handle_missing_docstring(item, file_path, requires_docstring)
            return  # No docstring required or docstring requirement disabled

        # Validate docstring sections if docstring exists
        self._validate_docstring_sections(docstring, item, file_path)

    def _validate_docstring_sections(
        self,
        docstring: str,
        item: FunctionAndClassDetails,
        file_path: str,
    ) -> None:
        """
        !!! note "Summary"
            Validate the sections within a docstring.

        Params:
            docstring (str):
                The docstring to validate.
            item (FunctionAndClassDetails):
                The function or class to check.
            file_path (str):
                The path to the file containing the item.

        Returns:
            (None):
                Nothing is returned.
        """

        errors: list[str] = []

        # Validate required sections are present
        required_section_errors: list[str] = self._validate_all_required_sections(docstring, item)
        errors.extend(required_section_errors)

        # Validate all existing sections (required or not)
        existing_section_errors: list[str] = self._validate_all_existing_sections(docstring, item)
        errors.extend(existing_section_errors)

        # Perform comprehensive validation checks
        comprehensive_errors: list[str] = self._perform_comprehensive_validation(docstring)
        errors.extend(comprehensive_errors)

        # Report errors if found
        if errors:
            combined_message: str = "; ".join(errors)
            raise DocstringError(
                message=combined_message,
                file_path=file_path,
                line_number=item.lineno,
                item_name=item.name,
                item_type=item.item_type,
            )

    def _is_params_section_required(self, item: FunctionAndClassDetails) -> bool:
        """
        !!! note "Summary"
            Check if params section is required for this item.

        Params:
            item (FunctionAndClassDetails):
                The function or class details.

        Returns:
            (bool):
                True if params section is required, False otherwise.
        """

        # For classes, params section not required (attributes handled differently)
        if isinstance(item.node, ast.ClassDef):
            return False

        # For functions, only required if function has parameters (excluding self/cls)
        # item.node is guaranteed to be FunctionDef or AsyncFunctionDef due to type constraints
        params = self._extract_all_params(item.node)
        return len(params) > 0

    def _validate_all_required_sections(self, docstring: str, item: FunctionAndClassDetails) -> list[str]:
        """
        !!! note "Summary"
            Validate all required sections are present.

        Params:
            docstring (str):
                The docstring to validate.
            item (FunctionAndClassDetails):
                The function or class details.

        Returns:
            (list[str]):
                List of validation error messages for missing required sections.
        """

        errors: list[str] = []
        for section in self.required_sections:
            # Special handling for params section - only required if function/class has parameters
            if section.name.lower() == "params":
                if not self._is_params_section_required(item):
                    continue

            # Only check if the section exists, don't validate content yet
            if not self._section_exists(docstring, section):
                errors.append(f"Missing required section: '{section.name}'")
        return errors

    def _validate_all_existing_sections(self, docstring: str, item: FunctionAndClassDetails) -> list[str]:
        """
        !!! note "Summary"
            Validate content of all existing sections (required or not).

        Params:
            docstring (str):
                The docstring to validate.
            item (FunctionAndClassDetails):
                The function or class details.

        Returns:
            (list[str]):
                List of validation error messages for invalid section content.
        """

        errors: list[str] = []
        for section in self.config.sections:
            # Only validate if the section actually exists in the docstring
            if self._section_exists(docstring, section):
                section_error = self._validate_single_section_content(docstring, section, item)
                if section_error:
                    errors.append(section_error)
        return errors

    def _section_exists(self, docstring: str, section: SectionConfig) -> bool:
        """
        !!! note "Summary"
            Check if a section exists in the docstring.

        Params:
            docstring (str):
                The docstring to check.
            section (SectionConfig):
                The section configuration.

        Returns:
            (bool):
                `True` if section exists, `False` otherwise.
        """

        section_name: str = section.name.lower()

        # For free text sections, use the existing logic from _check_free_text_section
        if section.type == "free_text":
            return self._check_free_text_section(docstring, section)

        # Check for admonition style sections (for non-free-text types)
        if section.admonition and isinstance(section.admonition, str):
            if section.prefix and isinstance(section.prefix, str):
                # e.g., "!!! note" or "???+ abstract"
                pattern: str = rf"{re.escape(section.prefix)}\s+{re.escape(section.admonition)}"
                if re.search(pattern, docstring, re.IGNORECASE):
                    return True

        # Check for standard sections with colons (e.g., "Params:", "Returns:")
        pattern = rf"^[ \t]*{re.escape(section_name)}:[ \t]*$"
        if re.search(pattern, docstring, re.IGNORECASE | re.MULTILINE):
            return True

        return False

    def _validate_single_section_content(
        self, docstring: str, section: SectionConfig, item: FunctionAndClassDetails
    ) -> Optional[str]:
        """
        !!! note "Summary"
            Validate the content of a single section based on its type.

        Params:
            docstring (str):
                The docstring to validate.
            section (SectionConfig):
                The section configuration to validate against.
            item (FunctionAndClassDetails):
                The function or class details.

        Returns:
            (Optional[str]):
                Error message if validation fails, None otherwise.
        """

        if section.type == "list_name_and_type":
            return self._validate_list_name_and_type_section(docstring, section, item)

        if section.type == "list_name":
            return self._validate_list_name_section(docstring, section)

        # For `section.type in ("free_text", "list_type")`
        # these sections do not need content validation beyond existence
        return None

    def _validate_list_name_and_type_section(
        self, docstring: str, section: SectionConfig, item: FunctionAndClassDetails
    ) -> Optional[str]:
        """
        !!! note "Summary"
            Validate list_name_and_type sections (params, returns).

        Params:
            docstring (str):
                The docstring to validate.
            section (SectionConfig):
                The section configuration.
            item (FunctionAndClassDetails):
                The function or class details.

        Returns:
            (Optional[str]):
                Error message if section is invalid, None otherwise.
        """

        section_name: str = section.name.lower()

        if section_name == "params" and isinstance(item.node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            # Check params section exists and is properly formatted with detailed error reporting
            is_valid, error_message = self._check_params_section_detailed(docstring, item.node)
            if not is_valid:
                return error_message

            # If validate_param_types is enabled, validate type annotations match
            if self.config.global_config.validate_param_types:
                type_error: Optional[str] = self._validate_param_types(docstring, item.node)
                if type_error:
                    return type_error

        # For returns/return sections, no additional validation beyond existence
        # The _section_exists check already verified the section is present

        return None

    def _validate_list_name_section(self, docstring: str, section: SectionConfig) -> Optional[str]:
        """
        !!! note "Summary"
            Validate list_name sections.

        Params:
            docstring (str):
                The docstring to validate.
            section (SectionConfig):
                The section configuration.

        Returns:
            (Optional[str]):
                Error message if section is missing, None otherwise.
        """
        # No additional validation beyond existence
        # The _section_exists check already verified the section is present
        return None

    def _perform_comprehensive_validation(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Perform comprehensive validation checks on docstring.

        Params:
            docstring (str):
                The docstring to validate.

        Returns:
            (list[str]):
                List of validation error messages.
        """

        errors: list[str] = []

        # Check section order
        order_errors: list[str] = self._check_section_order(docstring)
        errors.extend(order_errors)

        # Check for mutual exclusivity (returns vs yields)
        if self._has_both_returns_and_yields(docstring):
            errors.append("Docstring cannot have both Returns and Yields sections")

        # Check for undefined sections (only if not allowed)
        if not self.config.global_config.allow_undefined_sections:
            undefined_errors: list[str] = self._check_undefined_sections(docstring)
            errors.extend(undefined_errors)

        # Perform formatting validation
        formatting_errors: list[str] = self._perform_formatting_validation(docstring)
        errors.extend(formatting_errors)

        return errors

    def _perform_formatting_validation(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Perform formatting validation checks.

        Params:
            docstring (str):
                The docstring to validate.

        Returns:
            (list[str]):
                List of formatting error messages.
        """

        errors: list[str] = []

        # Check admonition values
        admonition_errors: list[str] = self._check_admonition_values(docstring)
        errors.extend(admonition_errors)

        # Check colon usage
        colon_errors: list[str] = self._check_colon_usage(docstring)
        errors.extend(colon_errors)

        # Check title case
        title_case_errors: list[str] = self._check_title_case_sections(docstring)
        errors.extend(title_case_errors)

        # Check parentheses
        parentheses_errors: list[str] = self._check_parentheses_validation(docstring)
        errors.extend(parentheses_errors)

        return errors

    def _check_free_text_section(self, docstring: str, section: SectionConfig) -> bool:
        """
        !!! note "Summary"
            Check if a free text section exists in the docstring.

        Params:
            docstring (str):
                The docstring to check.
            section (SectionConfig):
                The section configuration to validate.

        Returns:
            (bool):
                `True` if the section exists, `False` otherwise.
        """

        # Make the section name part case-insensitive too
        if isinstance(section.admonition, str) and section.admonition and section.prefix:
            # Format like: !!! note "Summary"
            escaped_name: str = re.escape(section.name)
            pattern: str = (
                rf'{re.escape(section.prefix)}\s+{re.escape(section.admonition)}\s+"[^"]*{escaped_name}[^"]*"'
            )
            return bool(re.search(pattern, docstring, re.IGNORECASE))

        # For summary, accept either formal format or simple docstring
        if section.name.lower() in ["summary"]:
            formal_pattern = r'!!! note "Summary"'
            if re.search(formal_pattern, docstring, re.IGNORECASE):
                return True
            # Accept any non-empty docstring as summary
            return len(docstring.strip()) > 0

        # Look for examples section
        elif section.name.lower() in ["examples", "example"]:
            return bool(re.search(r'\?\?\?\+ example "Examples"', docstring, re.IGNORECASE))

        # Default to true for unknown free text sections
        return True

    def _check_params_section(self, docstring: str, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool:
        """
        !!! note "Summary"
            Check if the Params section exists and documents all parameters.

        Params:
            docstring (str):
                The docstring to check.
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function node to check.

        Returns:
            (bool):
                `True` if the section exists and is valid, `False` otherwise.
        """

        # Get function parameters (excluding 'self' for methods)
        params: list[str] = self._extract_all_params(node)

        if not params:
            return True  # No parameters to document

        # Check if Params section exists
        if not re.search(r"Params:", docstring):
            return False

        # Check each parameter is documented
        for param in params:
            param_pattern: str = rf"{re.escape(param)}\s*\([^)]+\):"
            if not re.search(param_pattern, docstring):
                return False

        return True

    def _extract_documented_params(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Extract parameter names from the Params section of a docstring.

        Params:
            docstring (str):
                The docstring to parse.

        Returns:
            (list[str]):
                List of parameter names found in the Params section.
        """
        documented_params: list[str] = []
        param_pattern: str = r"^\s*(\*{0,2}\w+)\s*\([^)]+\):"
        lines: list[str] = docstring.split("\n")
        in_params_section: bool = False

        for line in lines:
            # Check if we've entered the Params section
            if "Params:" in line:
                in_params_section = True
                continue

            # Check if we've left the Params section (next section starts)
            # Match section names (can include spaces) followed by a colon
            if in_params_section and re.match(r"^[ ]{0,4}[A-Z][\w\s]+:", line):
                break

            # Extract parameter name
            if in_params_section:
                match = re.match(param_pattern, line)
                if match:
                    documented_params.append(match.group(1))

        return documented_params

    def _build_param_mismatch_error(self, missing_in_docstring: list[str], extra_in_docstring: list[str]) -> str:
        """
        !!! note "Summary"
            Build detailed error message for parameter mismatches.

        Params:
            missing_in_docstring (list[str]):
                Parameters in signature but not in docstring.
            extra_in_docstring (list[str]):
                Parameters in docstring but not in signature.

        Returns:
            (str):
                Formatted error message.
        """
        error_parts: list[str] = []

        # Create copies to avoid mutating inputs
        missing_copy: list[str] = list(missing_in_docstring)
        extra_copy: list[str] = list(extra_in_docstring)

        # Check for asterisk mismatch
        # We iterate over a copy of missing_copy to allow modification
        for missing in list(missing_copy):
            for extra in list(extra_copy):
                if extra.lstrip("*") == missing:
                    asterisk_count: int = len(extra) - len(extra.lstrip("*"))
                    asterisk_word: str = "asterisk" if asterisk_count == 1 else "asterisks"
                    error_parts.append(
                        f"  - Parameter '{missing}' found in docstring as '{extra}'. Please remove the {asterisk_word}."
                    )
                    missing_copy.remove(missing)
                    extra_copy.remove(extra)
                    break

        if missing_copy:
            missing_str: str = "', '".join(missing_copy)
            error_parts.append(f"  - In signature but not in docstring: '{missing_str}'")

        if extra_copy:
            extra_str: str = "', '".join(extra_copy)
            error_parts.append(f"  - In docstring but not in signature: '{extra_str}'")

        return "Parameter mismatch:\n" + "\n".join(error_parts)

    def _check_params_section_detailed(
        self, docstring: str, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]
    ) -> tuple[bool, Optional[str]]:
        """
        !!! note "Summary"
            Check if the Params section exists and documents all parameters, with detailed error reporting.

        Params:
            docstring (str):
                The docstring to check.
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function node to check.

        Returns:
            (tuple[bool, Optional[str]]):
                Tuple of (is_valid, error_message). If valid, error_message is None.
        """

        # Get function parameters (excluding 'self' and 'cls' for methods)
        signature_params: list[str] = self._extract_all_params(node)

        if not signature_params:
            return (True, None)  # No parameters to document

        # Check if Params section exists
        if not re.search(r"Params:", docstring):
            return (False, "Params section not found in docstring")

        # Extract documented parameters from docstring
        documented_params: list[str] = self._extract_documented_params(docstring)

        # Find parameters in signature but not in docstring
        missing_in_docstring: list[str] = [p for p in signature_params if p not in documented_params]

        # Find parameters in docstring but not in signature
        extra_in_docstring: list[str] = [p for p in documented_params if p not in signature_params]

        # Build detailed error message if there are mismatches
        if missing_in_docstring or extra_in_docstring:
            error_message: str = self._build_param_mismatch_error(missing_in_docstring, extra_in_docstring)
            return (False, error_message)

        return (True, None)

    def _add_arg_types_to_dict(self, args: list[ast.arg], param_types: dict[str, str]) -> None:
        """
        !!! note "Summary"
            Add type annotations from a list of arguments to the parameter types dictionary.

        Params:
            args (list[ast.arg]):
                List of AST argument nodes.
            param_types (dict[str, str]):
                Dictionary to add parameter types to.
        """
        for arg in args:
            if arg.arg not in ("self", "cls") and arg.annotation:
                param_types[arg.arg] = ast.unparse(arg.annotation)

    def _extract_param_types(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> dict[str, str]:
        """
        !!! note "Summary"
            Extract parameter names and their type annotations from function signature.

        Params:
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function AST node.

        Returns:
            (dict[str, str]):
                Dictionary mapping parameter names to their type annotation strings.
        """
        param_types: dict[str, str] = {}

        # Positional-only parameters (before /)
        self._add_arg_types_to_dict(node.args.posonlyargs, param_types)

        # Regular positional parameters
        self._add_arg_types_to_dict(node.args.args, param_types)

        # Variable positional arguments (*args)
        if node.args.vararg and node.args.vararg.annotation:
            param_types[node.args.vararg.arg] = ast.unparse(node.args.vararg.annotation)

        # Keyword-only parameters (after *)
        self._add_arg_types_to_dict(node.args.kwonlyargs, param_types)

        # Variable keyword arguments (**kwargs)
        if node.args.kwarg and node.args.kwarg.annotation:
            param_types[node.args.kwarg.arg] = ast.unparse(node.args.kwarg.annotation)

        return param_types

    def _extract_param_types_from_docstring(self, docstring: str) -> dict[str, str]:
        """
        !!! note "Summary"
            Extract parameter types from the Params section of docstring.

        Params:
            docstring (str):
                The docstring to parse.

        Returns:
            (dict[str, str]):
                Dictionary mapping parameter names to their documented types.
        """
        param_types: dict[str, str] = {}

        # Find the Params section
        if not re.search(r"Params:", docstring):
            return param_types

        # Pattern to match parameter documentation: name (type):
        # Handles variations like:
        # - name (str):
        # - name (Optional[str]):
        # - name (Union[str, int]):
        # - name (list[str]):
        pattern: str = r"^\s*(\w+)\s*\(([^)]+)\)\s*:"

        lines: list[str] = docstring.split("\n")
        in_params_section: bool = False

        for line in lines:
            # Check if we've entered the Params section
            if "Params:" in line:
                in_params_section = True
                continue

            # Check if we've left the Params section (next section starts)
            # Section headers have minimal indentation (0-4 spaces), not deep indentation like param descriptions
            if in_params_section and re.match(r"^[ ]{0,4}[A-Z]\w+:", line):
                break

            # Extract parameter name and type
            if in_params_section:
                match = re.match(pattern, line)
                if match:
                    param_name: str = match.group(1)
                    param_type: str = match.group(2)
                    param_types[param_name] = param_type

        return param_types

    def _normalize_type_string(self, type_str: str) -> str:
        """
        !!! note "Summary"
            Normalize a type string for comparison.

        Params:
            type_str (str):
                The type string to normalize.

        Returns:
            (str):
                Normalized type string.
        """

        # Remove whitespace
        normalized: str = re.sub(r"\s+", "", type_str)

        # Normalize quotes: ast.unparse() uses single quotes but docstrings typically use double quotes
        # Convert all quotes to single quotes for consistent comparison
        normalized = normalized.replace('"', "'")

        # Make case-insensitive for basic types
        # But preserve case for complex types to avoid breaking things like Optional
        return normalized

    def _compare_param_types(
        self, signature_types: dict[str, str], docstring_types: dict[str, str]
    ) -> list[tuple[str, str, str]]:
        """
        !!! note "Summary"
            Compare parameter types from signature and docstring.

        Params:
            signature_types (dict[str, str]):
                Parameter types from function signature.
            docstring_types (dict[str, str]):
                Parameter types from docstring.

        Returns:
            (list[tuple[str, str, str]]):
                List of mismatches as (param_name, signature_type, docstring_type).
        """
        mismatches: list[tuple[str, str, str]] = []

        for param_name, sig_type in signature_types.items():
            # Check if parameter is documented in docstring
            if param_name not in docstring_types:
                # Parameter not documented - this is handled by other validation
                continue

            doc_type: str = docstring_types[param_name]

            # Normalize both types for comparison
            normalized_sig: str = self._normalize_type_string(sig_type)
            normalized_doc: str = self._normalize_type_string(doc_type)

            # Case-insensitive comparison
            if normalized_sig.lower() != normalized_doc.lower():
                mismatches.append((param_name, sig_type, doc_type))

        return mismatches

    def _get_params_with_defaults(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> set[str]:
        """
        !!! note "Summary"
            Get set of parameter names that have default values.

        Params:
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function node to analyse.

        Returns:
            (set[str]):
                Set of parameter names that have default values.
        """
        params_with_defaults: set[str] = set()
        args = node.args

        # Combine positional-only and regular arguments
        all_positional_args = args.posonlyargs + args.args

        # Check defaults for positional arguments
        num_defaults = len(args.defaults)
        if num_defaults > 0:
            # Defaults apply to the last n arguments of the combined list
            num_args = len(all_positional_args)
            for i in range(num_args - num_defaults, num_args):
                arg = all_positional_args[i]
                if arg.arg not in ("self", "cls"):
                    params_with_defaults.add(arg.arg)

        # Keyword-only args with defaults
        for i, arg in enumerate(args.kwonlyargs):
            if args.kw_defaults[i] is not None:
                params_with_defaults.add(arg.arg)

        return params_with_defaults

    def _process_optional_suffix(
        self,
        param_name: str,
        doc_type: str,
        params_with_defaults: set[str],
        optional_style: str,
    ) -> tuple[str, Optional[str]]:
        """
        !!! note "Summary"
            Process the ', optional' suffix based on the optional_style mode.

        Params:
            param_name (str):
                Name of the parameter.
            doc_type (str):
                Docstring type including potential ', optional' suffix.
            params_with_defaults (set[str]):
                Set of parameters that have default values.
            optional_style (str):
                The validation mode: 'silent', 'validate', or 'strict'.

        Returns:
            (tuple[str, Optional[str]]):
                Tuple of (cleaned_type, error_message).
        """
        has_optional_suffix: bool = bool(re.search(r",\s*optional$", doc_type, flags=re.IGNORECASE))
        clean_type: str = re.sub(r",\s*optional$", "", doc_type, flags=re.IGNORECASE).strip()
        error_message: Optional[str] = None

        if optional_style == "validate":
            if has_optional_suffix and param_name not in params_with_defaults:
                error_message = f"Parameter '{param_name}' has ', optional' suffix but no default value in signature"
        elif optional_style == "strict":
            if param_name in params_with_defaults and not has_optional_suffix:
                error_message = (
                    f"Parameter '{param_name}' has default value but missing ', optional' suffix in docstring"
                )
            elif has_optional_suffix and param_name not in params_with_defaults:
                error_message = f"Parameter '{param_name}' has ', optional' suffix but no default value in signature"

        return clean_type, error_message

    def _format_optional_errors(self, errors: list[str]) -> str:
        """
        !!! note "Summary"
            Format multiple optional suffix validation errors.

        Params:
            errors (list[str]):
                List of error messages.

        Returns:
            (str):
                Formatted error message.
        """
        if len(errors) == 1:
            return errors[0]
        formatted_errors: str = "\n  - ".join([""] + errors)
        return f"Optional suffix validation errors:{formatted_errors}"

    def _format_type_mismatches(self, mismatches: list[tuple[str, str, str]]) -> str:
        """
        !!! note "Summary"
            Format parameter type mismatches for error output.

        Params:
            mismatches (list[tuple[str, str, str]]):
                List of (param_name, sig_type, doc_type) tuples.

        Returns:
            (str):
                Formatted error message.
        """
        mismatch_blocks: list[str] = []
        for name, sig_type, doc_type in mismatches:
            sig_type_clean: str = sig_type.replace("'", '"')
            doc_type_clean: str = doc_type.replace("'", '"')
            param_block: str = (
                f"""'{name}':\n    - signature: '{sig_type_clean}'\n    - docstring: '{doc_type_clean}'"""
            )
            mismatch_blocks.append(param_block)

        formatted_details: str = "\n  - ".join([""] + mismatch_blocks)
        return f"Parameter type mismatch:{formatted_details}"

    def _validate_param_types(
        self, docstring: str, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]
    ) -> Optional[str]:
        """
        !!! note "Summary"
            Validate that parameter types in docstring match the signature.

        ???+ abstract "Details"
            Implements three validation modes based on `optional_style` configuration:

            - **`"silent"`**: Strip `, optional` from docstring types before comparison.
            - **`"validate"`**: Error if `, optional` appears on required parameters.
            - **`"strict"`**: Require `, optional` for parameters with defaults, error if on required parameters.

        Params:
            docstring (str):
                The docstring to validate.
            node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
                The function node with type annotations.

        Returns:
            (Optional[str]):
                Error message if validation fails, None otherwise.
        """
        # Extract types from both sources
        signature_types: dict[str, str] = self._extract_param_types(node)
        docstring_types_raw: dict[str, str] = self._extract_param_types_from_docstring(docstring)

        # Get parameters with default values
        params_with_defaults: set[str] = self._get_params_with_defaults(node)

        # Get all parameter names (excluding self/cls)
        all_params: list[str] = self._extract_all_params(node)

        # Get the optional_style mode
        optional_style: str = self.config.global_config.optional_style

        # Process docstring types based on optional_style mode
        docstring_types: dict[str, str] = {}
        optional_errors: list[str] = []

        for param_name, doc_type in docstring_types_raw.items():
            clean_type, error_message = self._process_optional_suffix(
                param_name, doc_type, params_with_defaults, optional_style
            )
            docstring_types[param_name] = clean_type
            if error_message:
                optional_errors.append(error_message)

        # Return optional_style errors first if any
        if optional_errors:
            return self._format_optional_errors(optional_errors)

        # Check for parameters documented with type in docstring but missing annotation in signature
        for param_name in all_params:
            if param_name in docstring_types and param_name not in signature_types:
                return f"Parameter '{param_name}' has type in docstring but no type annotation in signature"

        # Check for parameters with annotations but no type in docstring
        for param_name, sig_type in signature_types.items():
            if param_name not in docstring_types:
                return (
                    f"Parameter '{param_name}' has type annotation '{sig_type}' in signature but no type in docstring"
                )

        # Compare types
        mismatches: list[tuple[str, str, str]] = self._compare_param_types(signature_types, docstring_types)

        if mismatches:
            return self._format_type_mismatches(mismatches)

        return None

    def _has_both_returns_and_yields(self, docstring: str) -> bool:
        """
        !!! note "Summary"
            Check if docstring has both Returns and Yields sections.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (bool):
                `True` if the section exists, `False` otherwise.
        """

        has_returns = bool(re.search(r"Returns:", docstring))
        has_yields = bool(re.search(r"Yields:", docstring))
        return has_returns and has_yields

    def _build_section_patterns(self) -> list[tuple[str, str]]:
        """
        !!! note "Summary"
            Build regex patterns for detecting sections from configuration.

        Returns:
            (list[tuple[str, str]]):
                List of tuples containing (pattern, section_name).
        """
        section_patterns: list[tuple[str, str]] = []
        # Sort sections that have an order, then append those that don't
        ordered_sections = sorted(
            [s for s in self.sections_config if s.order is not None],
            key=lambda x: x.order if x.order is not None else 0,
        )
        unordered_sections: list[SectionConfig] = [s for s in self.sections_config if s.order is None]

        for section in ordered_sections + unordered_sections:
            if (
                section.type == "free_text"
                and isinstance(section.admonition, str)
                and section.admonition
                and section.prefix
            ):
                pattern: str = (
                    rf'{re.escape(section.prefix)}\s+{re.escape(section.admonition)}\s+".*{re.escape(section.name)}"'
                )
                section_patterns.append((pattern, section.name))
            elif section.name.lower() == "params":
                section_patterns.append((r"Params:", "Params"))
            elif section.name.lower() in ["returns", "return"]:
                section_patterns.append((r"Returns:", "Returns"))
            elif section.name.lower() in ["yields", "yield"]:
                section_patterns.append((r"Yields:", "Yields"))
            elif section.name.lower() in ["raises", "raise"]:
                section_patterns.append((r"Raises:", "Raises"))

        # Add default patterns for common sections
        default_patterns: list[tuple[str, str]] = [
            (r'!!! note "Summary"', "Summary"),
            (r'!!! details "Details"', "Details"),
            (r'\?\?\?\+ example "Examples"', "Examples"),
            (r'\?\?\?\+ success "Credit"', "Credit"),
            (r'\?\?\?\+ calculation "Equation"', "Equation"),
            (r'\?\?\?\+ info "Notes"', "Notes"),
            (r'\?\?\? question "References"', "References"),
            (r'\?\?\? tip "See Also"', "See Also"),
        ]

        return section_patterns + default_patterns

    def _find_sections_with_positions(self, docstring: str, patterns: list[tuple[str, str]]) -> list[tuple[int, str]]:
        """
        !!! note "Summary"
            Find all sections in docstring and their positions.

        Params:
            docstring (str):
                The docstring to search.
            patterns (list[tuple[str, str]]):
                List of (pattern, section_name) tuples to search for.

        Returns:
            (list[tuple[int, str]]):
                List of (position, section_name) tuples sorted by position.
        """
        found_sections: list[tuple[int, str]] = []
        for pattern, section_name in patterns:
            match: Optional[re.Match[str]] = re.search(pattern, docstring, re.IGNORECASE)
            if match:
                found_sections.append((match.start(), section_name))

        # Sort by position in docstring
        found_sections.sort(key=lambda x: x[0])
        return found_sections

    def _build_expected_section_order(self) -> list[str]:
        """
        !!! note "Summary"
            Build the expected order of sections from configuration.

        Returns:
            (list[str]):
                List of section names in expected order.
        """
        expected_order: list[str] = [
            s.name.title()
            for s in sorted(
                [s for s in self.sections_config if s.order is not None],
                key=lambda x: x.order if x.order is not None else 0,
            )
        ]
        expected_order.extend(
            [
                "Summary",
                "Details",
                "Examples",
                "Credit",
                "Equation",
                "Notes",
                "References",
                "See Also",
            ]
        )
        return expected_order

    def _check_section_order(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that sections appear in the correct order.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (list[str]):
                A list of error messages, if any.
        """
        # Build patterns and find sections
        patterns = self._build_section_patterns()
        found_sections = self._find_sections_with_positions(docstring, patterns)
        expected_order = self._build_expected_section_order()

        # Check order matches expected order
        errors: list[str] = []
        last_expected_index = -1
        for _, section_name in found_sections:
            try:
                current_index: int = expected_order.index(section_name)
                if current_index < last_expected_index:
                    errors.append(f"Section '{section_name}' appears out of order")
                last_expected_index: int = current_index
            except ValueError:
                # Section not in expected order list - might be OK
                pass

        return errors

    def _normalize_section_name(self, section_name: str) -> str:
        """
        !!! note "Summary"
            Normalize section name by removing colons and whitespace.

        Params:
            section_name (str):
                The raw section name to normalize.

        Returns:
            (str):
                The normalized section name.
        """
        return section_name.lower().strip().rstrip(":")

    def _is_valid_section_name(self, section_name: str) -> bool:
        """
        !!! note "Summary"
            Check if section name is valid.

        !!! abstract "Details"
            Filters out empty names, code block markers, and special characters.

        Params:
            section_name (str):
                The section name to validate.

        Returns:
            (bool):
                True if the section name is valid, False otherwise.
        """
        # Skip empty matches or common docstring content
        if not section_name or section_name in ["", "py", "python", "sh", "shell"]:
            return False

        # Skip code blocks and inline code
        if any(char in section_name for char in ["`", ".", "/", "\\"]):
            return False

        return True

    def _extract_section_names_from_docstring(self, docstring: str) -> set[str]:
        """
        !!! note "Summary"
            Extract all section names found in docstring.

        Params:
            docstring (str):
                The docstring to extract section names from.

        Returns:
            (set[str]):
                A set of normalized section names found in the docstring.
        """
        # Common patterns for different section types
        section_patterns: list[tuple[str, str]] = [
            # Standard sections with colons (but not inside quotes)
            (r"^(\w+):\s*", "colon"),
            # Admonition sections with various prefixes
            (r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\"", "admonition"),
        ]

        found_sections: set[str] = set()

        for pattern, pattern_type in section_patterns:
            matches: Iterator[re.Match[str]] = re.finditer(pattern, docstring, re.IGNORECASE | re.MULTILINE)
            for match in matches:
                section_name: str = self._normalize_section_name(match.group(1))

                if self._is_valid_section_name(section_name):
                    found_sections.add(section_name)

        return found_sections

    def _check_undefined_sections(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check for sections in docstring that are not defined in configuration.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (list[str]):
                A list of error messages for undefined sections.
        """
        errors: list[str] = []

        # Get all configured section names (case-insensitive)
        configured_sections: set[str] = {section.name.lower() for section in self.sections_config}

        # Extract all section names from docstring
        found_sections: set[str] = self._extract_section_names_from_docstring(docstring)

        # Check which found sections are not configured
        for section_name in found_sections:
            if section_name not in configured_sections:
                errors.append(f"Section '{section_name}' found in docstring but not defined in configuration")

        return errors

    def _build_admonition_mapping(self) -> dict[str, str]:
        """
        !!! note "Summary"
            Build mapping of section names to expected admonitions.

        Returns:
            (dict[str, str]):
                Dictionary mapping section name to admonition type.
        """
        section_admonitions: dict[str, str] = {}
        for section in self.sections_config:
            if section.type == "free_text" and isinstance(section.admonition, str) and section.admonition:
                section_admonitions[section.name.lower()] = section.admonition.lower()
        return section_admonitions

    def _validate_single_admonition(self, match: re.Match[str], section_admonitions: dict[str, str]) -> Optional[str]:
        """
        !!! note "Summary"
            Validate a single admonition match against configuration.

        Params:
            match (re.Match[str]):
                The regex match for an admonition section.
            section_admonitions (dict[str, str]):
                Mapping of section names to expected admonitions.

        Returns:
            (Optional[str]):
                Error message if validation fails, None otherwise.
        """
        actual_admonition: str = match.group(1).lower()
        section_title: str = match.group(2)
        section_title_lower: str = section_title.lower()

        # Check if this section is configured with a specific admonition
        if section_title_lower in section_admonitions:
            expected_admonition: str = section_admonitions[section_title_lower]
            if actual_admonition != expected_admonition:
                return (
                    f"Section '{section_title}' has incorrect admonition '{actual_admonition}', "
                    f"expected '{expected_admonition}'"
                )

        # Check if section shouldn't have admonition but does
        section_config: Optional[SectionConfig] = next(
            (s for s in self.sections_config if s.name.lower() == section_title_lower), None
        )
        if section_config and section_config.admonition is False:
            return f"Section '{section_title}' is configured as non-admonition but found as admonition"

        return None

    def _check_admonition_values(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that admonition values in docstring match configuration.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (list[str]):
                A list of error messages for mismatched admonitions.
        """
        errors: list[str] = []

        # Build admonition mapping
        section_admonitions = self._build_admonition_mapping()

        # Pattern to find all admonition sections
        admonition_pattern = r"(?:\?\?\?[+]?|!!!)\s+(\w+)\s+\"([^\"]+)\""
        matches: Iterator[re.Match[str]] = re.finditer(admonition_pattern, docstring, re.IGNORECASE)

        # Validate each admonition
        for match in matches:
            error = self._validate_single_admonition(match, section_admonitions)
            if error:
                errors.append(error)

        return errors

    def _validate_admonition_has_no_colon(self, match: re.Match[str]) -> Optional[str]:
        """
        !!! note "Summary"
            Validate that a single admonition section does not have a colon.

        Params:
            match (re.Match[str]):
                The regex match for an admonition section.

        Returns:
            (Optional[str]):
                An error message if colon found, None otherwise.
        """

        section_title: str = match.group(1)
        has_colon: bool = section_title.endswith(":")
        section_title_clean: str = section_title.rstrip(":")
        section_title_lower: str = section_title_clean.lower()

        # Find config for this section
        section_config: Optional[SectionConfig] = next(
            (s for s in self.sections_config if s.name.lower() == section_title_lower), None
        )

        if section_config and isinstance(section_config.admonition, str) and section_config.admonition:
            if has_colon:
                return (
                    f"Section '{section_title_clean}' is an admonition, therefore it should not end with ':', "
                    f"see: '{match.group(0)}'"
                )

        return None

    def _check_admonition_colon_usage(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that admonition sections don't end with colon.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (list[str]):
                A list of error messages.
        """

        errors: list[str] = []
        admonition_pattern = r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\""
        matches: Iterator[re.Match[str]] = re.finditer(admonition_pattern, docstring, re.IGNORECASE)

        for match in matches:
            error: Optional[str] = self._validate_admonition_has_no_colon(match)
            if error:
                errors.append(error)

        return errors

    def _validate_non_admonition_has_colon(self, line: str, pattern: str) -> Optional[str]:
        """
        !!! note "Summary"
            Validate that a single line has colon if it's a non-admonition section.

        Params:
            line (str):
                The line to check.
            pattern (str):
                The regex pattern to match.

        Returns:
            (Optional[str]):
                An error message if colon missing, None otherwise.
        """

        match: Optional[re.Match[str]] = re.match(pattern, line)
        if not match:
            return None

        section_name: str = match.group(1)
        has_colon: bool = match.group(2) == ":"

        # Find config for this section
        section_config: Optional[SectionConfig] = next(
            (s for s in self.sections_config if s.name.lower() == section_name.lower()), None
        )

        if section_config and section_config.admonition is False:
            if not has_colon:
                return f"Section '{section_name}' is non-admonition, therefore it must end with ':', " f"see: '{line}'"

        return None

    def _check_non_admonition_colon_usage(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that non-admonition sections end with colon.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (list[str]):
                A list of error messages.
        """

        errors: list[str] = []
        non_admonition_pattern = r"^(\w+)(:?)$"

        for line in docstring.split("\n"):
            line: str = line.strip()
            error: Optional[str] = self._validate_non_admonition_has_colon(line, non_admonition_pattern)
            if error:
                errors.append(error)

        return errors

    def _check_colon_usage(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that colons are used correctly for admonition vs non-admonition sections.

        Params:
            docstring (str):
                The docstring to check.

        Returns:
            (list[str]):
                A list of error messages.
        """

        errors: list[str] = []

        # Check admonition sections (should not end with colon)
        errors.extend(self._check_admonition_colon_usage(docstring))

        # Check non-admonition sections (should end with colon)
        errors.extend(self._check_non_admonition_colon_usage(docstring))

        return errors

    def _check_title_case_sections(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that non-admonition sections are single word, title case, and match config name.
        """

        errors: list[str] = []

        # Pattern to find section headers (single word followed by optional colon)
        section_pattern = r"^(\w+):?$"

        for line in docstring.split("\n"):
            line: str = line.strip()
            match: Optional[re.Match[str]] = re.match(section_pattern, line)
            if match:
                section_word: str = match.group(1)
                section_name_lower: str = section_word.lower()

                # Check if this is a configured non-admonition section
                section_config: Optional[SectionConfig] = next(
                    (s for s in self.sections_config if s.name.lower() == section_name_lower), None
                )
                if section_config and section_config.admonition is False:
                    # Check if it's title case
                    expected_title_case: str = section_config.name.title()
                    if section_word != expected_title_case:
                        errors.append(
                            f"Section '{section_name_lower}' must be in title case as '{expected_title_case}', "
                            f"found: '{section_word}'"
                        )

        return errors

    def _check_parentheses_validation(self, docstring: str) -> list[str]:
        """
        !!! note "Summary"
            Check that list_type and list_name_and_type sections have proper parentheses.
        """

        errors: list[str] = []

        # Get sections that require parentheses
        parentheses_sections: list[SectionConfig] = [
            s for s in self.sections_config if s.type in ["list_type", "list_name_and_type"]
        ]

        if not parentheses_sections:
            return errors

        # Process each line in the docstring
        lines: list[str] = docstring.split("\n")
        current_section: Optional[SectionConfig] = None
        type_line_indent: Optional[int] = None

        for line in lines:
            stripped_line: str = line.strip()

            # Check for any section header (to properly transition out of current section)
            section_detected: bool = self._detect_any_section_header(stripped_line, line)
            if section_detected:
                # Check if it's a parentheses-required section
                new_section: Optional[SectionConfig] = self._detect_section_header(
                    stripped_line, line, parentheses_sections
                )
                current_section = new_section  # None if not parentheses-required
                type_line_indent = None
                continue

            # Process content lines within parentheses-required sections
            if current_section and self._is_content_line(stripped_line):
                line_errors: list[str]
                new_indent: Optional[int]
                line_errors, new_indent = self._validate_parentheses_line(
                    line, stripped_line, current_section, type_line_indent
                )
                errors.extend(line_errors)
                if new_indent is not None:
                    type_line_indent = new_indent

        return errors

    def _detect_any_section_header(self, stripped_line: str, full_line: str) -> bool:
        """
        !!! note "Summary"
            Detect any section header (for section transitions).

        Params:
            stripped_line (str):
                The stripped line content.
            full_line (str):
                The full line with indentation.

        Returns:
            (bool):
                True if line is a section header, False otherwise.
        """
        # Admonition sections
        admonition_match: Optional[re.Match[str]] = re.match(
            r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\"", stripped_line, re.IGNORECASE
        )
        if admonition_match:
            section_name: str = admonition_match.group(1)
            # Check if it's a known section
            return any(s.name.lower() == section_name.lower() for s in self.sections_config)

        # Non-admonition sections (must not be indented)
        if not full_line.startswith((" ", "\t")):
            # Match section names (can include spaces) followed by an optional colon
            simple_section_match: Optional[re.Match[str]] = re.match(r"^([A-Z][\w\s]+):?$", stripped_line)
            if simple_section_match:
                section_name: str = simple_section_match.group(1).strip()
                # Check if it's a known section
                return any(s.name.lower() == section_name.lower() for s in self.sections_config)

        return False

    def _detect_section_header(
        self, stripped_line: str, full_line: str, parentheses_sections: list[SectionConfig]
    ) -> Optional[SectionConfig]:
        """
        !!! note "Summary"
            Detect section headers and return matching section config.

        Params:
            stripped_line (str):
                The stripped line content.
            full_line (str):
                The full line with indentation.
            parentheses_sections (list[SectionConfig]):
                List of sections requiring parentheses validation.

        Returns:
            (Optional[SectionConfig]):
                Matching section config or None if not found.
        """
        # Admonition sections
        admonition_match: Optional[re.Match[str]] = re.match(
            r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\"", stripped_line, re.IGNORECASE
        )
        if admonition_match:
            section_name: str = admonition_match.group(1)
            return next((s for s in parentheses_sections if s.name.lower() == section_name.lower()), None)

        # Non-admonition sections (must not be indented)
        if not full_line.startswith((" ", "\t")):
            # Match section names (can include spaces) followed by an optional colon
            simple_section_match: Optional[re.Match[str]] = re.match(r"^([A-Z][\w\s]+):?$", stripped_line)
            if simple_section_match:
                section_name: str = simple_section_match.group(1).strip()
                # Check if it's a known section
                potential_section: Optional[SectionConfig] = next(
                    (s for s in self.sections_config if s.name.lower() == section_name.lower()), None
                )
                if potential_section:
                    return next((s for s in parentheses_sections if s.name.lower() == section_name.lower()), None)

        return None

    def _is_content_line(self, stripped_line: str) -> bool:
        """
        !!! note "Summary"
            Check if line is content that needs validation.

        Params:
            stripped_line (str):
                The stripped line content.

        Returns:
            (bool):
                True if line is content requiring validation, False otherwise.
        """
        return bool(stripped_line) and not stripped_line.startswith(("!", "?", "#")) and ":" in stripped_line

    def _is_description_line(self, stripped_line: str) -> bool:
        """
        !!! note "Summary"
            Check if line is a description rather than a type definition.

        Params:
            stripped_line (str):
                The stripped line content.

        Returns:
            (bool):
                True if line is a description, False otherwise.
        """
        description_prefixes: list[str] = [
            "default:",
            "note:",
            "example:",
            "see:",
            "warning:",
            "info:",
            "tip:",
            "returns:",
        ]

        return (
            any(stripped_line.lower().startswith(prefix) for prefix in description_prefixes)
            or "Default:" in stripped_line
            or "Output format:" in stripped_line
            or "Show examples:" in stripped_line
            or "Example code:" in stripped_line
            or stripped_line.strip().startswith(("-", "*", "•", "+"))
            or stripped_line.startswith(">>>")  # Doctest examples
        )

    def _validate_parentheses_line(
        self, full_line: str, stripped_line: str, current_section: SectionConfig, type_line_indent: Optional[int]
    ) -> tuple[list[str], Optional[int]]:
        """
        !!! note "Summary"
            Validate a single line for parentheses requirements.

        Params:
            full_line (str):
                The full line with indentation.
            stripped_line (str):
                The stripped line content.
            current_section (SectionConfig):
                The current section being validated.
            type_line_indent (Optional[int]):
                The indentation level of type definitions.

        Returns:
            (tuple[list[str], Optional[int]]):
                Tuple of error messages and updated type line indent.
        """
        errors: list[str] = []
        new_indent: Optional[int] = None
        current_indent: int = len(full_line) - len(full_line.lstrip())

        # Skip description lines
        if self._is_description_line(stripped_line):
            return errors, type_line_indent

        if current_section.type == "list_type":
            errors, new_indent = self._validate_list_type_line(
                stripped_line, current_indent, type_line_indent, current_section
            )
        elif current_section.type == "list_name_and_type":
            errors, new_indent = self._validate_list_name_and_type_line(
                stripped_line, current_indent, type_line_indent, current_section
            )

        return errors, new_indent if new_indent is not None else type_line_indent

    def _validate_list_type_line(
        self, stripped_line: str, current_indent: int, type_line_indent: Optional[int], current_section: SectionConfig
    ) -> tuple[list[str], Optional[int]]:
        """
        !!! note "Summary"
            Validate list_type section lines.

        Params:
            stripped_line (str):
                The stripped line content.
            current_indent (int):
                The current line's indentation level.
            type_line_indent (Optional[int]):
                The indentation level of type definitions.
            current_section (SectionConfig):
                The current section being validated.

        Returns:
            (tuple[list[str], Optional[int]]):
                Tuple of error messages and updated type line indent.
        """
        errors: list[str] = []

        # Check for valid type definition format
        if re.search(r"^\s*\([^)]+\):", stripped_line):
            return errors, current_indent

        # Handle lines without proper format
        if type_line_indent is None or current_indent > type_line_indent:
            # Allow as possible description
            return errors, None

        # This should be a type definition but lacks proper format
        errors.append(
            f"Section '{current_section.name}' (type: '{current_section.type}') requires "
            f"parenthesized types, see: '{stripped_line}'"
        )
        return errors, None

    def _validate_list_name_and_type_line(
        self, stripped_line: str, current_indent: int, type_line_indent: Optional[int], current_section: SectionConfig
    ) -> tuple[list[str], Optional[int]]:
        """
        !!! note "Summary"
            Validate list_name_and_type section lines.

        Params:
            stripped_line (str):
                The stripped line content.
            current_indent (int):
                The current line's indentation level.
            type_line_indent (Optional[int]):
                The indentation level of type definitions.
            current_section (SectionConfig):
                The current section being validated.

        Returns:
            (tuple[list[str], Optional[int]]):
                Tuple of error messages and updated type line indent.
        """
        errors: list[str] = []

        # Check for valid parameter definition format
        if re.search(r"\([^)]+\):", stripped_line):
            return errors, current_indent

        # Check if this is likely a description line
        colon_part: str = stripped_line.split(":")[0].strip()

        # Skip description-like content
        if any(word in colon_part.lower() for word in ["default", "output", "format", "show", "example"]):
            return errors, None

        # Skip if more indented than parameter definition (description line)
        if type_line_indent is not None and current_indent > type_line_indent:
            return errors, None

        # Skip if too many words before colon (likely description)
        words_before_colon: list[str] = colon_part.split()
        if len(words_before_colon) > 2:
            return errors, None

        # Flag potential parameter definitions without proper format
        if not stripped_line.strip().startswith("#"):
            errors.append(
                f"Section '{current_section.name}' (type: '{current_section.type}') requires "
                f"parenthesized types, see: '{stripped_line}'"
            )

        return errors, None
__init__ 🔗
__init__(config: Config) -> None

Summary

Initialize the docstring checker.

Parameters:

Name Type Description Default
config Config

Configuration object containing global settings and section definitions.

required
Source code in src/docstring_format_checker/core.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __init__(self, config: Config) -> None:
    """
    !!! note "Summary"
        Initialize the docstring checker.

    Params:
        config (Config):
            Configuration object containing global settings and section definitions.
    """
    self.config: Config = config
    self.sections_config: list[SectionConfig] = config.sections
    self.required_sections: list[SectionConfig] = [s for s in config.sections if s.required]
    self.optional_sections: list[SectionConfig] = [s for s in config.sections if not s.required]
config instance-attribute 🔗
config: Config = config
sections_config instance-attribute 🔗
sections_config: list[SectionConfig] = sections
required_sections instance-attribute 🔗
required_sections: list[SectionConfig] = [
    s for s in (sections) if required
]
optional_sections instance-attribute 🔗
optional_sections: list[SectionConfig] = [
    s for s in (sections) if not required
]
check_file 🔗
check_file(
    file_path: Union[str, Path],
) -> list[DocstringError]

Summary

Check docstrings in a Python file.

Parameters:

Name Type Description Default
file_path Union[str, Path]

Path to the Python file to check.

required

Raises:

Type Description
FileNotFoundError

If the file doesn't exist.

InvalidFileError

If the file is not a Python file.

UnicodeError

If the file can't be decoded.

SyntaxError

If the file contains invalid Python syntax.

Returns:

Type Description
list[DocstringError]

List of DocstringError objects for any validation failures.

Source code in src/docstring_format_checker/core.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def check_file(self, file_path: Union[str, Path]) -> list[DocstringError]:
    """
    !!! note "Summary"
        Check docstrings in a Python file.

    Params:
        file_path (Union[str, Path]):
            Path to the Python file to check.

    Raises:
        (FileNotFoundError):
            If the file doesn't exist.
        (InvalidFileError):
            If the file is not a Python file.
        (UnicodeError):
            If the file can't be decoded.
        (SyntaxError):
            If the file contains invalid Python syntax.

    Returns:
        (list[DocstringError]):
            List of DocstringError objects for any validation failures.
    """

    file_path = Path(file_path)
    if not file_path.exists():
        raise FileNotFoundError(f"File not found: {file_path}")

    if file_path.suffix != ".py":
        raise InvalidFileError(f"File must be a Python file (.py): {file_path}")

    # Read and parse the file
    try:
        with open(file_path, encoding="utf-8") as f:
            content: str = f.read()
    except UnicodeDecodeError as e:
        raise UnicodeError(f"Cannot decode file {file_path}: {e}") from e

    try:
        tree: ast.Module = ast.parse(content)
    except SyntaxError as e:
        raise SyntaxError(f"Invalid Python syntax in {file_path}: {e}") from e

    # Extract all functions and classes
    items: list[FunctionAndClassDetails] = self._extract_items(tree)

    # Check each item
    errors: list[DocstringError] = []
    for item in items:
        try:
            self._check_single_docstring(item, str(file_path))
        except DocstringError as e:
            errors.append(e)

    return errors
_should_exclude_file 🔗
_should_exclude_file(
    relative_path: Path, exclude_patterns: list[str]
) -> bool

Summary

Check if a file should be excluded based on patterns.

Parameters:

Name Type Description Default
relative_path Path

The relative path of the file to check.

required
exclude_patterns list[str]

List of glob patterns to check against.

required

Returns:

Type Description
bool

True if the file matches any exclusion pattern.

Source code in src/docstring_format_checker/core.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def _should_exclude_file(self, relative_path: Path, exclude_patterns: list[str]) -> bool:
    """
    !!! note "Summary"
        Check if a file should be excluded based on patterns.

    Params:
        relative_path (Path):
            The relative path of the file to check.
        exclude_patterns (list[str]):
            List of glob patterns to check against.

    Returns:
        (bool):
            True if the file matches any exclusion pattern.
    """
    for pattern in exclude_patterns:
        if fnmatch.fnmatch(str(relative_path), pattern):
            return True
    return False
_filter_python_files 🔗
_filter_python_files(
    python_files: list[Path],
    directory_path: Path,
    exclude_patterns: list[str],
) -> list[Path]

Summary

Filter Python files based on exclusion patterns.

Parameters:

Name Type Description Default
python_files list[Path]

List of Python files to filter.

required
directory_path Path

The base directory path for relative path calculation.

required
exclude_patterns list[str]

List of glob patterns to exclude.

required

Returns:

Type Description
list[Path]

Filtered list of Python files that don't match exclusion patterns.

Source code in src/docstring_format_checker/core.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def _filter_python_files(
    self,
    python_files: list[Path],
    directory_path: Path,
    exclude_patterns: list[str],
) -> list[Path]:
    """
    !!! note "Summary"
        Filter Python files based on exclusion patterns.

    Params:
        python_files (list[Path]):
            List of Python files to filter.
        directory_path (Path):
            The base directory path for relative path calculation.
        exclude_patterns (list[str]):
            List of glob patterns to exclude.

    Returns:
        (list[Path]):
            Filtered list of Python files that don't match exclusion patterns.
    """
    filtered_files: list[Path] = []
    for file_path in python_files:
        relative_path: Path = file_path.relative_to(directory_path)
        if not self._should_exclude_file(relative_path, exclude_patterns):
            filtered_files.append(file_path)
    return filtered_files
_check_file_with_error_handling 🔗
_check_file_with_error_handling(
    file_path: Path,
) -> list[DocstringError]

Summary

Check a single file and handle exceptions gracefully.

Parameters:

Name Type Description Default
file_path Path

Path to the file to check.

required

Returns:

Type Description
list[DocstringError]

List of DocstringError objects found in the file.

Source code in src/docstring_format_checker/core.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def _check_file_with_error_handling(self, file_path: Path) -> list[DocstringError]:
    """
    !!! note "Summary"
        Check a single file and handle exceptions gracefully.

    Params:
        file_path (Path):
            Path to the file to check.

    Returns:
        (list[DocstringError]):
            List of DocstringError objects found in the file.
    """
    try:
        return self.check_file(file_path)
    except (FileNotFoundError, ValueError, SyntaxError) as e:
        # Create a special error for file-level issues
        error = DocstringError(
            message=str(e),
            file_path=str(file_path),
            line_number=0,
            item_name="",
            item_type="file",
        )
        return [error]
check_directory 🔗
check_directory(
    directory_path: Union[str, Path],
    exclude_patterns: Optional[list[str]] = None,
) -> dict[str, list[DocstringError]]

Summary

Check docstrings in all Python files in a directory recursively.

Parameters:

Name Type Description Default
directory_path Union[str, Path]

Path to the directory to check.

required
exclude_patterns Optional[list[str]]

List of glob patterns to exclude.

None

Raises:

Type Description
FileNotFoundError

If the directory doesn't exist.

DirectoryNotFoundError

If the path is not a directory.

Returns:

Type Description
dict[str, list[DocstringError]]

Dictionary mapping file paths to lists of DocstringError objects.

Source code in src/docstring_format_checker/core.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def check_directory(
    self,
    directory_path: Union[str, Path],
    exclude_patterns: Optional[list[str]] = None,
) -> dict[str, list[DocstringError]]:
    """
    !!! note "Summary"
        Check docstrings in all Python files in a directory recursively.

    Params:
        directory_path (Union[str, Path]):
            Path to the directory to check.
        exclude_patterns (Optional[list[str]]):
            List of glob patterns to exclude.

    Raises:
        (FileNotFoundError):
            If the directory doesn't exist.
        (DirectoryNotFoundError):
            If the path is not a directory.

    Returns:
        (dict[str, list[DocstringError]]):
            Dictionary mapping file paths to lists of DocstringError objects.
    """
    directory_path = Path(directory_path)
    if not directory_path.exists():
        raise FileNotFoundError(f"Directory not found: {directory_path}")

    if not directory_path.is_dir():
        raise DirectoryNotFoundError(f"Path is not a directory: {directory_path}")

    python_files: list[Path] = list(directory_path.glob("**/*.py"))

    # Filter out excluded patterns if provided
    if exclude_patterns:
        python_files = self._filter_python_files(python_files, directory_path, exclude_patterns)

    # Check each file and collect results
    results: dict[str, list[DocstringError]] = {}
    for file_path in python_files:
        errors: list[DocstringError] = self._check_file_with_error_handling(file_path)
        if errors:  # Only include files with errors
            results[str(file_path)] = errors

    return results
_is_overload_function 🔗
_is_overload_function(
    node: Union[FunctionDef, AsyncFunctionDef],
) -> bool

Summary

Check if a function definition is decorated with @overload.

Parameters:

Name Type Description Default
node Union[FunctionDef, AsyncFunctionDef]

The function node to check for @overload decorator.

required

Returns:

Type Description
bool

True if the function has @overload decorator, False otherwise.

Source code in src/docstring_format_checker/core.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def _is_overload_function(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool:
    """
    !!! note "Summary"
        Check if a function definition is decorated with @overload.

    Params:
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function node to check for @overload decorator.

    Returns:
        (bool):
            True if the function has @overload decorator, False otherwise.
    """

    for decorator in node.decorator_list:
        # Handle direct name reference: @overload
        if isinstance(decorator, ast.Name) and decorator.id == "overload":
            return True
        # Handle attribute reference: @typing.overload
        elif isinstance(decorator, ast.Attribute) and decorator.attr == "overload":
            return True
    return False
_extract_all_params 🔗
_extract_all_params(
    node: Union[FunctionDef, AsyncFunctionDef],
) -> list[str]

Summary

Extract all parameter names from a function signature.

Details

Extract all parameter types including:

  • Positional-only parameters (before /)
  • Regular positional parameters
  • Keyword-only parameters (after *)
  • Variable positional arguments (*args)
  • Variable keyword arguments (**kwargs)

Exclude self and cls parameters (method context parameters).

Parameters:

Name Type Description Default
node Union[FunctionDef, AsyncFunctionDef]

The function node to extract parameters from.

required

Returns:

Type Description
list[str]

List of all parameter names in the function signature.

Examples
def func(a, b, /, c, *args, d, **kwargs): ...


# Returns: ['a', 'b', 'c', 'args', 'd', 'kwargs']
Source code in src/docstring_format_checker/core.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def _extract_all_params(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> list[str]:
    """
    !!! note "Summary"
        Extract all parameter names from a function signature.

    ???+ abstract "Details"
        Extract all parameter types including:

        - Positional-only parameters (before `/`)
        - Regular positional parameters
        - Keyword-only parameters (after `*`)
        - Variable positional arguments (`*args`)
        - Variable keyword arguments (`**kwargs`)

        Exclude `self` and `cls` parameters (method context parameters).

    Params:
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function node to extract parameters from.

    Returns:
        (list[str]):
            List of all parameter names in the function signature.

    ???+ example "Examples"

        ```python
        def func(a, b, /, c, *args, d, **kwargs): ...


        # Returns: ['a', 'b', 'c', 'args', 'd', 'kwargs']
        ```
    """
    params: list[str] = []

    # Positional-only parameters (before /)
    for arg in node.args.posonlyargs:
        if arg.arg not in ("self", "cls"):
            params.append(arg.arg)

    # Regular positional parameters
    for arg in node.args.args:
        if arg.arg not in ("self", "cls"):
            params.append(arg.arg)

    # Variable positional arguments (*args)
    if node.args.vararg:
        params.append(node.args.vararg.arg)

    # Keyword-only parameters (after *)
    for arg in node.args.kwonlyargs:
        if arg.arg not in ("self", "cls"):
            params.append(arg.arg)

    # Variable keyword arguments (**kwargs)
    if node.args.kwarg:
        params.append(node.args.kwarg.arg)

    return params
_extract_items 🔗
_extract_items(tree: AST) -> list[FunctionAndClassDetails]

Summary

Extract all functions and classes from the AST.

Parameters:

Name Type Description Default
tree AST

The Abstract Syntax Tree (AST) to extract items from.

required

Returns:

Type Description
list[FunctionAndClassDetails]

A list of extracted function and class details.

Source code in src/docstring_format_checker/core.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def _extract_items(self, tree: ast.AST) -> list[FunctionAndClassDetails]:
    """
    !!! note "Summary"
        Extract all functions and classes from the AST.

    Params:
        tree (ast.AST):
            The Abstract Syntax Tree (AST) to extract items from.

    Returns:
        (list[FunctionAndClassDetails]):
            A list of extracted function and class details.
    """

    items: list[FunctionAndClassDetails] = []

    class ItemVisitor(ast.NodeVisitor):
        """
        !!! note "Summary"
            AST visitor to extract function and class definitions
        """

        def __init__(self, checker: DocstringChecker) -> None:
            """
            !!! note "Summary"
                Initialize the AST visitor.
            """
            self.class_stack: list[str] = []
            self.checker: DocstringChecker = checker

        def visit_ClassDef(self, node: ast.ClassDef) -> None:
            """
            !!! note "Summary"
                Visit class definition node.
            """
            # Skip private classes unless check_private is enabled
            should_check: bool = self.checker.config.global_config.check_private or not node.name.startswith("_")
            if should_check:
                items.append(
                    FunctionAndClassDetails(
                        item_type="class",
                        name=node.name,
                        node=node,
                        lineno=node.lineno,
                        parent_class=None,
                    )
                )

            # Visit methods in this class
            self.class_stack.append(node.name)
            self.generic_visit(node)
            self.class_stack.pop()

        def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
            """
            !!! note "Summary"
                Visit function definition node.
            """
            self._visit_function(node)

        def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
            """
            !!! note "Summary"
                Visit async function definition node.
            """
            self._visit_function(node)

        def _visit_function(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> None:
            """
            !!! note "Summary"
                Visit function definition node (sync or async).
            """

            # Skip private functions unless check_private is enabled
            should_check: bool = self.checker.config.global_config.check_private or not node.name.startswith("_")
            if should_check:
                # Skip @overload functions - they don't need docstrings
                if not self.checker._is_overload_function(node):
                    item_type: Literal["function", "method"] = "method" if self.class_stack else "function"
                    parent_class: Optional[str] = self.class_stack[-1] if self.class_stack else None

                    items.append(
                        FunctionAndClassDetails(
                            item_type=item_type,
                            name=node.name,
                            node=node,
                            lineno=node.lineno,
                            parent_class=parent_class,
                        )
                    )

            self.generic_visit(node)

    visitor = ItemVisitor(self)
    visitor.visit(tree)

    return items
_is_section_applicable_to_item 🔗
_is_section_applicable_to_item(
    section: SectionConfig, item: FunctionAndClassDetails
) -> bool

Summary

Check if a section configuration applies to the given item type.

Parameters:

Name Type Description Default
section SectionConfig

The section configuration to check.

required
item FunctionAndClassDetails

The function or class to check against.

required

Returns:

Type Description
bool

True if the section applies to this item type.

Source code in src/docstring_format_checker/core.py
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
def _is_section_applicable_to_item(
    self,
    section: SectionConfig,
    item: FunctionAndClassDetails,
) -> bool:
    """
    !!! note "Summary"
        Check if a section configuration applies to the given item type.

    Params:
        section (SectionConfig):
            The section configuration to check.
        item (FunctionAndClassDetails):
            The function or class to check against.

    Returns:
        (bool):
            True if the section applies to this item type.
    """

    is_function: bool = isinstance(item.node, (ast.FunctionDef, ast.AsyncFunctionDef))

    # Free text sections apply only to functions and methods, not classes
    if section.type == "free_text":
        return is_function

    # List name and type sections have specific rules
    if section.type == "list_name_and_type":
        section_name_lower: str = section.name.lower()

        # Params only apply to functions/methods
        if section_name_lower == "params" and is_function:
            return True

        # Returns only apply to functions/methods
        if section_name_lower in ["returns", "return"] and is_function:
            return True

        return False

    # These sections apply to functions/methods that might have them
    if section.type in ["list_type", "list_name"]:
        return is_function

    return False
_get_applicable_required_sections 🔗
_get_applicable_required_sections(
    item: FunctionAndClassDetails,
) -> list[SectionConfig]

Summary

Get all required sections that apply to the given item.

Parameters:

Name Type Description Default
item FunctionAndClassDetails

The function or class to check.

required

Returns:

Type Description
list[SectionConfig]

List of section configurations that are required and apply to this item.

Source code in src/docstring_format_checker/core.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def _get_applicable_required_sections(self, item: FunctionAndClassDetails) -> list[SectionConfig]:
    """
    !!! note "Summary"
        Get all required sections that apply to the given item.

    Params:
        item (FunctionAndClassDetails):
            The function or class to check.

    Returns:
        (list[SectionConfig]):
            List of section configurations that are required and apply to this item.
    """

    # Filter required sections based on item type
    applicable_sections: list[SectionConfig] = []
    for section in self.sections_config:
        if section.required and self._is_section_applicable_to_item(section, item):
            applicable_sections.append(section)
    return applicable_sections
_handle_missing_docstring 🔗
_handle_missing_docstring(
    item: FunctionAndClassDetails,
    file_path: str,
    requires_docstring: bool,
) -> None

Summary

Handle the case where a docstring is missing.

Parameters:

Name Type Description Default
item FunctionAndClassDetails

The function or class without a docstring.

required
file_path str

The path to the file containing the item.

required
requires_docstring bool

Whether a docstring is required for this item.

required

Raises:

Type Description
DocstringError

If docstring is required but missing.

Source code in src/docstring_format_checker/core.py
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
def _handle_missing_docstring(
    self,
    item: FunctionAndClassDetails,
    file_path: str,
    requires_docstring: bool,
) -> None:
    """
    !!! note "Summary"
        Handle the case where a docstring is missing.

    Params:
        item (FunctionAndClassDetails):
            The function or class without a docstring.
        file_path (str):
            The path to the file containing the item.
        requires_docstring (bool):
            Whether a docstring is required for this item.

    Raises:
        DocstringError: If docstring is required but missing.
    """

    # Raise error if docstring is required
    if requires_docstring and self.config.global_config.require_docstrings:
        message: str = f"Missing docstring for {item.item_type}"
        raise DocstringError(
            message=message,
            file_path=file_path,
            line_number=item.lineno,
            item_name=item.name,
            item_type=item.item_type,
        )
_check_single_docstring 🔗
_check_single_docstring(
    item: FunctionAndClassDetails, file_path: str
) -> None

Summary

Check a single function or class docstring.

Parameters:

Name Type Description Default
item FunctionAndClassDetails

The function or class to check.

required
file_path str

The path to the file containing the item.

required

Returns:

Type Description
None

Nothing is returned.

Source code in src/docstring_format_checker/core.py
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
def _check_single_docstring(self, item: FunctionAndClassDetails, file_path: str) -> None:
    """
    !!! note "Summary"
        Check a single function or class docstring.

    Params:
        item (FunctionAndClassDetails):
            The function or class to check.
        file_path (str):
            The path to the file containing the item.

    Returns:
        (None):
            Nothing is returned.
    """

    docstring: Optional[str] = ast.get_docstring(item.node)

    # Determine which required sections apply to this item type
    applicable_sections: list[SectionConfig] = self._get_applicable_required_sections(item)
    requires_docstring: bool = len(applicable_sections) > 0

    # Only require docstrings if the global flag is enabled
    if not docstring:
        self._handle_missing_docstring(item, file_path, requires_docstring)
        return  # No docstring required or docstring requirement disabled

    # Validate docstring sections if docstring exists
    self._validate_docstring_sections(docstring, item, file_path)
_validate_docstring_sections 🔗
_validate_docstring_sections(
    docstring: str,
    item: FunctionAndClassDetails,
    file_path: str,
) -> None

Summary

Validate the sections within a docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
item FunctionAndClassDetails

The function or class to check.

required
file_path str

The path to the file containing the item.

required

Returns:

Type Description
None

Nothing is returned.

Source code in src/docstring_format_checker/core.py
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
def _validate_docstring_sections(
    self,
    docstring: str,
    item: FunctionAndClassDetails,
    file_path: str,
) -> None:
    """
    !!! note "Summary"
        Validate the sections within a docstring.

    Params:
        docstring (str):
            The docstring to validate.
        item (FunctionAndClassDetails):
            The function or class to check.
        file_path (str):
            The path to the file containing the item.

    Returns:
        (None):
            Nothing is returned.
    """

    errors: list[str] = []

    # Validate required sections are present
    required_section_errors: list[str] = self._validate_all_required_sections(docstring, item)
    errors.extend(required_section_errors)

    # Validate all existing sections (required or not)
    existing_section_errors: list[str] = self._validate_all_existing_sections(docstring, item)
    errors.extend(existing_section_errors)

    # Perform comprehensive validation checks
    comprehensive_errors: list[str] = self._perform_comprehensive_validation(docstring)
    errors.extend(comprehensive_errors)

    # Report errors if found
    if errors:
        combined_message: str = "; ".join(errors)
        raise DocstringError(
            message=combined_message,
            file_path=file_path,
            line_number=item.lineno,
            item_name=item.name,
            item_type=item.item_type,
        )
_is_params_section_required 🔗
_is_params_section_required(
    item: FunctionAndClassDetails,
) -> bool

Summary

Check if params section is required for this item.

Parameters:

Name Type Description Default
item FunctionAndClassDetails

The function or class details.

required

Returns:

Type Description
bool

True if params section is required, False otherwise.

Source code in src/docstring_format_checker/core.py
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
def _is_params_section_required(self, item: FunctionAndClassDetails) -> bool:
    """
    !!! note "Summary"
        Check if params section is required for this item.

    Params:
        item (FunctionAndClassDetails):
            The function or class details.

    Returns:
        (bool):
            True if params section is required, False otherwise.
    """

    # For classes, params section not required (attributes handled differently)
    if isinstance(item.node, ast.ClassDef):
        return False

    # For functions, only required if function has parameters (excluding self/cls)
    # item.node is guaranteed to be FunctionDef or AsyncFunctionDef due to type constraints
    params = self._extract_all_params(item.node)
    return len(params) > 0
_validate_all_required_sections 🔗
_validate_all_required_sections(
    docstring: str, item: FunctionAndClassDetails
) -> list[str]

Summary

Validate all required sections are present.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
item FunctionAndClassDetails

The function or class details.

required

Returns:

Type Description
list[str]

List of validation error messages for missing required sections.

Source code in src/docstring_format_checker/core.py
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
def _validate_all_required_sections(self, docstring: str, item: FunctionAndClassDetails) -> list[str]:
    """
    !!! note "Summary"
        Validate all required sections are present.

    Params:
        docstring (str):
            The docstring to validate.
        item (FunctionAndClassDetails):
            The function or class details.

    Returns:
        (list[str]):
            List of validation error messages for missing required sections.
    """

    errors: list[str] = []
    for section in self.required_sections:
        # Special handling for params section - only required if function/class has parameters
        if section.name.lower() == "params":
            if not self._is_params_section_required(item):
                continue

        # Only check if the section exists, don't validate content yet
        if not self._section_exists(docstring, section):
            errors.append(f"Missing required section: '{section.name}'")
    return errors
_validate_all_existing_sections 🔗
_validate_all_existing_sections(
    docstring: str, item: FunctionAndClassDetails
) -> list[str]

Summary

Validate content of all existing sections (required or not).

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
item FunctionAndClassDetails

The function or class details.

required

Returns:

Type Description
list[str]

List of validation error messages for invalid section content.

Source code in src/docstring_format_checker/core.py
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
def _validate_all_existing_sections(self, docstring: str, item: FunctionAndClassDetails) -> list[str]:
    """
    !!! note "Summary"
        Validate content of all existing sections (required or not).

    Params:
        docstring (str):
            The docstring to validate.
        item (FunctionAndClassDetails):
            The function or class details.

    Returns:
        (list[str]):
            List of validation error messages for invalid section content.
    """

    errors: list[str] = []
    for section in self.config.sections:
        # Only validate if the section actually exists in the docstring
        if self._section_exists(docstring, section):
            section_error = self._validate_single_section_content(docstring, section, item)
            if section_error:
                errors.append(section_error)
    return errors
_section_exists 🔗
_section_exists(
    docstring: str, section: SectionConfig
) -> bool

Summary

Check if a section exists in the docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required
section SectionConfig

The section configuration.

required

Returns:

Type Description
bool

True if section exists, False otherwise.

Source code in src/docstring_format_checker/core.py
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
def _section_exists(self, docstring: str, section: SectionConfig) -> bool:
    """
    !!! note "Summary"
        Check if a section exists in the docstring.

    Params:
        docstring (str):
            The docstring to check.
        section (SectionConfig):
            The section configuration.

    Returns:
        (bool):
            `True` if section exists, `False` otherwise.
    """

    section_name: str = section.name.lower()

    # For free text sections, use the existing logic from _check_free_text_section
    if section.type == "free_text":
        return self._check_free_text_section(docstring, section)

    # Check for admonition style sections (for non-free-text types)
    if section.admonition and isinstance(section.admonition, str):
        if section.prefix and isinstance(section.prefix, str):
            # e.g., "!!! note" or "???+ abstract"
            pattern: str = rf"{re.escape(section.prefix)}\s+{re.escape(section.admonition)}"
            if re.search(pattern, docstring, re.IGNORECASE):
                return True

    # Check for standard sections with colons (e.g., "Params:", "Returns:")
    pattern = rf"^[ \t]*{re.escape(section_name)}:[ \t]*$"
    if re.search(pattern, docstring, re.IGNORECASE | re.MULTILINE):
        return True

    return False
_validate_single_section_content 🔗
_validate_single_section_content(
    docstring: str,
    section: SectionConfig,
    item: FunctionAndClassDetails,
) -> Optional[str]

Summary

Validate the content of a single section based on its type.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
section SectionConfig

The section configuration to validate against.

required
item FunctionAndClassDetails

The function or class details.

required

Returns:

Type Description
Optional[str]

Error message if validation fails, None otherwise.

Source code in src/docstring_format_checker/core.py
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
def _validate_single_section_content(
    self, docstring: str, section: SectionConfig, item: FunctionAndClassDetails
) -> Optional[str]:
    """
    !!! note "Summary"
        Validate the content of a single section based on its type.

    Params:
        docstring (str):
            The docstring to validate.
        section (SectionConfig):
            The section configuration to validate against.
        item (FunctionAndClassDetails):
            The function or class details.

    Returns:
        (Optional[str]):
            Error message if validation fails, None otherwise.
    """

    if section.type == "list_name_and_type":
        return self._validate_list_name_and_type_section(docstring, section, item)

    if section.type == "list_name":
        return self._validate_list_name_section(docstring, section)

    # For `section.type in ("free_text", "list_type")`
    # these sections do not need content validation beyond existence
    return None
_validate_list_name_and_type_section 🔗
_validate_list_name_and_type_section(
    docstring: str,
    section: SectionConfig,
    item: FunctionAndClassDetails,
) -> Optional[str]

Summary

Validate list_name_and_type sections (params, returns).

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
section SectionConfig

The section configuration.

required
item FunctionAndClassDetails

The function or class details.

required

Returns:

Type Description
Optional[str]

Error message if section is invalid, None otherwise.

Source code in src/docstring_format_checker/core.py
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
def _validate_list_name_and_type_section(
    self, docstring: str, section: SectionConfig, item: FunctionAndClassDetails
) -> Optional[str]:
    """
    !!! note "Summary"
        Validate list_name_and_type sections (params, returns).

    Params:
        docstring (str):
            The docstring to validate.
        section (SectionConfig):
            The section configuration.
        item (FunctionAndClassDetails):
            The function or class details.

    Returns:
        (Optional[str]):
            Error message if section is invalid, None otherwise.
    """

    section_name: str = section.name.lower()

    if section_name == "params" and isinstance(item.node, (ast.FunctionDef, ast.AsyncFunctionDef)):
        # Check params section exists and is properly formatted with detailed error reporting
        is_valid, error_message = self._check_params_section_detailed(docstring, item.node)
        if not is_valid:
            return error_message

        # If validate_param_types is enabled, validate type annotations match
        if self.config.global_config.validate_param_types:
            type_error: Optional[str] = self._validate_param_types(docstring, item.node)
            if type_error:
                return type_error

    # For returns/return sections, no additional validation beyond existence
    # The _section_exists check already verified the section is present

    return None
_validate_list_name_section 🔗
_validate_list_name_section(
    docstring: str, section: SectionConfig
) -> Optional[str]

Summary

Validate list_name sections.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
section SectionConfig

The section configuration.

required

Returns:

Type Description
Optional[str]

Error message if section is missing, None otherwise.

Source code in src/docstring_format_checker/core.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
def _validate_list_name_section(self, docstring: str, section: SectionConfig) -> Optional[str]:
    """
    !!! note "Summary"
        Validate list_name sections.

    Params:
        docstring (str):
            The docstring to validate.
        section (SectionConfig):
            The section configuration.

    Returns:
        (Optional[str]):
            Error message if section is missing, None otherwise.
    """
    # No additional validation beyond existence
    # The _section_exists check already verified the section is present
    return None
_perform_comprehensive_validation 🔗
_perform_comprehensive_validation(
    docstring: str,
) -> list[str]

Summary

Perform comprehensive validation checks on docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required

Returns:

Type Description
list[str]

List of validation error messages.

Source code in src/docstring_format_checker/core.py
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
def _perform_comprehensive_validation(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Perform comprehensive validation checks on docstring.

    Params:
        docstring (str):
            The docstring to validate.

    Returns:
        (list[str]):
            List of validation error messages.
    """

    errors: list[str] = []

    # Check section order
    order_errors: list[str] = self._check_section_order(docstring)
    errors.extend(order_errors)

    # Check for mutual exclusivity (returns vs yields)
    if self._has_both_returns_and_yields(docstring):
        errors.append("Docstring cannot have both Returns and Yields sections")

    # Check for undefined sections (only if not allowed)
    if not self.config.global_config.allow_undefined_sections:
        undefined_errors: list[str] = self._check_undefined_sections(docstring)
        errors.extend(undefined_errors)

    # Perform formatting validation
    formatting_errors: list[str] = self._perform_formatting_validation(docstring)
    errors.extend(formatting_errors)

    return errors
_perform_formatting_validation 🔗
_perform_formatting_validation(docstring: str) -> list[str]

Summary

Perform formatting validation checks.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required

Returns:

Type Description
list[str]

List of formatting error messages.

Source code in src/docstring_format_checker/core.py
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
def _perform_formatting_validation(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Perform formatting validation checks.

    Params:
        docstring (str):
            The docstring to validate.

    Returns:
        (list[str]):
            List of formatting error messages.
    """

    errors: list[str] = []

    # Check admonition values
    admonition_errors: list[str] = self._check_admonition_values(docstring)
    errors.extend(admonition_errors)

    # Check colon usage
    colon_errors: list[str] = self._check_colon_usage(docstring)
    errors.extend(colon_errors)

    # Check title case
    title_case_errors: list[str] = self._check_title_case_sections(docstring)
    errors.extend(title_case_errors)

    # Check parentheses
    parentheses_errors: list[str] = self._check_parentheses_validation(docstring)
    errors.extend(parentheses_errors)

    return errors
_check_free_text_section 🔗
_check_free_text_section(
    docstring: str, section: SectionConfig
) -> bool

Summary

Check if a free text section exists in the docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required
section SectionConfig

The section configuration to validate.

required

Returns:

Type Description
bool

True if the section exists, False otherwise.

Source code in src/docstring_format_checker/core.py
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
def _check_free_text_section(self, docstring: str, section: SectionConfig) -> bool:
    """
    !!! note "Summary"
        Check if a free text section exists in the docstring.

    Params:
        docstring (str):
            The docstring to check.
        section (SectionConfig):
            The section configuration to validate.

    Returns:
        (bool):
            `True` if the section exists, `False` otherwise.
    """

    # Make the section name part case-insensitive too
    if isinstance(section.admonition, str) and section.admonition and section.prefix:
        # Format like: !!! note "Summary"
        escaped_name: str = re.escape(section.name)
        pattern: str = (
            rf'{re.escape(section.prefix)}\s+{re.escape(section.admonition)}\s+"[^"]*{escaped_name}[^"]*"'
        )
        return bool(re.search(pattern, docstring, re.IGNORECASE))

    # For summary, accept either formal format or simple docstring
    if section.name.lower() in ["summary"]:
        formal_pattern = r'!!! note "Summary"'
        if re.search(formal_pattern, docstring, re.IGNORECASE):
            return True
        # Accept any non-empty docstring as summary
        return len(docstring.strip()) > 0

    # Look for examples section
    elif section.name.lower() in ["examples", "example"]:
        return bool(re.search(r'\?\?\?\+ example "Examples"', docstring, re.IGNORECASE))

    # Default to true for unknown free text sections
    return True
_check_params_section 🔗
_check_params_section(
    docstring: str,
    node: Union[FunctionDef, AsyncFunctionDef],
) -> bool

Summary

Check if the Params section exists and documents all parameters.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required
node Union[FunctionDef, AsyncFunctionDef]

The function node to check.

required

Returns:

Type Description
bool

True if the section exists and is valid, False otherwise.

Source code in src/docstring_format_checker/core.py
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
def _check_params_section(self, docstring: str, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool:
    """
    !!! note "Summary"
        Check if the Params section exists and documents all parameters.

    Params:
        docstring (str):
            The docstring to check.
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function node to check.

    Returns:
        (bool):
            `True` if the section exists and is valid, `False` otherwise.
    """

    # Get function parameters (excluding 'self' for methods)
    params: list[str] = self._extract_all_params(node)

    if not params:
        return True  # No parameters to document

    # Check if Params section exists
    if not re.search(r"Params:", docstring):
        return False

    # Check each parameter is documented
    for param in params:
        param_pattern: str = rf"{re.escape(param)}\s*\([^)]+\):"
        if not re.search(param_pattern, docstring):
            return False

    return True
_extract_documented_params 🔗
_extract_documented_params(docstring: str) -> list[str]

Summary

Extract parameter names from the Params section of a docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to parse.

required

Returns:

Type Description
list[str]

List of parameter names found in the Params section.

Source code in src/docstring_format_checker/core.py
 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
def _extract_documented_params(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Extract parameter names from the Params section of a docstring.

    Params:
        docstring (str):
            The docstring to parse.

    Returns:
        (list[str]):
            List of parameter names found in the Params section.
    """
    documented_params: list[str] = []
    param_pattern: str = r"^\s*(\*{0,2}\w+)\s*\([^)]+\):"
    lines: list[str] = docstring.split("\n")
    in_params_section: bool = False

    for line in lines:
        # Check if we've entered the Params section
        if "Params:" in line:
            in_params_section = True
            continue

        # Check if we've left the Params section (next section starts)
        # Match section names (can include spaces) followed by a colon
        if in_params_section and re.match(r"^[ ]{0,4}[A-Z][\w\s]+:", line):
            break

        # Extract parameter name
        if in_params_section:
            match = re.match(param_pattern, line)
            if match:
                documented_params.append(match.group(1))

    return documented_params
_build_param_mismatch_error 🔗
_build_param_mismatch_error(
    missing_in_docstring: list[str],
    extra_in_docstring: list[str],
) -> str

Summary

Build detailed error message for parameter mismatches.

Parameters:

Name Type Description Default
missing_in_docstring list[str]

Parameters in signature but not in docstring.

required
extra_in_docstring list[str]

Parameters in docstring but not in signature.

required

Returns:

Type Description
str

Formatted error message.

Source code in src/docstring_format_checker/core.py
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
def _build_param_mismatch_error(self, missing_in_docstring: list[str], extra_in_docstring: list[str]) -> str:
    """
    !!! note "Summary"
        Build detailed error message for parameter mismatches.

    Params:
        missing_in_docstring (list[str]):
            Parameters in signature but not in docstring.
        extra_in_docstring (list[str]):
            Parameters in docstring but not in signature.

    Returns:
        (str):
            Formatted error message.
    """
    error_parts: list[str] = []

    # Create copies to avoid mutating inputs
    missing_copy: list[str] = list(missing_in_docstring)
    extra_copy: list[str] = list(extra_in_docstring)

    # Check for asterisk mismatch
    # We iterate over a copy of missing_copy to allow modification
    for missing in list(missing_copy):
        for extra in list(extra_copy):
            if extra.lstrip("*") == missing:
                asterisk_count: int = len(extra) - len(extra.lstrip("*"))
                asterisk_word: str = "asterisk" if asterisk_count == 1 else "asterisks"
                error_parts.append(
                    f"  - Parameter '{missing}' found in docstring as '{extra}'. Please remove the {asterisk_word}."
                )
                missing_copy.remove(missing)
                extra_copy.remove(extra)
                break

    if missing_copy:
        missing_str: str = "', '".join(missing_copy)
        error_parts.append(f"  - In signature but not in docstring: '{missing_str}'")

    if extra_copy:
        extra_str: str = "', '".join(extra_copy)
        error_parts.append(f"  - In docstring but not in signature: '{extra_str}'")

    return "Parameter mismatch:\n" + "\n".join(error_parts)
_check_params_section_detailed 🔗
_check_params_section_detailed(
    docstring: str,
    node: Union[FunctionDef, AsyncFunctionDef],
) -> tuple[bool, Optional[str]]

Summary

Check if the Params section exists and documents all parameters, with detailed error reporting.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required
node Union[FunctionDef, AsyncFunctionDef]

The function node to check.

required

Returns:

Type Description
tuple[bool, Optional[str]]

Tuple of (is_valid, error_message). If valid, error_message is None.

Source code in src/docstring_format_checker/core.py
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
def _check_params_section_detailed(
    self, docstring: str, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]
) -> tuple[bool, Optional[str]]:
    """
    !!! note "Summary"
        Check if the Params section exists and documents all parameters, with detailed error reporting.

    Params:
        docstring (str):
            The docstring to check.
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function node to check.

    Returns:
        (tuple[bool, Optional[str]]):
            Tuple of (is_valid, error_message). If valid, error_message is None.
    """

    # Get function parameters (excluding 'self' and 'cls' for methods)
    signature_params: list[str] = self._extract_all_params(node)

    if not signature_params:
        return (True, None)  # No parameters to document

    # Check if Params section exists
    if not re.search(r"Params:", docstring):
        return (False, "Params section not found in docstring")

    # Extract documented parameters from docstring
    documented_params: list[str] = self._extract_documented_params(docstring)

    # Find parameters in signature but not in docstring
    missing_in_docstring: list[str] = [p for p in signature_params if p not in documented_params]

    # Find parameters in docstring but not in signature
    extra_in_docstring: list[str] = [p for p in documented_params if p not in signature_params]

    # Build detailed error message if there are mismatches
    if missing_in_docstring or extra_in_docstring:
        error_message: str = self._build_param_mismatch_error(missing_in_docstring, extra_in_docstring)
        return (False, error_message)

    return (True, None)
_add_arg_types_to_dict 🔗
_add_arg_types_to_dict(
    args: list[arg], param_types: dict[str, str]
) -> None

Summary

Add type annotations from a list of arguments to the parameter types dictionary.

Parameters:

Name Type Description Default
args list[arg]

List of AST argument nodes.

required
param_types dict[str, str]

Dictionary to add parameter types to.

required
Source code in src/docstring_format_checker/core.py
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
def _add_arg_types_to_dict(self, args: list[ast.arg], param_types: dict[str, str]) -> None:
    """
    !!! note "Summary"
        Add type annotations from a list of arguments to the parameter types dictionary.

    Params:
        args (list[ast.arg]):
            List of AST argument nodes.
        param_types (dict[str, str]):
            Dictionary to add parameter types to.
    """
    for arg in args:
        if arg.arg not in ("self", "cls") and arg.annotation:
            param_types[arg.arg] = ast.unparse(arg.annotation)
_extract_param_types 🔗
_extract_param_types(
    node: Union[FunctionDef, AsyncFunctionDef],
) -> dict[str, str]

Summary

Extract parameter names and their type annotations from function signature.

Parameters:

Name Type Description Default
node Union[FunctionDef, AsyncFunctionDef]

The function AST node.

required

Returns:

Type Description
dict[str, str]

Dictionary mapping parameter names to their type annotation strings.

Source code in src/docstring_format_checker/core.py
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
def _extract_param_types(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> dict[str, str]:
    """
    !!! note "Summary"
        Extract parameter names and their type annotations from function signature.

    Params:
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function AST node.

    Returns:
        (dict[str, str]):
            Dictionary mapping parameter names to their type annotation strings.
    """
    param_types: dict[str, str] = {}

    # Positional-only parameters (before /)
    self._add_arg_types_to_dict(node.args.posonlyargs, param_types)

    # Regular positional parameters
    self._add_arg_types_to_dict(node.args.args, param_types)

    # Variable positional arguments (*args)
    if node.args.vararg and node.args.vararg.annotation:
        param_types[node.args.vararg.arg] = ast.unparse(node.args.vararg.annotation)

    # Keyword-only parameters (after *)
    self._add_arg_types_to_dict(node.args.kwonlyargs, param_types)

    # Variable keyword arguments (**kwargs)
    if node.args.kwarg and node.args.kwarg.annotation:
        param_types[node.args.kwarg.arg] = ast.unparse(node.args.kwarg.annotation)

    return param_types
_extract_param_types_from_docstring 🔗
_extract_param_types_from_docstring(
    docstring: str,
) -> dict[str, str]

Summary

Extract parameter types from the Params section of docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to parse.

required

Returns:

Type Description
dict[str, str]

Dictionary mapping parameter names to their documented types.

Source code in src/docstring_format_checker/core.py
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
def _extract_param_types_from_docstring(self, docstring: str) -> dict[str, str]:
    """
    !!! note "Summary"
        Extract parameter types from the Params section of docstring.

    Params:
        docstring (str):
            The docstring to parse.

    Returns:
        (dict[str, str]):
            Dictionary mapping parameter names to their documented types.
    """
    param_types: dict[str, str] = {}

    # Find the Params section
    if not re.search(r"Params:", docstring):
        return param_types

    # Pattern to match parameter documentation: name (type):
    # Handles variations like:
    # - name (str):
    # - name (Optional[str]):
    # - name (Union[str, int]):
    # - name (list[str]):
    pattern: str = r"^\s*(\w+)\s*\(([^)]+)\)\s*:"

    lines: list[str] = docstring.split("\n")
    in_params_section: bool = False

    for line in lines:
        # Check if we've entered the Params section
        if "Params:" in line:
            in_params_section = True
            continue

        # Check if we've left the Params section (next section starts)
        # Section headers have minimal indentation (0-4 spaces), not deep indentation like param descriptions
        if in_params_section and re.match(r"^[ ]{0,4}[A-Z]\w+:", line):
            break

        # Extract parameter name and type
        if in_params_section:
            match = re.match(pattern, line)
            if match:
                param_name: str = match.group(1)
                param_type: str = match.group(2)
                param_types[param_name] = param_type

    return param_types
_normalize_type_string 🔗
_normalize_type_string(type_str: str) -> str

Summary

Normalize a type string for comparison.

Parameters:

Name Type Description Default
type_str str

The type string to normalize.

required

Returns:

Type Description
str

Normalized type string.

Source code in src/docstring_format_checker/core.py
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
def _normalize_type_string(self, type_str: str) -> str:
    """
    !!! note "Summary"
        Normalize a type string for comparison.

    Params:
        type_str (str):
            The type string to normalize.

    Returns:
        (str):
            Normalized type string.
    """

    # Remove whitespace
    normalized: str = re.sub(r"\s+", "", type_str)

    # Normalize quotes: ast.unparse() uses single quotes but docstrings typically use double quotes
    # Convert all quotes to single quotes for consistent comparison
    normalized = normalized.replace('"', "'")

    # Make case-insensitive for basic types
    # But preserve case for complex types to avoid breaking things like Optional
    return normalized
_compare_param_types 🔗
_compare_param_types(
    signature_types: dict[str, str],
    docstring_types: dict[str, str],
) -> list[tuple[str, str, str]]

Summary

Compare parameter types from signature and docstring.

Parameters:

Name Type Description Default
signature_types dict[str, str]

Parameter types from function signature.

required
docstring_types dict[str, str]

Parameter types from docstring.

required

Returns:

Type Description
list[tuple[str, str, str]]

List of mismatches as (param_name, signature_type, docstring_type).

Source code in src/docstring_format_checker/core.py
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
def _compare_param_types(
    self, signature_types: dict[str, str], docstring_types: dict[str, str]
) -> list[tuple[str, str, str]]:
    """
    !!! note "Summary"
        Compare parameter types from signature and docstring.

    Params:
        signature_types (dict[str, str]):
            Parameter types from function signature.
        docstring_types (dict[str, str]):
            Parameter types from docstring.

    Returns:
        (list[tuple[str, str, str]]):
            List of mismatches as (param_name, signature_type, docstring_type).
    """
    mismatches: list[tuple[str, str, str]] = []

    for param_name, sig_type in signature_types.items():
        # Check if parameter is documented in docstring
        if param_name not in docstring_types:
            # Parameter not documented - this is handled by other validation
            continue

        doc_type: str = docstring_types[param_name]

        # Normalize both types for comparison
        normalized_sig: str = self._normalize_type_string(sig_type)
        normalized_doc: str = self._normalize_type_string(doc_type)

        # Case-insensitive comparison
        if normalized_sig.lower() != normalized_doc.lower():
            mismatches.append((param_name, sig_type, doc_type))

    return mismatches
_get_params_with_defaults 🔗
_get_params_with_defaults(
    node: Union[FunctionDef, AsyncFunctionDef],
) -> set[str]

Summary

Get set of parameter names that have default values.

Parameters:

Name Type Description Default
node Union[FunctionDef, AsyncFunctionDef]

The function node to analyse.

required

Returns:

Type Description
set[str]

Set of parameter names that have default values.

Source code in src/docstring_format_checker/core.py
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
def _get_params_with_defaults(self, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> set[str]:
    """
    !!! note "Summary"
        Get set of parameter names that have default values.

    Params:
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function node to analyse.

    Returns:
        (set[str]):
            Set of parameter names that have default values.
    """
    params_with_defaults: set[str] = set()
    args = node.args

    # Combine positional-only and regular arguments
    all_positional_args = args.posonlyargs + args.args

    # Check defaults for positional arguments
    num_defaults = len(args.defaults)
    if num_defaults > 0:
        # Defaults apply to the last n arguments of the combined list
        num_args = len(all_positional_args)
        for i in range(num_args - num_defaults, num_args):
            arg = all_positional_args[i]
            if arg.arg not in ("self", "cls"):
                params_with_defaults.add(arg.arg)

    # Keyword-only args with defaults
    for i, arg in enumerate(args.kwonlyargs):
        if args.kw_defaults[i] is not None:
            params_with_defaults.add(arg.arg)

    return params_with_defaults
_process_optional_suffix 🔗
_process_optional_suffix(
    param_name: str,
    doc_type: str,
    params_with_defaults: set[str],
    optional_style: str,
) -> tuple[str, Optional[str]]

Summary

Process the ', optional' suffix based on the optional_style mode.

Parameters:

Name Type Description Default
param_name str

Name of the parameter.

required
doc_type str

Docstring type including potential ', optional' suffix.

required
params_with_defaults set[str]

Set of parameters that have default values.

required
optional_style str

The validation mode: 'silent', 'validate', or 'strict'.

required

Returns:

Type Description
tuple[str, Optional[str]]

Tuple of (cleaned_type, error_message).

Source code in src/docstring_format_checker/core.py
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
def _process_optional_suffix(
    self,
    param_name: str,
    doc_type: str,
    params_with_defaults: set[str],
    optional_style: str,
) -> tuple[str, Optional[str]]:
    """
    !!! note "Summary"
        Process the ', optional' suffix based on the optional_style mode.

    Params:
        param_name (str):
            Name of the parameter.
        doc_type (str):
            Docstring type including potential ', optional' suffix.
        params_with_defaults (set[str]):
            Set of parameters that have default values.
        optional_style (str):
            The validation mode: 'silent', 'validate', or 'strict'.

    Returns:
        (tuple[str, Optional[str]]):
            Tuple of (cleaned_type, error_message).
    """
    has_optional_suffix: bool = bool(re.search(r",\s*optional$", doc_type, flags=re.IGNORECASE))
    clean_type: str = re.sub(r",\s*optional$", "", doc_type, flags=re.IGNORECASE).strip()
    error_message: Optional[str] = None

    if optional_style == "validate":
        if has_optional_suffix and param_name not in params_with_defaults:
            error_message = f"Parameter '{param_name}' has ', optional' suffix but no default value in signature"
    elif optional_style == "strict":
        if param_name in params_with_defaults and not has_optional_suffix:
            error_message = (
                f"Parameter '{param_name}' has default value but missing ', optional' suffix in docstring"
            )
        elif has_optional_suffix and param_name not in params_with_defaults:
            error_message = f"Parameter '{param_name}' has ', optional' suffix but no default value in signature"

    return clean_type, error_message
_format_optional_errors 🔗
_format_optional_errors(errors: list[str]) -> str

Summary

Format multiple optional suffix validation errors.

Parameters:

Name Type Description Default
errors list[str]

List of error messages.

required

Returns:

Type Description
str

Formatted error message.

Source code in src/docstring_format_checker/core.py
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
def _format_optional_errors(self, errors: list[str]) -> str:
    """
    !!! note "Summary"
        Format multiple optional suffix validation errors.

    Params:
        errors (list[str]):
            List of error messages.

    Returns:
        (str):
            Formatted error message.
    """
    if len(errors) == 1:
        return errors[0]
    formatted_errors: str = "\n  - ".join([""] + errors)
    return f"Optional suffix validation errors:{formatted_errors}"
_format_type_mismatches 🔗
_format_type_mismatches(
    mismatches: list[tuple[str, str, str]],
) -> str

Summary

Format parameter type mismatches for error output.

Parameters:

Name Type Description Default
mismatches list[tuple[str, str, str]]

List of (param_name, sig_type, doc_type) tuples.

required

Returns:

Type Description
str

Formatted error message.

Source code in src/docstring_format_checker/core.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
def _format_type_mismatches(self, mismatches: list[tuple[str, str, str]]) -> str:
    """
    !!! note "Summary"
        Format parameter type mismatches for error output.

    Params:
        mismatches (list[tuple[str, str, str]]):
            List of (param_name, sig_type, doc_type) tuples.

    Returns:
        (str):
            Formatted error message.
    """
    mismatch_blocks: list[str] = []
    for name, sig_type, doc_type in mismatches:
        sig_type_clean: str = sig_type.replace("'", '"')
        doc_type_clean: str = doc_type.replace("'", '"')
        param_block: str = (
            f"""'{name}':\n    - signature: '{sig_type_clean}'\n    - docstring: '{doc_type_clean}'"""
        )
        mismatch_blocks.append(param_block)

    formatted_details: str = "\n  - ".join([""] + mismatch_blocks)
    return f"Parameter type mismatch:{formatted_details}"
_validate_param_types 🔗
_validate_param_types(
    docstring: str,
    node: Union[FunctionDef, AsyncFunctionDef],
) -> Optional[str]

Summary

Validate that parameter types in docstring match the signature.

Details

Implements three validation modes based on optional_style configuration:

  • "silent": Strip , optional from docstring types before comparison.
  • "validate": Error if , optional appears on required parameters.
  • "strict": Require , optional for parameters with defaults, error if on required parameters.

Parameters:

Name Type Description Default
docstring str

The docstring to validate.

required
node Union[FunctionDef, AsyncFunctionDef]

The function node with type annotations.

required

Returns:

Type Description
Optional[str]

Error message if validation fails, None otherwise.

Source code in src/docstring_format_checker/core.py
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
def _validate_param_types(
    self, docstring: str, node: Union[ast.FunctionDef, ast.AsyncFunctionDef]
) -> Optional[str]:
    """
    !!! note "Summary"
        Validate that parameter types in docstring match the signature.

    ???+ abstract "Details"
        Implements three validation modes based on `optional_style` configuration:

        - **`"silent"`**: Strip `, optional` from docstring types before comparison.
        - **`"validate"`**: Error if `, optional` appears on required parameters.
        - **`"strict"`**: Require `, optional` for parameters with defaults, error if on required parameters.

    Params:
        docstring (str):
            The docstring to validate.
        node (Union[ast.FunctionDef, ast.AsyncFunctionDef]):
            The function node with type annotations.

    Returns:
        (Optional[str]):
            Error message if validation fails, None otherwise.
    """
    # Extract types from both sources
    signature_types: dict[str, str] = self._extract_param_types(node)
    docstring_types_raw: dict[str, str] = self._extract_param_types_from_docstring(docstring)

    # Get parameters with default values
    params_with_defaults: set[str] = self._get_params_with_defaults(node)

    # Get all parameter names (excluding self/cls)
    all_params: list[str] = self._extract_all_params(node)

    # Get the optional_style mode
    optional_style: str = self.config.global_config.optional_style

    # Process docstring types based on optional_style mode
    docstring_types: dict[str, str] = {}
    optional_errors: list[str] = []

    for param_name, doc_type in docstring_types_raw.items():
        clean_type, error_message = self._process_optional_suffix(
            param_name, doc_type, params_with_defaults, optional_style
        )
        docstring_types[param_name] = clean_type
        if error_message:
            optional_errors.append(error_message)

    # Return optional_style errors first if any
    if optional_errors:
        return self._format_optional_errors(optional_errors)

    # Check for parameters documented with type in docstring but missing annotation in signature
    for param_name in all_params:
        if param_name in docstring_types and param_name not in signature_types:
            return f"Parameter '{param_name}' has type in docstring but no type annotation in signature"

    # Check for parameters with annotations but no type in docstring
    for param_name, sig_type in signature_types.items():
        if param_name not in docstring_types:
            return (
                f"Parameter '{param_name}' has type annotation '{sig_type}' in signature but no type in docstring"
            )

    # Compare types
    mismatches: list[tuple[str, str, str]] = self._compare_param_types(signature_types, docstring_types)

    if mismatches:
        return self._format_type_mismatches(mismatches)

    return None
_has_both_returns_and_yields 🔗
_has_both_returns_and_yields(docstring: str) -> bool

Summary

Check if docstring has both Returns and Yields sections.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
bool

True if the section exists, False otherwise.

Source code in src/docstring_format_checker/core.py
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
def _has_both_returns_and_yields(self, docstring: str) -> bool:
    """
    !!! note "Summary"
        Check if docstring has both Returns and Yields sections.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (bool):
            `True` if the section exists, `False` otherwise.
    """

    has_returns = bool(re.search(r"Returns:", docstring))
    has_yields = bool(re.search(r"Yields:", docstring))
    return has_returns and has_yields
_build_section_patterns 🔗
_build_section_patterns() -> list[tuple[str, str]]

Summary

Build regex patterns for detecting sections from configuration.

Returns:

Type Description
list[tuple[str, str]]

List of tuples containing (pattern, section_name).

Source code in src/docstring_format_checker/core.py
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
def _build_section_patterns(self) -> list[tuple[str, str]]:
    """
    !!! note "Summary"
        Build regex patterns for detecting sections from configuration.

    Returns:
        (list[tuple[str, str]]):
            List of tuples containing (pattern, section_name).
    """
    section_patterns: list[tuple[str, str]] = []
    # Sort sections that have an order, then append those that don't
    ordered_sections = sorted(
        [s for s in self.sections_config if s.order is not None],
        key=lambda x: x.order if x.order is not None else 0,
    )
    unordered_sections: list[SectionConfig] = [s for s in self.sections_config if s.order is None]

    for section in ordered_sections + unordered_sections:
        if (
            section.type == "free_text"
            and isinstance(section.admonition, str)
            and section.admonition
            and section.prefix
        ):
            pattern: str = (
                rf'{re.escape(section.prefix)}\s+{re.escape(section.admonition)}\s+".*{re.escape(section.name)}"'
            )
            section_patterns.append((pattern, section.name))
        elif section.name.lower() == "params":
            section_patterns.append((r"Params:", "Params"))
        elif section.name.lower() in ["returns", "return"]:
            section_patterns.append((r"Returns:", "Returns"))
        elif section.name.lower() in ["yields", "yield"]:
            section_patterns.append((r"Yields:", "Yields"))
        elif section.name.lower() in ["raises", "raise"]:
            section_patterns.append((r"Raises:", "Raises"))

    # Add default patterns for common sections
    default_patterns: list[tuple[str, str]] = [
        (r'!!! note "Summary"', "Summary"),
        (r'!!! details "Details"', "Details"),
        (r'\?\?\?\+ example "Examples"', "Examples"),
        (r'\?\?\?\+ success "Credit"', "Credit"),
        (r'\?\?\?\+ calculation "Equation"', "Equation"),
        (r'\?\?\?\+ info "Notes"', "Notes"),
        (r'\?\?\? question "References"', "References"),
        (r'\?\?\? tip "See Also"', "See Also"),
    ]

    return section_patterns + default_patterns
_find_sections_with_positions 🔗
_find_sections_with_positions(
    docstring: str, patterns: list[tuple[str, str]]
) -> list[tuple[int, str]]

Summary

Find all sections in docstring and their positions.

Parameters:

Name Type Description Default
docstring str

The docstring to search.

required
patterns list[tuple[str, str]]

List of (pattern, section_name) tuples to search for.

required

Returns:

Type Description
list[tuple[int, str]]

List of (position, section_name) tuples sorted by position.

Source code in src/docstring_format_checker/core.py
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
def _find_sections_with_positions(self, docstring: str, patterns: list[tuple[str, str]]) -> list[tuple[int, str]]:
    """
    !!! note "Summary"
        Find all sections in docstring and their positions.

    Params:
        docstring (str):
            The docstring to search.
        patterns (list[tuple[str, str]]):
            List of (pattern, section_name) tuples to search for.

    Returns:
        (list[tuple[int, str]]):
            List of (position, section_name) tuples sorted by position.
    """
    found_sections: list[tuple[int, str]] = []
    for pattern, section_name in patterns:
        match: Optional[re.Match[str]] = re.search(pattern, docstring, re.IGNORECASE)
        if match:
            found_sections.append((match.start(), section_name))

    # Sort by position in docstring
    found_sections.sort(key=lambda x: x[0])
    return found_sections
_build_expected_section_order 🔗
_build_expected_section_order() -> list[str]

Summary

Build the expected order of sections from configuration.

Returns:

Type Description
list[str]

List of section names in expected order.

Source code in src/docstring_format_checker/core.py
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
def _build_expected_section_order(self) -> list[str]:
    """
    !!! note "Summary"
        Build the expected order of sections from configuration.

    Returns:
        (list[str]):
            List of section names in expected order.
    """
    expected_order: list[str] = [
        s.name.title()
        for s in sorted(
            [s for s in self.sections_config if s.order is not None],
            key=lambda x: x.order if x.order is not None else 0,
        )
    ]
    expected_order.extend(
        [
            "Summary",
            "Details",
            "Examples",
            "Credit",
            "Equation",
            "Notes",
            "References",
            "See Also",
        ]
    )
    return expected_order
_check_section_order 🔗
_check_section_order(docstring: str) -> list[str]

Summary

Check that sections appear in the correct order.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
list[str]

A list of error messages, if any.

Source code in src/docstring_format_checker/core.py
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
def _check_section_order(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that sections appear in the correct order.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (list[str]):
            A list of error messages, if any.
    """
    # Build patterns and find sections
    patterns = self._build_section_patterns()
    found_sections = self._find_sections_with_positions(docstring, patterns)
    expected_order = self._build_expected_section_order()

    # Check order matches expected order
    errors: list[str] = []
    last_expected_index = -1
    for _, section_name in found_sections:
        try:
            current_index: int = expected_order.index(section_name)
            if current_index < last_expected_index:
                errors.append(f"Section '{section_name}' appears out of order")
            last_expected_index: int = current_index
        except ValueError:
            # Section not in expected order list - might be OK
            pass

    return errors
_normalize_section_name 🔗
_normalize_section_name(section_name: str) -> str

Summary

Normalize section name by removing colons and whitespace.

Parameters:

Name Type Description Default
section_name str

The raw section name to normalize.

required

Returns:

Type Description
str

The normalized section name.

Source code in src/docstring_format_checker/core.py
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
def _normalize_section_name(self, section_name: str) -> str:
    """
    !!! note "Summary"
        Normalize section name by removing colons and whitespace.

    Params:
        section_name (str):
            The raw section name to normalize.

    Returns:
        (str):
            The normalized section name.
    """
    return section_name.lower().strip().rstrip(":")
_is_valid_section_name 🔗
_is_valid_section_name(section_name: str) -> bool

Summary

Check if section name is valid.

Details

Filters out empty names, code block markers, and special characters.

Parameters:

Name Type Description Default
section_name str

The section name to validate.

required

Returns:

Type Description
bool

True if the section name is valid, False otherwise.

Source code in src/docstring_format_checker/core.py
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
def _is_valid_section_name(self, section_name: str) -> bool:
    """
    !!! note "Summary"
        Check if section name is valid.

    !!! abstract "Details"
        Filters out empty names, code block markers, and special characters.

    Params:
        section_name (str):
            The section name to validate.

    Returns:
        (bool):
            True if the section name is valid, False otherwise.
    """
    # Skip empty matches or common docstring content
    if not section_name or section_name in ["", "py", "python", "sh", "shell"]:
        return False

    # Skip code blocks and inline code
    if any(char in section_name for char in ["`", ".", "/", "\\"]):
        return False

    return True
_extract_section_names_from_docstring 🔗
_extract_section_names_from_docstring(
    docstring: str,
) -> set[str]

Summary

Extract all section names found in docstring.

Parameters:

Name Type Description Default
docstring str

The docstring to extract section names from.

required

Returns:

Type Description
set[str]

A set of normalized section names found in the docstring.

Source code in src/docstring_format_checker/core.py
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
def _extract_section_names_from_docstring(self, docstring: str) -> set[str]:
    """
    !!! note "Summary"
        Extract all section names found in docstring.

    Params:
        docstring (str):
            The docstring to extract section names from.

    Returns:
        (set[str]):
            A set of normalized section names found in the docstring.
    """
    # Common patterns for different section types
    section_patterns: list[tuple[str, str]] = [
        # Standard sections with colons (but not inside quotes)
        (r"^(\w+):\s*", "colon"),
        # Admonition sections with various prefixes
        (r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\"", "admonition"),
    ]

    found_sections: set[str] = set()

    for pattern, pattern_type in section_patterns:
        matches: Iterator[re.Match[str]] = re.finditer(pattern, docstring, re.IGNORECASE | re.MULTILINE)
        for match in matches:
            section_name: str = self._normalize_section_name(match.group(1))

            if self._is_valid_section_name(section_name):
                found_sections.add(section_name)

    return found_sections
_check_undefined_sections 🔗
_check_undefined_sections(docstring: str) -> list[str]

Summary

Check for sections in docstring that are not defined in configuration.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
list[str]

A list of error messages for undefined sections.

Source code in src/docstring_format_checker/core.py
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
def _check_undefined_sections(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check for sections in docstring that are not defined in configuration.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (list[str]):
            A list of error messages for undefined sections.
    """
    errors: list[str] = []

    # Get all configured section names (case-insensitive)
    configured_sections: set[str] = {section.name.lower() for section in self.sections_config}

    # Extract all section names from docstring
    found_sections: set[str] = self._extract_section_names_from_docstring(docstring)

    # Check which found sections are not configured
    for section_name in found_sections:
        if section_name not in configured_sections:
            errors.append(f"Section '{section_name}' found in docstring but not defined in configuration")

    return errors
_build_admonition_mapping 🔗
_build_admonition_mapping() -> dict[str, str]

Summary

Build mapping of section names to expected admonitions.

Returns:

Type Description
dict[str, str]

Dictionary mapping section name to admonition type.

Source code in src/docstring_format_checker/core.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
def _build_admonition_mapping(self) -> dict[str, str]:
    """
    !!! note "Summary"
        Build mapping of section names to expected admonitions.

    Returns:
        (dict[str, str]):
            Dictionary mapping section name to admonition type.
    """
    section_admonitions: dict[str, str] = {}
    for section in self.sections_config:
        if section.type == "free_text" and isinstance(section.admonition, str) and section.admonition:
            section_admonitions[section.name.lower()] = section.admonition.lower()
    return section_admonitions
_validate_single_admonition 🔗
_validate_single_admonition(
    match: Match[str], section_admonitions: dict[str, str]
) -> Optional[str]

Summary

Validate a single admonition match against configuration.

Parameters:

Name Type Description Default
match Match[str]

The regex match for an admonition section.

required
section_admonitions dict[str, str]

Mapping of section names to expected admonitions.

required

Returns:

Type Description
Optional[str]

Error message if validation fails, None otherwise.

Source code in src/docstring_format_checker/core.py
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
def _validate_single_admonition(self, match: re.Match[str], section_admonitions: dict[str, str]) -> Optional[str]:
    """
    !!! note "Summary"
        Validate a single admonition match against configuration.

    Params:
        match (re.Match[str]):
            The regex match for an admonition section.
        section_admonitions (dict[str, str]):
            Mapping of section names to expected admonitions.

    Returns:
        (Optional[str]):
            Error message if validation fails, None otherwise.
    """
    actual_admonition: str = match.group(1).lower()
    section_title: str = match.group(2)
    section_title_lower: str = section_title.lower()

    # Check if this section is configured with a specific admonition
    if section_title_lower in section_admonitions:
        expected_admonition: str = section_admonitions[section_title_lower]
        if actual_admonition != expected_admonition:
            return (
                f"Section '{section_title}' has incorrect admonition '{actual_admonition}', "
                f"expected '{expected_admonition}'"
            )

    # Check if section shouldn't have admonition but does
    section_config: Optional[SectionConfig] = next(
        (s for s in self.sections_config if s.name.lower() == section_title_lower), None
    )
    if section_config and section_config.admonition is False:
        return f"Section '{section_title}' is configured as non-admonition but found as admonition"

    return None
_check_admonition_values 🔗
_check_admonition_values(docstring: str) -> list[str]

Summary

Check that admonition values in docstring match configuration.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
list[str]

A list of error messages for mismatched admonitions.

Source code in src/docstring_format_checker/core.py
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
def _check_admonition_values(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that admonition values in docstring match configuration.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (list[str]):
            A list of error messages for mismatched admonitions.
    """
    errors: list[str] = []

    # Build admonition mapping
    section_admonitions = self._build_admonition_mapping()

    # Pattern to find all admonition sections
    admonition_pattern = r"(?:\?\?\?[+]?|!!!)\s+(\w+)\s+\"([^\"]+)\""
    matches: Iterator[re.Match[str]] = re.finditer(admonition_pattern, docstring, re.IGNORECASE)

    # Validate each admonition
    for match in matches:
        error = self._validate_single_admonition(match, section_admonitions)
        if error:
            errors.append(error)

    return errors
_validate_admonition_has_no_colon 🔗
_validate_admonition_has_no_colon(
    match: Match[str],
) -> Optional[str]

Summary

Validate that a single admonition section does not have a colon.

Parameters:

Name Type Description Default
match Match[str]

The regex match for an admonition section.

required

Returns:

Type Description
Optional[str]

An error message if colon found, None otherwise.

Source code in src/docstring_format_checker/core.py
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
def _validate_admonition_has_no_colon(self, match: re.Match[str]) -> Optional[str]:
    """
    !!! note "Summary"
        Validate that a single admonition section does not have a colon.

    Params:
        match (re.Match[str]):
            The regex match for an admonition section.

    Returns:
        (Optional[str]):
            An error message if colon found, None otherwise.
    """

    section_title: str = match.group(1)
    has_colon: bool = section_title.endswith(":")
    section_title_clean: str = section_title.rstrip(":")
    section_title_lower: str = section_title_clean.lower()

    # Find config for this section
    section_config: Optional[SectionConfig] = next(
        (s for s in self.sections_config if s.name.lower() == section_title_lower), None
    )

    if section_config and isinstance(section_config.admonition, str) and section_config.admonition:
        if has_colon:
            return (
                f"Section '{section_title_clean}' is an admonition, therefore it should not end with ':', "
                f"see: '{match.group(0)}'"
            )

    return None
_check_admonition_colon_usage 🔗
_check_admonition_colon_usage(docstring: str) -> list[str]

Summary

Check that admonition sections don't end with colon.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
list[str]

A list of error messages.

Source code in src/docstring_format_checker/core.py
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
def _check_admonition_colon_usage(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that admonition sections don't end with colon.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (list[str]):
            A list of error messages.
    """

    errors: list[str] = []
    admonition_pattern = r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\""
    matches: Iterator[re.Match[str]] = re.finditer(admonition_pattern, docstring, re.IGNORECASE)

    for match in matches:
        error: Optional[str] = self._validate_admonition_has_no_colon(match)
        if error:
            errors.append(error)

    return errors
_validate_non_admonition_has_colon 🔗
_validate_non_admonition_has_colon(
    line: str, pattern: str
) -> Optional[str]

Summary

Validate that a single line has colon if it's a non-admonition section.

Parameters:

Name Type Description Default
line str

The line to check.

required
pattern str

The regex pattern to match.

required

Returns:

Type Description
Optional[str]

An error message if colon missing, None otherwise.

Source code in src/docstring_format_checker/core.py
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
def _validate_non_admonition_has_colon(self, line: str, pattern: str) -> Optional[str]:
    """
    !!! note "Summary"
        Validate that a single line has colon if it's a non-admonition section.

    Params:
        line (str):
            The line to check.
        pattern (str):
            The regex pattern to match.

    Returns:
        (Optional[str]):
            An error message if colon missing, None otherwise.
    """

    match: Optional[re.Match[str]] = re.match(pattern, line)
    if not match:
        return None

    section_name: str = match.group(1)
    has_colon: bool = match.group(2) == ":"

    # Find config for this section
    section_config: Optional[SectionConfig] = next(
        (s for s in self.sections_config if s.name.lower() == section_name.lower()), None
    )

    if section_config and section_config.admonition is False:
        if not has_colon:
            return f"Section '{section_name}' is non-admonition, therefore it must end with ':', " f"see: '{line}'"

    return None
_check_non_admonition_colon_usage 🔗
_check_non_admonition_colon_usage(
    docstring: str,
) -> list[str]

Summary

Check that non-admonition sections end with colon.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
list[str]

A list of error messages.

Source code in src/docstring_format_checker/core.py
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
def _check_non_admonition_colon_usage(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that non-admonition sections end with colon.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (list[str]):
            A list of error messages.
    """

    errors: list[str] = []
    non_admonition_pattern = r"^(\w+)(:?)$"

    for line in docstring.split("\n"):
        line: str = line.strip()
        error: Optional[str] = self._validate_non_admonition_has_colon(line, non_admonition_pattern)
        if error:
            errors.append(error)

    return errors
_check_colon_usage 🔗
_check_colon_usage(docstring: str) -> list[str]

Summary

Check that colons are used correctly for admonition vs non-admonition sections.

Parameters:

Name Type Description Default
docstring str

The docstring to check.

required

Returns:

Type Description
list[str]

A list of error messages.

Source code in src/docstring_format_checker/core.py
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
def _check_colon_usage(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that colons are used correctly for admonition vs non-admonition sections.

    Params:
        docstring (str):
            The docstring to check.

    Returns:
        (list[str]):
            A list of error messages.
    """

    errors: list[str] = []

    # Check admonition sections (should not end with colon)
    errors.extend(self._check_admonition_colon_usage(docstring))

    # Check non-admonition sections (should end with colon)
    errors.extend(self._check_non_admonition_colon_usage(docstring))

    return errors
_check_title_case_sections 🔗
_check_title_case_sections(docstring: str) -> list[str]

Summary

Check that non-admonition sections are single word, title case, and match config name.

Source code in src/docstring_format_checker/core.py
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
def _check_title_case_sections(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that non-admonition sections are single word, title case, and match config name.
    """

    errors: list[str] = []

    # Pattern to find section headers (single word followed by optional colon)
    section_pattern = r"^(\w+):?$"

    for line in docstring.split("\n"):
        line: str = line.strip()
        match: Optional[re.Match[str]] = re.match(section_pattern, line)
        if match:
            section_word: str = match.group(1)
            section_name_lower: str = section_word.lower()

            # Check if this is a configured non-admonition section
            section_config: Optional[SectionConfig] = next(
                (s for s in self.sections_config if s.name.lower() == section_name_lower), None
            )
            if section_config and section_config.admonition is False:
                # Check if it's title case
                expected_title_case: str = section_config.name.title()
                if section_word != expected_title_case:
                    errors.append(
                        f"Section '{section_name_lower}' must be in title case as '{expected_title_case}', "
                        f"found: '{section_word}'"
                    )

    return errors
_check_parentheses_validation 🔗
_check_parentheses_validation(docstring: str) -> list[str]

Summary

Check that list_type and list_name_and_type sections have proper parentheses.

Source code in src/docstring_format_checker/core.py
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
def _check_parentheses_validation(self, docstring: str) -> list[str]:
    """
    !!! note "Summary"
        Check that list_type and list_name_and_type sections have proper parentheses.
    """

    errors: list[str] = []

    # Get sections that require parentheses
    parentheses_sections: list[SectionConfig] = [
        s for s in self.sections_config if s.type in ["list_type", "list_name_and_type"]
    ]

    if not parentheses_sections:
        return errors

    # Process each line in the docstring
    lines: list[str] = docstring.split("\n")
    current_section: Optional[SectionConfig] = None
    type_line_indent: Optional[int] = None

    for line in lines:
        stripped_line: str = line.strip()

        # Check for any section header (to properly transition out of current section)
        section_detected: bool = self._detect_any_section_header(stripped_line, line)
        if section_detected:
            # Check if it's a parentheses-required section
            new_section: Optional[SectionConfig] = self._detect_section_header(
                stripped_line, line, parentheses_sections
            )
            current_section = new_section  # None if not parentheses-required
            type_line_indent = None
            continue

        # Process content lines within parentheses-required sections
        if current_section and self._is_content_line(stripped_line):
            line_errors: list[str]
            new_indent: Optional[int]
            line_errors, new_indent = self._validate_parentheses_line(
                line, stripped_line, current_section, type_line_indent
            )
            errors.extend(line_errors)
            if new_indent is not None:
                type_line_indent = new_indent

    return errors
_detect_any_section_header 🔗
_detect_any_section_header(
    stripped_line: str, full_line: str
) -> bool

Summary

Detect any section header (for section transitions).

Parameters:

Name Type Description Default
stripped_line str

The stripped line content.

required
full_line str

The full line with indentation.

required

Returns:

Type Description
bool

True if line is a section header, False otherwise.

Source code in src/docstring_format_checker/core.py
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
def _detect_any_section_header(self, stripped_line: str, full_line: str) -> bool:
    """
    !!! note "Summary"
        Detect any section header (for section transitions).

    Params:
        stripped_line (str):
            The stripped line content.
        full_line (str):
            The full line with indentation.

    Returns:
        (bool):
            True if line is a section header, False otherwise.
    """
    # Admonition sections
    admonition_match: Optional[re.Match[str]] = re.match(
        r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\"", stripped_line, re.IGNORECASE
    )
    if admonition_match:
        section_name: str = admonition_match.group(1)
        # Check if it's a known section
        return any(s.name.lower() == section_name.lower() for s in self.sections_config)

    # Non-admonition sections (must not be indented)
    if not full_line.startswith((" ", "\t")):
        # Match section names (can include spaces) followed by an optional colon
        simple_section_match: Optional[re.Match[str]] = re.match(r"^([A-Z][\w\s]+):?$", stripped_line)
        if simple_section_match:
            section_name: str = simple_section_match.group(1).strip()
            # Check if it's a known section
            return any(s.name.lower() == section_name.lower() for s in self.sections_config)

    return False
_detect_section_header 🔗
_detect_section_header(
    stripped_line: str,
    full_line: str,
    parentheses_sections: list[SectionConfig],
) -> Optional[SectionConfig]

Summary

Detect section headers and return matching section config.

Parameters:

Name Type Description Default
stripped_line str

The stripped line content.

required
full_line str

The full line with indentation.

required
parentheses_sections list[SectionConfig]

List of sections requiring parentheses validation.

required

Returns:

Type Description
Optional[SectionConfig]

Matching section config or None if not found.

Source code in src/docstring_format_checker/core.py
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
def _detect_section_header(
    self, stripped_line: str, full_line: str, parentheses_sections: list[SectionConfig]
) -> Optional[SectionConfig]:
    """
    !!! note "Summary"
        Detect section headers and return matching section config.

    Params:
        stripped_line (str):
            The stripped line content.
        full_line (str):
            The full line with indentation.
        parentheses_sections (list[SectionConfig]):
            List of sections requiring parentheses validation.

    Returns:
        (Optional[SectionConfig]):
            Matching section config or None if not found.
    """
    # Admonition sections
    admonition_match: Optional[re.Match[str]] = re.match(
        r"(?:\?\?\?[+]?|!!!)\s+\w+\s+\"([^\"]+)\"", stripped_line, re.IGNORECASE
    )
    if admonition_match:
        section_name: str = admonition_match.group(1)
        return next((s for s in parentheses_sections if s.name.lower() == section_name.lower()), None)

    # Non-admonition sections (must not be indented)
    if not full_line.startswith((" ", "\t")):
        # Match section names (can include spaces) followed by an optional colon
        simple_section_match: Optional[re.Match[str]] = re.match(r"^([A-Z][\w\s]+):?$", stripped_line)
        if simple_section_match:
            section_name: str = simple_section_match.group(1).strip()
            # Check if it's a known section
            potential_section: Optional[SectionConfig] = next(
                (s for s in self.sections_config if s.name.lower() == section_name.lower()), None
            )
            if potential_section:
                return next((s for s in parentheses_sections if s.name.lower() == section_name.lower()), None)

    return None
_is_content_line 🔗
_is_content_line(stripped_line: str) -> bool

Summary

Check if line is content that needs validation.

Parameters:

Name Type Description Default
stripped_line str

The stripped line content.

required

Returns:

Type Description
bool

True if line is content requiring validation, False otherwise.

Source code in src/docstring_format_checker/core.py
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
def _is_content_line(self, stripped_line: str) -> bool:
    """
    !!! note "Summary"
        Check if line is content that needs validation.

    Params:
        stripped_line (str):
            The stripped line content.

    Returns:
        (bool):
            True if line is content requiring validation, False otherwise.
    """
    return bool(stripped_line) and not stripped_line.startswith(("!", "?", "#")) and ":" in stripped_line
_is_description_line 🔗
_is_description_line(stripped_line: str) -> bool

Summary

Check if line is a description rather than a type definition.

Parameters:

Name Type Description Default
stripped_line str

The stripped line content.

required

Returns:

Type Description
bool

True if line is a description, False otherwise.

Source code in src/docstring_format_checker/core.py
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
def _is_description_line(self, stripped_line: str) -> bool:
    """
    !!! note "Summary"
        Check if line is a description rather than a type definition.

    Params:
        stripped_line (str):
            The stripped line content.

    Returns:
        (bool):
            True if line is a description, False otherwise.
    """
    description_prefixes: list[str] = [
        "default:",
        "note:",
        "example:",
        "see:",
        "warning:",
        "info:",
        "tip:",
        "returns:",
    ]

    return (
        any(stripped_line.lower().startswith(prefix) for prefix in description_prefixes)
        or "Default:" in stripped_line
        or "Output format:" in stripped_line
        or "Show examples:" in stripped_line
        or "Example code:" in stripped_line
        or stripped_line.strip().startswith(("-", "*", "•", "+"))
        or stripped_line.startswith(">>>")  # Doctest examples
    )
_validate_parentheses_line 🔗
_validate_parentheses_line(
    full_line: str,
    stripped_line: str,
    current_section: SectionConfig,
    type_line_indent: Optional[int],
) -> tuple[list[str], Optional[int]]

Summary

Validate a single line for parentheses requirements.

Parameters:

Name Type Description Default
full_line str

The full line with indentation.

required
stripped_line str

The stripped line content.

required
current_section SectionConfig

The current section being validated.

required
type_line_indent Optional[int]

The indentation level of type definitions.

required

Returns:

Type Description
tuple[list[str], Optional[int]]

Tuple of error messages and updated type line indent.

Source code in src/docstring_format_checker/core.py
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
def _validate_parentheses_line(
    self, full_line: str, stripped_line: str, current_section: SectionConfig, type_line_indent: Optional[int]
) -> tuple[list[str], Optional[int]]:
    """
    !!! note "Summary"
        Validate a single line for parentheses requirements.

    Params:
        full_line (str):
            The full line with indentation.
        stripped_line (str):
            The stripped line content.
        current_section (SectionConfig):
            The current section being validated.
        type_line_indent (Optional[int]):
            The indentation level of type definitions.

    Returns:
        (tuple[list[str], Optional[int]]):
            Tuple of error messages and updated type line indent.
    """
    errors: list[str] = []
    new_indent: Optional[int] = None
    current_indent: int = len(full_line) - len(full_line.lstrip())

    # Skip description lines
    if self._is_description_line(stripped_line):
        return errors, type_line_indent

    if current_section.type == "list_type":
        errors, new_indent = self._validate_list_type_line(
            stripped_line, current_indent, type_line_indent, current_section
        )
    elif current_section.type == "list_name_and_type":
        errors, new_indent = self._validate_list_name_and_type_line(
            stripped_line, current_indent, type_line_indent, current_section
        )

    return errors, new_indent if new_indent is not None else type_line_indent
_validate_list_type_line 🔗
_validate_list_type_line(
    stripped_line: str,
    current_indent: int,
    type_line_indent: Optional[int],
    current_section: SectionConfig,
) -> tuple[list[str], Optional[int]]

Summary

Validate list_type section lines.

Parameters:

Name Type Description Default
stripped_line str

The stripped line content.

required
current_indent int

The current line's indentation level.

required
type_line_indent Optional[int]

The indentation level of type definitions.

required
current_section SectionConfig

The current section being validated.

required

Returns:

Type Description
tuple[list[str], Optional[int]]

Tuple of error messages and updated type line indent.

Source code in src/docstring_format_checker/core.py
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
def _validate_list_type_line(
    self, stripped_line: str, current_indent: int, type_line_indent: Optional[int], current_section: SectionConfig
) -> tuple[list[str], Optional[int]]:
    """
    !!! note "Summary"
        Validate list_type section lines.

    Params:
        stripped_line (str):
            The stripped line content.
        current_indent (int):
            The current line's indentation level.
        type_line_indent (Optional[int]):
            The indentation level of type definitions.
        current_section (SectionConfig):
            The current section being validated.

    Returns:
        (tuple[list[str], Optional[int]]):
            Tuple of error messages and updated type line indent.
    """
    errors: list[str] = []

    # Check for valid type definition format
    if re.search(r"^\s*\([^)]+\):", stripped_line):
        return errors, current_indent

    # Handle lines without proper format
    if type_line_indent is None or current_indent > type_line_indent:
        # Allow as possible description
        return errors, None

    # This should be a type definition but lacks proper format
    errors.append(
        f"Section '{current_section.name}' (type: '{current_section.type}') requires "
        f"parenthesized types, see: '{stripped_line}'"
    )
    return errors, None
_validate_list_name_and_type_line 🔗
_validate_list_name_and_type_line(
    stripped_line: str,
    current_indent: int,
    type_line_indent: Optional[int],
    current_section: SectionConfig,
) -> tuple[list[str], Optional[int]]

Summary

Validate list_name_and_type section lines.

Parameters:

Name Type Description Default
stripped_line str

The stripped line content.

required
current_indent int

The current line's indentation level.

required
type_line_indent Optional[int]

The indentation level of type definitions.

required
current_section SectionConfig

The current section being validated.

required

Returns:

Type Description
tuple[list[str], Optional[int]]

Tuple of error messages and updated type line indent.

Source code in src/docstring_format_checker/core.py
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
def _validate_list_name_and_type_line(
    self, stripped_line: str, current_indent: int, type_line_indent: Optional[int], current_section: SectionConfig
) -> tuple[list[str], Optional[int]]:
    """
    !!! note "Summary"
        Validate list_name_and_type section lines.

    Params:
        stripped_line (str):
            The stripped line content.
        current_indent (int):
            The current line's indentation level.
        type_line_indent (Optional[int]):
            The indentation level of type definitions.
        current_section (SectionConfig):
            The current section being validated.

    Returns:
        (tuple[list[str], Optional[int]]):
            Tuple of error messages and updated type line indent.
    """
    errors: list[str] = []

    # Check for valid parameter definition format
    if re.search(r"\([^)]+\):", stripped_line):
        return errors, current_indent

    # Check if this is likely a description line
    colon_part: str = stripped_line.split(":")[0].strip()

    # Skip description-like content
    if any(word in colon_part.lower() for word in ["default", "output", "format", "show", "example"]):
        return errors, None

    # Skip if more indented than parameter definition (description line)
    if type_line_indent is not None and current_indent > type_line_indent:
        return errors, None

    # Skip if too many words before colon (likely description)
    words_before_colon: list[str] = colon_part.split()
    if len(words_before_colon) > 2:
        return errors, None

    # Flag potential parameter definitions without proper format
    if not stripped_line.strip().startswith("#"):
        errors.append(
            f"Section '{current_section.name}' (type: '{current_section.type}') requires "
            f"parenthesized types, see: '{stripped_line}'"
        )

    return errors, None