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

from __future__ import annotations

import inspect
from collections import defaultdict
from contextlib import suppress
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING, Any, Callable, Union, cast

from _griffe.c3linear import c3linear_merge
from _griffe.docstrings.parsers import DocstringStyle, parse
from _griffe.enumerations import Kind, ParameterKind, Parser
from _griffe.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError, NameResolutionError
from _griffe.expressions import ExprCall, ExprName
from _griffe.logger import logger
from _griffe.mixins import ObjectAliasMixin

if TYPE_CHECKING:
    from collections.abc import Sequence

    from _griffe.collections import LinesCollection, ModulesCollection
    from _griffe.docstrings.models import DocstringSection
    from _griffe.expressions import Expr

from functools import cached_property


class Decorator:
    """This class represents decorators."""

    def __init__(self, value: str | Expr, *, lineno: int | None, endlineno: int | None) -> None:
        """Initialize the decorator.

        Parameters:
            value: The decorator code.
            lineno: The starting line number.
            endlineno: The ending line number.
        """
        self.value: str | Expr = value
        """The decorator value (as a Griffe expression or string)."""
        self.lineno: int | None = lineno
        """The starting line number of the decorator."""
        self.endlineno: int | None = endlineno
        """The ending line number of the decorator."""

    @property
    def callable_path(self) -> str:
        """The path of the callable used as decorator."""
        value = self.value.function if isinstance(self.value, ExprCall) else self.value
        return value if isinstance(value, str) else value.canonical_path

    def as_dict(self, **kwargs: Any) -> dict[str, Any]:  # noqa: ARG002
        """Return this decorator's data as a dictionary.

        Parameters:
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        return {
            "value": self.value,
            "lineno": self.lineno,
            "endlineno": self.endlineno,
        }


class Docstring:
    """This class represents docstrings."""

    def __init__(
        self,
        value: str,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
        parent: Object | None = None,
        parser: DocstringStyle | Parser | None = None,
        parser_options: dict[str, Any] | None = None,
    ) -> None:
        """Initialize the docstring.

        Parameters:
            value: The docstring value.
            lineno: The starting line number.
            endlineno: The ending line number.
            parent: The parent object on which this docstring is attached.
            parser: The docstring parser to use. By default, no parsing is done.
            parser_options: Additional docstring parsing options.
        """
        self.value: str = inspect.cleandoc(value.rstrip())
        """The original value of the docstring, cleaned by `inspect.cleandoc`.

        See also: [`source`][griffe.Docstring.source].
        """

        self.lineno: int | None = lineno
        """The starting line number of the docstring.

        See also: [`endlineno`][griffe.Docstring.endlineno]."""

        self.endlineno: int | None = endlineno
        """The ending line number of the docstring.

        See also: [`lineno`][griffe.Docstring.lineno]."""

        self.parent: Object | None = parent
        """The object this docstring is attached to."""

        self.parser: DocstringStyle | Parser | None = parser
        """The selected docstring parser.

        See also: [`parser_options`][griffe.Docstring.parser_options],
        [`parse`][griffe.Docstring.parse].
        """

        self.parser_options: dict[str, Any] = parser_options or {}
        """The configured parsing options.

        See also: [`parser`][griffe.Docstring.parser],
        [`parse`][griffe.Docstring.parse].
        """

    @property
    def lines(self) -> list[str]:
        """The lines of the docstring.

        See also: [`source`][griffe.Docstring.source].
        """
        return self.value.split("\n")

    @property
    def source(self) -> str:
        """The original, uncleaned value of the docstring as written in the source.

        See also: [`value`][griffe.Docstring.value].
        """
        if self.parent is None:
            raise ValueError("Cannot get original docstring without parent object")
        if isinstance(self.parent.filepath, list):
            raise ValueError("Cannot get original docstring for namespace package")  # noqa: TRY004
        if self.lineno is None or self.endlineno is None:
            raise ValueError("Cannot get original docstring without line numbers")
        return "\n".join(self.parent.lines_collection[self.parent.filepath][self.lineno - 1 : self.endlineno])

    @cached_property
    def parsed(self) -> list[DocstringSection]:
        """The docstring sections, parsed into structured data."""
        return self.parse()

    def parse(
        self,
        parser: DocstringStyle | Parser | None = None,
        **options: Any,
    ) -> list[DocstringSection]:
        """Parse the docstring into structured data.

        See also: [`parser`][griffe.Docstring.parser],
        [`parser_options`][griffe.Docstring.parser_options].

        Parameters:
            parser: The docstring parser to use.
                In order: use the given parser, or the self parser, or no parser (return a single text section).
            **options: Additional docstring parsing options.

        Returns:
            The parsed docstring as a list of sections.
        """
        return parse(self, parser or self.parser, **(options or self.parser_options))

    def as_dict(
        self,
        *,
        full: bool = False,
        **kwargs: Any,  # noqa: ARG002
    ) -> dict[str, Any]:
        """Return this docstring's data as a dictionary.

        Parameters:
            full: Whether to return full info, or just base info.
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base: dict[str, Any] = {
            "value": self.value,
            "lineno": self.lineno,
            "endlineno": self.endlineno,
        }
        if full:
            base["parsed"] = self.parsed
        return base


class Parameter:
    """This class represent a function parameter.

    See also: [`Parameters`][griffe.Parameters].
    """

    def __init__(
        self,
        name: str,
        *,
        annotation: str | Expr | None = None,
        kind: ParameterKind | None = None,
        default: str | Expr | None = None,
        docstring: Docstring | None = None,
    ) -> None:
        """Initialize the parameter.

        Parameters:
            name: The parameter name, without leading stars (`*` or `**`).
            annotation: The parameter annotation, if any.
            kind: The parameter kind.
            default: The parameter default, if any.
            docstring: The parameter docstring.
        """
        self.name: str = name
        """The parameter name."""
        self.annotation: str | Expr | None = annotation
        """The parameter type annotation."""
        self.kind: ParameterKind | None = kind
        """The parameter kind."""
        self.default: str | Expr | None = default
        """The parameter default value."""
        self.docstring: Docstring | None = docstring
        """The parameter docstring."""
        # The parent function is set in `Function.__init__`,
        # when the parameters are assigned to the function.
        self.function: Function | None = None
        """The parent function of the parameter."""

    def __str__(self) -> str:
        param = f"{self.name}: {self.annotation} = {self.default}"
        if self.kind:
            return f"[{self.kind.value}] {param}"
        return param

    def __repr__(self) -> str:
        return f"Parameter(name={self.name!r}, annotation={self.annotation!r}, kind={self.kind!r}, default={self.default!r})"

    def __eq__(self, value: object, /) -> bool:
        """Parameters are equal if all their attributes except `docstring` and `function` are equal."""
        if not isinstance(value, Parameter):
            return NotImplemented
        return (
            self.name == value.name
            and self.annotation == value.annotation
            and self.kind == value.kind
            and self.default == value.default
        )

    @property
    def required(self) -> bool:
        """Whether this parameter is required."""
        return self.default is None

    def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]:  # noqa: ARG002
        """Return this parameter's data as a dictionary.

        Parameters:
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base: dict[str, Any] = {
            "name": self.name,
            "annotation": self.annotation,
            "kind": self.kind,
            "default": self.default,
        }
        if self.docstring:
            base["docstring"] = self.docstring.as_dict(full=full)
        return base


class Parameters:
    """This class is a container for parameters.

    It allows to get parameters using their position (index) or their name:

    ```pycon
    >>> parameters = Parameters(Parameter("hello"))
    >>> parameters[0] is parameters["hello"]
    True
    ```

    See also: [`Parameter`][griffe.Parameter].
    """

    def __init__(self, *parameters: Parameter) -> None:
        """Initialize the parameters container.

        Parameters:
            *parameters: The initial parameters to add to the container.
        """
        self._params: list[Parameter] = list(parameters)

    def __repr__(self) -> str:
        return f"Parameters({', '.join(repr(param) for param in self._params)})"

    def __getitem__(self, name_or_index: int | str) -> Parameter:
        """Get a parameter by index or name."""
        if isinstance(name_or_index, int):
            return self._params[name_or_index]
        name = name_or_index.lstrip("*")
        try:
            return next(param for param in self._params if param.name == name)
        except StopIteration as error:
            raise KeyError(f"parameter {name_or_index} not found") from error

    def __setitem__(self, name_or_index: int | str, parameter: Parameter) -> None:
        """Set a parameter by index or name."""
        if isinstance(name_or_index, int):
            self._params[name_or_index] = parameter
        else:
            name = name_or_index.lstrip("*")
            try:
                index = next(idx for idx, param in enumerate(self._params) if param.name == name)
            except StopIteration:
                self._params.append(parameter)
            else:
                self._params[index] = parameter

    def __delitem__(self, name_or_index: int | str) -> None:
        """Delete a parameter by index or name."""
        if isinstance(name_or_index, int):
            del self._params[name_or_index]
        else:
            name = name_or_index.lstrip("*")
            try:
                index = next(idx for idx, param in enumerate(self._params) if param.name == name)
            except StopIteration as error:
                raise KeyError(f"parameter {name_or_index} not found") from error
            del self._params[index]

    def __len__(self):
        """The number of parameters."""
        return len(self._params)

    def __iter__(self):
        """Iterate over the parameters, in order."""
        return iter(self._params)

    def __contains__(self, param_name: str):
        """Whether a parameter with the given name is present."""
        try:
            next(param for param in self._params if param.name == param_name.lstrip("*"))
        except StopIteration:
            return False
        return True

    def add(self, parameter: Parameter) -> None:
        """Add a parameter to the container.

        Parameters:
            parameter: The function parameter to add.

        Raises:
            ValueError: When a parameter with the same name is already present.
        """
        if parameter.name in self:
            raise ValueError(f"parameter {parameter.name} already present")
        self._params.append(parameter)


class Object(ObjectAliasMixin):
    """An abstract class representing a Python object."""

    kind: Kind
    """The object kind."""
    is_alias: bool = False
    """Always false for objects."""
    is_collection: bool = False
    """Always false for objects."""
    inherited: bool = False
    """Always false for objects.

    Only aliases can be marked as inherited.
    """

    def __init__(
        self,
        name: str,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
        runtime: bool = True,
        docstring: Docstring | None = None,
        parent: Module | Class | None = None,
        lines_collection: LinesCollection | None = None,
        modules_collection: ModulesCollection | None = None,
    ) -> None:
        """Initialize the object.

        Parameters:
            name: The object name, as declared in the code.
            lineno: The object starting line, or None for modules. Lines start at 1.
            endlineno: The object ending line (inclusive), or None for modules.
            runtime: Whether this object is present at runtime or not.
            docstring: The object docstring.
            parent: The object parent.
            lines_collection: A collection of source code lines.
            modules_collection: A collection of modules.
        """
        self.name: str = name
        """The object name."""

        self.lineno: int | None = lineno
        """The starting line number of the object.

        See also: [`endlineno`][griffe.Object.endlineno].
        """

        self.endlineno: int | None = endlineno
        """The ending line number of the object.

        See also: [`lineno`][griffe.Object.lineno].
        """

        self.docstring: Docstring | None = docstring
        """The object docstring.

        See also: [`has_docstring`][griffe.Object.has_docstring],
        [`has_docstrings`][griffe.Object.has_docstrings].
        """

        self.parent: Module | Class | None = parent
        """The parent of the object (none if top module)."""

        self.members: dict[str, Object | Alias] = {}
        """The object members (modules, classes, functions, attributes).

        See also: [`inherited_members`][griffe.Object.inherited_members],
        [`get_member`][griffe.Object.get_member],
        [`set_member`][griffe.Object.set_member],
        [`filter_members`][griffe.Object.filter_members].
        """

        self.labels: set[str] = set()
        """The object labels (`property`, `dataclass`, etc.).

        See also: [`has_labels`][griffe.Object.has_labels]."""

        self.imports: dict[str, str] = {}
        """The other objects imported by this object.

        Keys are the names within the object (`from ... import ... as AS_NAME`),
        while the values are the actual names of the objects (`from ... import REAL_NAME as ...`).
        """

        self.exports: list[str | ExprName] | None = None
        """The names of the objects exported by this (module) object through the `__all__` variable.

        Exports can contain string (object names) or resolvable names,
        like other lists of exports coming from submodules:

        ```python
        from .submodule import __all__ as submodule_all

        __all__ = ["hello", *submodule_all]
        ```

        Exports get expanded by the loader before it expands wildcards and resolves aliases.

        See also: [`GriffeLoader.expand_exports`][griffe.GriffeLoader.expand_exports].
        """

        self.aliases: dict[str, Alias] = {}
        """The aliases pointing to this object."""

        self.runtime: bool = runtime
        """Whether this object is available at runtime.

        Typically, type-guarded objects (under an `if TYPE_CHECKING` condition)
        are not available at runtime.
        """

        self.extra: dict[str, dict[str, Any]] = defaultdict(dict)
        """Namespaced dictionaries storing extra metadata for this object, used by extensions."""

        self.public: bool | None = None
        """Whether this object is public."""

        self.deprecated: bool | str | None = None
        """Whether this object is deprecated (boolean or deprecation message)."""

        self._lines_collection: LinesCollection | None = lines_collection
        self._modules_collection: ModulesCollection | None = modules_collection

        # Attach the docstring to this object.
        if docstring:
            docstring.parent = self

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self.name!r}, {self.lineno!r}, {self.endlineno!r})"

    # Prevent using `__len__`.
    def __bool__(self) -> bool:
        """An object is always true-ish."""
        return True

    def __len__(self) -> int:
        """The number of members in this object, recursively."""
        return len(self.members) + sum(len(member) for member in self.members.values())

    @property
    def has_docstring(self) -> bool:
        """Whether this object has a docstring (empty or not).

        See also: [`docstring`][griffe.Object.docstring],
        [`has_docstrings`][griffe.Object.has_docstrings].
        """
        return bool(self.docstring)

    # NOTE: (pawamoy) I'm not happy with `has_docstrings`.
    # It currently recurses into submodules, but that doesn't make sense
    # if downstream projects use it to know if they should render an init module
    # while not rendering submodules too: the property could tell them there are
    # docstrings, but they could be in submodules, not in the init module.
    # Maybe we should derive it into new properties: `has_local_docstrings`,
    # `has_docstrings`, `has_public_docstrings`... Maybe we should make it a function?`
    # For now it's used in mkdocstrings-python so we must be careful with changes.
    @property
    def has_docstrings(self) -> bool:
        """Whether this object or any of its members has a docstring (empty or not).

        Inherited members are not considered. Imported members are not considered,
        unless they are also public.

        See also: [`docstring`][griffe.Object.docstring],
        [`has_docstring`][griffe.Object.has_docstring].
        """
        if self.has_docstring:
            return True
        for member in self.members.values():
            try:
                if (not member.is_imported or member.is_public) and member.has_docstrings:
                    return True
            except AliasResolutionError:
                continue
        return False

    def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool:
        """Tell if this object is of the given kind.

        See also: [`is_module`][griffe.Object.is_module],
        [`is_class`][griffe.Object.is_class],
        [`is_function`][griffe.Object.is_function],
        [`is_attribute`][griffe.Object.is_attribute],
        [`is_alias`][griffe.Object.is_alias].

        Parameters:
            kind: An instance or set of kinds (strings or enumerations).

        Raises:
            ValueError: When an empty set is given as argument.

        Returns:
            True or False.
        """
        if isinstance(kind, set):
            if not kind:
                raise ValueError("kind must not be an empty set")
            return self.kind in (knd if isinstance(knd, Kind) else Kind(knd) for knd in kind)
        if isinstance(kind, str):
            kind = Kind(kind)
        return self.kind is kind

    @property
    def inherited_members(self) -> dict[str, Alias]:
        """Members that are inherited from base classes.

        This method is part of the consumer API:
        do not use when producing Griffe trees!

        See also: [`members`][griffe.Object.members].
        """
        if not isinstance(self, Class):
            return {}
        try:
            mro = self.mro()
        except ValueError as error:
            logger.debug(error)
            return {}
        inherited_members = {}
        for base in reversed(mro):
            for name, member in base.members.items():
                if name not in self.members:
                    inherited_members[name] = Alias(name, member, parent=self, inherited=True)
        return inherited_members

    @property
    def is_module(self) -> bool:
        """Whether this object is a module.

        See also:  [`is_init_module`][griffe.Object.is_init_module].
        [`is_class`][griffe.Object.is_class],
        [`is_function`][griffe.Object.is_function],
        [`is_attribute`][griffe.Object.is_attribute],
        [`is_alias`][griffe.Object.is_alias],
        [`is_kind`][griffe.Object.is_kind].
        """
        return self.kind is Kind.MODULE

    @property
    def is_class(self) -> bool:
        """Whether this object is a class.

        See also:  [`is_module`][griffe.Object.is_module].
        [`is_function`][griffe.Object.is_function],
        [`is_attribute`][griffe.Object.is_attribute],
        [`is_alias`][griffe.Object.is_alias],
        [`is_kind`][griffe.Object.is_kind].
        """
        return self.kind is Kind.CLASS

    @property
    def is_function(self) -> bool:
        """Whether this object is a function.

        See also:  [`is_module`][griffe.Object.is_module].
        [`is_class`][griffe.Object.is_class],
        [`is_attribute`][griffe.Object.is_attribute],
        [`is_alias`][griffe.Object.is_alias],
        [`is_kind`][griffe.Object.is_kind].
        """
        return self.kind is Kind.FUNCTION

    @property
    def is_attribute(self) -> bool:
        """Whether this object is an attribute.

        See also:  [`is_module`][griffe.Object.is_module].
        [`is_class`][griffe.Object.is_class],
        [`is_function`][griffe.Object.is_function],
        [`is_alias`][griffe.Object.is_alias],
        [`is_kind`][griffe.Object.is_kind].
        """
        return self.kind is Kind.ATTRIBUTE

    @property
    def is_init_module(self) -> bool:
        """Whether this object is an `__init__.py` module.

        See also:  [`is_module`][griffe.Object.is_module].
        """
        return False

    @property
    def is_package(self) -> bool:
        """Whether this object is a package (top module).

        See also:  [`is_subpackage`][griffe.Object.is_subpackage].
        """
        return False

    @property
    def is_subpackage(self) -> bool:
        """Whether this object is a subpackage.

        See also:  [`is_package`][griffe.Object.is_package].
        """
        return False

    @property
    def is_namespace_package(self) -> bool:
        """Whether this object is a namespace package (top folder, no `__init__.py`).

        See also:  [`is_namespace_subpackage`][griffe.Object.is_namespace_subpackage].
        """
        return False

    @property
    def is_namespace_subpackage(self) -> bool:
        """Whether this object is a namespace subpackage.

        See also:  [`is_namespace_package`][griffe.Object.is_namespace_package].
        """
        return False

    def has_labels(self, *labels: str) -> bool:
        """Tell if this object has all the given labels.

        See also: [`labels`][griffe.Object.labels].

        Parameters:
            *labels: Labels that must be present.

        Returns:
            True or False.
        """
        return set(labels).issubset(self.labels)

    def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]:
        """Filter and return members based on predicates.

        See also: [`members`][griffe.Object.members].

        Parameters:
            *predicates: A list of predicates, i.e. callables accepting a member as argument and returning a boolean.

        Returns:
            A dictionary of members.
        """
        if not predicates:
            return self.members
        members: dict[str, Object | Alias] = {
            name: member for name, member in self.members.items() if all(predicate(member) for predicate in predicates)
        }
        return members

    @property
    def module(self) -> Module:
        """The parent module of this object.

        See also: [`package`][griffe.Object.package].

        Examples:
            >>> import griffe
            >>> markdown = griffe.load("markdown")
            >>> markdown["core.Markdown.references"].module
            Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/core.py'))
            >>> # The `module` of a module is itself.
            >>> markdown["core"].module
            Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/core.py'))

        Raises:
            ValueError: When the object is not a module and does not have a parent.
        """
        if isinstance(self, Module):
            return self
        if self.parent is not None:
            return self.parent.module
        raise ValueError(f"Object {self.name} does not have a parent module")

    @property
    def package(self) -> Module:
        """The absolute top module (the package) of this object.

        See also: [`module`][griffe.Object.module].

        Examples:
            >>> import griffe
            >>> markdown = griffe.load("markdown")
            >>> markdown["core.Markdown.references"].package
            Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/__init__.py'))
        """
        module = self.module
        while module.parent:
            module = module.parent  # type: ignore[assignment]
        return module

    @property
    def filepath(self) -> Path | list[Path]:
        """The file path (or directory list for namespace packages) where this object was defined.

        See also: [`relative_filepath`][griffe.Object.relative_filepath],
        [`relative_package_filepath`][griffe.Object.relative_package_filepath].

        Examples:
            >>> import griffe
            >>> markdown = griffe.load("markdown")
            >>> markdown.filepath
            PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/__init__.py')
        """
        return self.module.filepath

    @property
    def relative_package_filepath(self) -> Path:
        """The file path where this object was defined, relative to the top module path.

        See also: [`filepath`][griffe.Object.filepath],
        [`relative_filepath`][griffe.Object.relative_filepath].

        Raises:
            ValueError: When the relative path could not be computed.
        """
        package_path = self.package.filepath

        # Current "module" is a namespace package.
        if isinstance(self.filepath, list):
            # Current package is a namespace package.
            if isinstance(package_path, list):
                for pkg_path in package_path:
                    for self_path in self.filepath:
                        with suppress(ValueError):
                            return self_path.relative_to(pkg_path.parent)

            # Current package is a regular package.
            # NOTE: Technically it makes no sense to have a namespace package
            # under a non-namespace one, so we should never enter this branch.
            else:
                for self_path in self.filepath:
                    with suppress(ValueError):
                        return self_path.relative_to(package_path.parent.parent)
            raise ValueError

        # Current package is a namespace package,
        # and current module is a regular module or package.
        if isinstance(package_path, list):
            for pkg_path in package_path:
                with suppress(ValueError):
                    return self.filepath.relative_to(pkg_path.parent)
            raise ValueError

        # Current package is a regular package,
        # and current module is a regular module or package,
        # try to compute the path relative to the parent folder
        # of the package (search path).
        return self.filepath.relative_to(package_path.parent.parent)

    @property
    def relative_filepath(self) -> Path:
        """The file path where this object was defined, relative to the current working directory.

        If this object's file path is not relative to the current working directory, return its absolute path.

        See also: [`filepath`][griffe.Object.filepath],
        [`relative_package_filepath`][griffe.Object.relative_package_filepath].

        Raises:
            ValueError: When the relative path could not be computed.
        """
        cwd = Path.cwd()
        if isinstance(self.filepath, list):
            for self_path in self.filepath:
                with suppress(ValueError):
                    return self_path.relative_to(cwd)
            raise ValueError(f"No directory in {self.filepath!r} is relative to the current working directory {cwd}")
        try:
            return self.filepath.relative_to(cwd)
        except ValueError:
            return self.filepath

    @property
    def path(self) -> str:
        """The dotted path of this object.

        On regular objects (not aliases), the path is the canonical path.

        See also: [`canonical_path`][griffe.Object.canonical_path].

        Examples:
            >>> import griffe
            >>> markdown = griffe.load("markdown")
            >>> markdown["core.Markdown.references"].path
            'markdown.core.Markdown.references'
        """
        return self.canonical_path

    @property
    def canonical_path(self) -> str:
        """The full dotted path of this object.

        The canonical path is the path where the object was defined (not imported).

        See also: [`path`][griffe.Object.path].
        """
        if self.parent is None:
            return self.name
        return f"{self.parent.path}.{self.name}"

    @property
    def modules_collection(self) -> ModulesCollection:
        """The modules collection attached to this object or its parents.

        Raises:
            ValueError: When no modules collection can be found in the object or its parents.
        """
        if self._modules_collection is not None:
            return self._modules_collection
        if self.parent is None:
            raise ValueError("no modules collection in this object or its parents")
        return self.parent.modules_collection

    @property
    def lines_collection(self) -> LinesCollection:
        """The lines collection attached to this object or its parents.

        See also: [`lines`][griffe.Object.lines],
        [`source`][griffe.Object.source].

        Raises:
            ValueError: When no modules collection can be found in the object or its parents.
        """
        if self._lines_collection is not None:
            return self._lines_collection
        if self.parent is None:
            raise ValueError("no lines collection in this object or its parents")
        return self.parent.lines_collection

    @property
    def lines(self) -> list[str]:
        """The lines containing the source of this object.

        See also: [`lines_collection`][griffe.Object.lines_collection],
        [`source`][griffe.Object.source].
        """
        try:
            filepath = self.filepath
        except BuiltinModuleError:
            return []
        if isinstance(filepath, list):
            return []
        try:
            lines = self.lines_collection[filepath]
        except KeyError:
            return []
        if self.is_module:
            return lines
        if self.lineno is None or self.endlineno is None:
            return []
        return lines[self.lineno - 1 : self.endlineno]

    @property
    def source(self) -> str:
        """The source code of this object.

        See also: [`lines`][griffe.Object.lines],
        [`lines_collection`][griffe.Object.lines_collection].
        """
        return dedent("\n".join(self.lines))

    def resolve(self, name: str) -> str:
        """Resolve a name within this object's and parents' scope.

        Parameters:
            name: The name to resolve.

        Raises:
            NameResolutionError: When the name could not be resolved.

        Returns:
            The resolved name.
        """
        # TODO: Better match Python's own scoping rules?
        # Also, maybe return regular paths instead of canonical ones?

        # Name is a member this object.
        if name in self.members:
            if self.members[name].is_alias:
                return self.members[name].target_path  # type: ignore[union-attr]
            return self.members[name].path

        # Name unknown and no more parent scope, could be a built-in.
        if self.parent is None:
            raise NameResolutionError(f"{name} could not be resolved in the scope of {self.path}")

        # Name is parent, non-module object.
        if name == self.parent.name and not self.parent.is_module:
            return self.parent.path

        # Recurse in parent.
        return self.parent.resolve(name)

    def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]:
        """Return this object's data as a dictionary.

        See also: [`as_json`][griffe.Object.as_json].

        Parameters:
            full: Whether to return full info, or just base info.
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base: dict[str, Any] = {
            "kind": self.kind,
            "name": self.name,
        }

        if full:
            base.update(
                {
                    "path": self.path,
                    "filepath": self.filepath,
                    "relative_filepath": self.relative_filepath,
                    "relative_package_filepath": self.relative_package_filepath,
                },
            )

        if self.lineno is not None:
            base["lineno"] = self.lineno
        if self.endlineno is not None:
            base["endlineno"] = self.endlineno
        if self.docstring:
            base["docstring"] = self.docstring

        base["labels"] = self.labels
        base["members"] = {name: member.as_dict(full=full, **kwargs) for name, member in self.members.items()}

        return base


class Alias(ObjectAliasMixin):
    """This class represents an alias, or indirection, to an object declared in another module.

    Aliases represent objects that are in the scope of a module or class,
    but were imported from another module.

    They behave almost exactly like regular objects, to a few exceptions:

    - line numbers are those of the alias, not the target
    - the path is the alias path, not the canonical one
    - the name can be different from the target's
    - if the target can be resolved, the kind is the target's kind
    - if the target cannot be resolved, the kind becomes [Kind.ALIAS][griffe.Kind]
    """

    is_alias: bool = True
    """Always true for aliases."""
    is_collection: bool = False
    """Always false for aliases.

    See also: [`ModulesCollection`][griffe.ModulesCollection].
    """

    def __init__(
        self,
        name: str,
        target: str | Object | Alias,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
        runtime: bool = True,
        parent: Module | Class | Alias | None = None,
        inherited: bool = False,
    ) -> None:
        """Initialize the alias.

        Parameters:
            name: The alias name.
            target: If it's a string, the target resolution is delayed until accessing the target property.
                If it's an object, or even another alias, the target is immediately set.
            lineno: The alias starting line number.
            endlineno: The alias ending line number.
            runtime: Whether this alias is present at runtime or not.
            parent: The alias parent.
            inherited: Whether this alias wraps an inherited member.
        """
        self.name: str = name
        """The alias name."""

        self.alias_lineno: int | None = lineno
        """The starting line number of the alias."""

        self.alias_endlineno: int | None = endlineno
        """The ending line number of the alias."""

        self.runtime: bool = runtime
        """Whether this alias is available at runtime."""

        self.inherited: bool = inherited
        """Whether this alias represents an inherited member."""

        self.public: bool | None = None
        """Whether this alias is public."""

        self.deprecated: str | bool | None = None
        """Whether this alias is deprecated (boolean or deprecation message)."""

        self._parent: Module | Class | Alias | None = parent
        self._passed_through: bool = False

        self.target_path: str
        """The path of this alias' target."""

        if isinstance(target, str):
            self._target: Object | Alias | None = None
            self.target_path = target
        else:
            self._target = target
            self.target_path = target.path
            self._update_target_aliases()

    def __repr__(self) -> str:
        return f"Alias({self.name!r}, {self.target_path!r})"

    # Prevent using `__len__`.
    def __bool__(self) -> bool:
        """An alias is always true-ish."""
        return True

    def __len__(self) -> int:
        """The length of an alias is always 1."""
        return 1

    # SPECIAL PROXIES -------------------------------
    # The following methods and properties exist on the target(s),
    # but we must handle them in a special way.

    @property
    def kind(self) -> Kind:
        """The target's kind, or `Kind.ALIAS` if the target cannot be resolved.

        See also: [`is_kind`][griffe.Alias.is_kind].
        """
        # custom behavior to avoid raising exceptions
        try:
            return self.final_target.kind
        except (AliasResolutionError, CyclicAliasError):
            return Kind.ALIAS

    @property
    def has_docstring(self) -> bool:
        """Whether this alias' target has a non-empty docstring.

        See also: [`has_docstrings`][griffe.Alias.has_docstrings],
        [`docstring`][griffe.Alias.docstring].
        """
        try:
            return self.final_target.has_docstring
        except (AliasResolutionError, CyclicAliasError):
            return False

    @property
    def has_docstrings(self) -> bool:
        """Whether this alias' target or any of its members has a non-empty docstring.

        See also: [`has_docstring`][griffe.Alias.has_docstring],
        [`docstring`][griffe.Alias.docstring].
        """
        try:
            return self.final_target.has_docstrings
        except (AliasResolutionError, CyclicAliasError):
            return False

    @property
    def parent(self) -> Module | Class | Alias | None:
        """The parent of this alias."""
        return self._parent

    @parent.setter
    def parent(self, value: Module | Class | Alias) -> None:
        self._parent = value
        self._update_target_aliases()

    @property
    def path(self) -> str:
        """The dotted path / import path of this object.

        See also: [`canonical_path`][griffe.Alias.canonical_path].
        """
        return f"{self.parent.path}.{self.name}"  # type: ignore[union-attr]

    @property
    def modules_collection(self) -> ModulesCollection:
        """The modules collection attached to the alias parents."""
        # No need to forward to the target.
        return self.parent.modules_collection  # type: ignore[union-attr]

    @property
    def members(self) -> dict[str, Object | Alias]:
        """The target's members (modules, classes, functions, attributes).

        See also: [`inherited_members`][griffe.Alias.inherited_members],
        [`get_member`][griffe.Alias.get_member],
        [`set_member`][griffe.Alias.set_member],
        [`filter_members`][griffe.Alias.filter_members].
        """
        final_target = self.final_target

        # We recreate aliases to maintain a correct hierarchy,
        # and therefore correct paths. The path of an alias member
        # should be the path of the alias plus the member's name,
        # not the original member's path.
        return {
            name: Alias(name, target=member, parent=self, inherited=False)
            for name, member in final_target.members.items()
        }

    @property
    def inherited_members(self) -> dict[str, Alias]:
        """Members that are inherited from base classes.

        Each inherited member of the target will be wrapped in an alias,
        to preserve correct object access paths.

        This method is part of the consumer API:
        do not use when producing Griffe trees!

        See also: [`members`][griffe.Alias.members].
        """
        final_target = self.final_target

        # We recreate aliases to maintain a correct hierarchy,
        # and therefore correct paths. The path of an alias member
        # should be the path of the alias plus the member's name,
        # not the original member's path.
        return {
            name: Alias(name, target=member, parent=self, inherited=True)
            for name, member in final_target.inherited_members.items()
        }

    def as_json(self, *, full: bool = False, **kwargs: Any) -> str:
        """Return this target's data as a JSON string.

        See also: [`as_dict`][griffe.Alias.as_dict].

        Parameters:
            full: Whether to return full info, or just base info.
            **kwargs: Additional serialization options passed to encoder.

        Returns:
            A JSON string.
        """
        try:
            return self.final_target.as_json(full=full, **kwargs)
        except (AliasResolutionError, CyclicAliasError):
            return super().as_json(full=full, **kwargs)

    # GENERIC OBJECT PROXIES --------------------------------
    # The following methods and properties exist on the target(s).
    # We first try to reach the final target, triggering alias resolution errors
    # and cyclic aliases errors early. We avoid recursing in the alias chain.

    @property
    def extra(self) -> dict:
        """Namespaced dictionaries storing extra metadata for this object, used by extensions."""
        return self.final_target.extra

    @property
    def lineno(self) -> int | None:
        """The starting line number of the target object.

        See also: [`endlineno`][griffe.Alias.endlineno].
        """
        return self.final_target.lineno

    @lineno.setter
    def lineno(self, lineno: int | None) -> None:
        self.final_target.lineno = lineno

    @property
    def endlineno(self) -> int | None:
        """The ending line number of the target object.

        See also: [`lineno`][griffe.Alias.lineno].
        """
        return self.final_target.endlineno

    @endlineno.setter
    def endlineno(self, endlineno: int | None) -> None:
        self.final_target.endlineno = endlineno

    @property
    def docstring(self) -> Docstring | None:
        """The target docstring.

        See also: [`has_docstring`][griffe.Alias.has_docstring],
        [`has_docstrings`][griffe.Alias.has_docstrings].
        """
        return self.final_target.docstring

    @docstring.setter
    def docstring(self, docstring: Docstring | None) -> None:
        self.final_target.docstring = docstring

    @property
    def labels(self) -> set[str]:
        """The target labels (`property`, `dataclass`, etc.).

        See also: [`has_labels`][griffe.Alias.has_labels].
        """
        return self.final_target.labels

    @property
    def imports(self) -> dict[str, str]:
        """The other objects imported by this alias' target.

        Keys are the names within the object (`from ... import ... as AS_NAME`),
        while the values are the actual names of the objects (`from ... import REAL_NAME as ...`).

        See also: [`is_imported`][griffe.Alias.is_imported].
        """
        return self.final_target.imports

    @property
    def exports(self) -> list[str | ExprName] | None:
        """The names of the objects exported by this (module) object through the `__all__` variable.

        Exports can contain string (object names) or resolvable names,
        like other lists of exports coming from submodules:

        ```python
        from .submodule import __all__ as submodule_all

        __all__ = ["hello", *submodule_all]
        ```

        Exports get expanded by the loader before it expands wildcards and resolves aliases.

        See also: [`GriffeLoader.expand_exports`][griffe.GriffeLoader.expand_exports].
        """
        return self.final_target.exports

    @property
    def aliases(self) -> dict[str, Alias]:
        """The aliases pointing to this object."""
        return self.final_target.aliases

    def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool:
        """Tell if this object is of the given kind.

        See also: [`is_module`][griffe.Alias.is_module],
        [`is_class`][griffe.Alias.is_class],
        [`is_function`][griffe.Alias.is_function],
        [`is_attribute`][griffe.Alias.is_attribute],
        [`is_alias`][griffe.Alias.is_alias].

        Parameters:
            kind: An instance or set of kinds (strings or enumerations).

        Raises:
            ValueError: When an empty set is given as argument.

        Returns:
            True or False.
        """
        return self.final_target.is_kind(kind)

    @property
    def is_module(self) -> bool:
        """Whether this object is a module.

        See also:  [`is_init_module`][griffe.Alias.is_init_module].
        [`is_class`][griffe.Alias.is_class],
        [`is_function`][griffe.Alias.is_function],
        [`is_attribute`][griffe.Alias.is_attribute],
        [`is_alias`][griffe.Alias.is_alias],
        [`is_kind`][griffe.Alias.is_kind].
        """
        return self.final_target.is_module

    @property
    def is_class(self) -> bool:
        """Whether this object is a class.

        See also: [`is_module`][griffe.Alias.is_module],
        [`is_function`][griffe.Alias.is_function],
        [`is_attribute`][griffe.Alias.is_attribute],
        [`is_alias`][griffe.Alias.is_alias],
        [`is_kind`][griffe.Alias.is_kind].
        """
        return self.final_target.is_class

    @property
    def is_function(self) -> bool:
        """Whether this object is a function.

        See also: [`is_module`][griffe.Alias.is_module],
        [`is_class`][griffe.Alias.is_class],
        [`is_attribute`][griffe.Alias.is_attribute],
        [`is_alias`][griffe.Alias.is_alias],
        [`is_kind`][griffe.Alias.is_kind].
        """
        return self.final_target.is_function

    @property
    def is_attribute(self) -> bool:
        """Whether this object is an attribute.

        See also: [`is_module`][griffe.Alias.is_module],
        [`is_class`][griffe.Alias.is_class],
        [`is_function`][griffe.Alias.is_function],
        [`is_alias`][griffe.Alias.is_alias],
        [`is_kind`][griffe.Alias.is_kind].
        """
        return self.final_target.is_attribute

    def has_labels(self, *labels: str) -> bool:
        """Tell if this object has all the given labels.

        See also: [`labels`][griffe.Alias.labels].

        Parameters:
            *labels: Labels that must be present.

        Returns:
            True or False.
        """
        return self.final_target.has_labels(*labels)

    def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]:
        """Filter and return members based on predicates.

        See also: [`members`][griffe.Alias.members],
        [`get_member`][griffe.Alias.get_member],
        [`set_member`][griffe.Alias.set_member].

        Parameters:
            *predicates: A list of predicates, i.e. callables accepting a member as argument and returning a boolean.

        Returns:
            A dictionary of members.
        """
        return self.final_target.filter_members(*predicates)

    @property
    def module(self) -> Module:
        """The parent module of this object.

        See also: [`package`][griffe.Alias.package].

        Raises:
            ValueError: When the object is not a module and does not have a parent.
        """
        return self.final_target.module

    @property
    def package(self) -> Module:
        """The absolute top module (the package) of this object.

        See also: [`module`][griffe.Alias.module].
        """
        return self.final_target.package

    @property
    def filepath(self) -> Path | list[Path]:
        """The file path (or directory list for namespace packages) where this object was defined.

        See also: [`relative_filepath`][griffe.Alias.relative_filepath],
        [`relative_package_filepath`][griffe.Alias.relative_package_filepath].
        """
        return self.final_target.filepath

    @property
    def relative_filepath(self) -> Path:
        """The file path where this object was defined, relative to the current working directory.

        If this object's file path is not relative to the current working directory, return its absolute path.

        See also: [`filepath`][griffe.Alias.filepath],
        [`relative_package_filepath`][griffe.Alias.relative_package_filepath].

        Raises:
            ValueError: When the relative path could not be computed.
        """
        return self.final_target.relative_filepath

    @property
    def relative_package_filepath(self) -> Path:
        """The file path where this object was defined, relative to the top module path.

        See also: [`filepath`][griffe.Alias.filepath],
        [`relative_filepath`][griffe.Alias.relative_filepath].

        Raises:
            ValueError: When the relative path could not be computed.
        """
        return self.final_target.relative_package_filepath

    @property
    def canonical_path(self) -> str:
        """The full dotted path of this object.

        The canonical path is the path where the object was defined (not imported).

        See also: [`path`][griffe.Alias.path].
        """
        return self.final_target.canonical_path

    @property
    def lines_collection(self) -> LinesCollection:
        """The lines collection attached to this object or its parents.

        See also: [`lines`][griffe.Alias.lines],
        [`source`][griffe.Alias.source].

        Raises:
            ValueError: When no modules collection can be found in the object or its parents.
        """
        return self.final_target.lines_collection

    @property
    def lines(self) -> list[str]:
        """The lines containing the source of this object.

        See also: [`source`][griffe.Alias.source],
        [`lines_collection`][griffe.Alias.lines_collection].
        """
        return self.final_target.lines

    @property
    def source(self) -> str:
        """The source code of this object.

        See also: [`lines`][griffe.Alias.lines],
        [`lines_collection`][griffe.Alias.lines_collection].
        """
        return self.final_target.source

    def resolve(self, name: str) -> str:
        """Resolve a name within this object's and parents' scope.

        Parameters:
            name: The name to resolve.

        Raises:
            NameResolutionError: When the name could not be resolved.

        Returns:
            The resolved name.
        """
        return self.final_target.resolve(name)

    # SPECIFIC MODULE/CLASS/FUNCTION/ATTRIBUTE PROXIES ---------------
    # These methods and properties exist on targets of specific kind.
    # We first try to reach the final target, triggering alias resolution errors
    # and cyclic aliases errors early. We avoid recursing in the alias chain.

    @property
    def _filepath(self) -> Path | list[Path] | None:
        return cast("Module", self.final_target)._filepath

    @property
    def bases(self) -> list[Expr | str]:
        """The class bases.

        See also: [`Class`][griffe.Class],
        [`resolved_bases`][griffe.Alias.resolved_bases],
        [`mro`][griffe.Alias.mro].
        """
        return cast("Class", self.final_target).bases

    @property
    def decorators(self) -> list[Decorator]:
        """The class/function decorators.

        See also: [`Function`][griffe.Function],
        [`Class`][griffe.Class].
        """
        return cast("Union[Class, Function]", self.target).decorators

    @property
    def imports_future_annotations(self) -> bool:
        """Whether this module import future annotations."""
        return cast("Module", self.final_target).imports_future_annotations

    @property
    def is_init_module(self) -> bool:
        """Whether this module is an `__init__.py` module.

        See also: [`is_module`][griffe.Alias.is_module].
        """
        return cast("Module", self.final_target).is_init_module

    @property
    def is_package(self) -> bool:
        """Whether this module is a package (top module).

        See also: [`is_subpackage`][griffe.Alias.is_subpackage].
        """
        return cast("Module", self.final_target).is_package

    @property
    def is_subpackage(self) -> bool:
        """Whether this module is a subpackage.

        See also: [`is_package`][griffe.Alias.is_package].
        """
        return cast("Module", self.final_target).is_subpackage

    @property
    def is_namespace_package(self) -> bool:
        """Whether this module is a namespace package (top folder, no `__init__.py`).

        See also: [`is_namespace_subpackage`][griffe.Alias.is_namespace_subpackage].
        """
        return cast("Module", self.final_target).is_namespace_package

    @property
    def is_namespace_subpackage(self) -> bool:
        """Whether this module is a namespace subpackage.

        See also: [`is_namespace_package`][griffe.Alias.is_namespace_package].
        """
        return cast("Module", self.final_target).is_namespace_subpackage

    @property
    def overloads(self) -> dict[str, list[Function]] | list[Function] | None:
        """The overloaded signatures declared in this class/module or for this function."""
        return cast("Union[Module, Class, Function]", self.final_target).overloads

    @overloads.setter
    def overloads(self, overloads: list[Function] | None) -> None:
        cast("Union[Module, Class, Function]", self.final_target).overloads = overloads

    @property
    def parameters(self) -> Parameters:
        """The parameters of the current function or `__init__` method for classes.

        This property can fetch inherited members,
        and therefore is part of the consumer API:
        do not use when producing Griffe trees!
        """
        return cast("Union[Class, Function]", self.final_target).parameters

    @property
    def returns(self) -> str | Expr | None:
        """The function return type annotation."""
        return cast("Function", self.final_target).returns

    @returns.setter
    def returns(self, returns: str | Expr | None) -> None:
        cast("Function", self.final_target).returns = returns

    @property
    def setter(self) -> Function | None:
        """The setter linked to this function (property)."""
        return cast("Attribute", self.final_target).setter

    @property
    def deleter(self) -> Function | None:
        """The deleter linked to this function (property)."""
        return cast("Attribute", self.final_target).deleter

    @property
    def value(self) -> str | Expr | None:
        """The attribute value."""
        return cast("Attribute", self.final_target).value

    @value.setter
    def value(self, value: str | Expr | None) -> None:
        cast("Attribute", self.final_target).value = value

    @property
    def annotation(self) -> str | Expr | None:
        """The attribute type annotation."""
        return cast("Attribute", self.final_target).annotation

    @annotation.setter
    def annotation(self, annotation: str | Expr | None) -> None:
        cast("Attribute", self.final_target).annotation = annotation

    @property
    def resolved_bases(self) -> list[Object]:
        """Resolved class bases.

        This method is part of the consumer API:
        do not use when producing Griffe trees!
        """
        return cast("Class", self.final_target).resolved_bases

    def mro(self) -> list[Class]:
        """Return a list of classes in order corresponding to Python's MRO."""
        return cast("Class", self.final_target).mro()

    # SPECIFIC ALIAS METHOD AND PROPERTIES -----------------
    # These methods and properties do not exist on targets,
    # they are specific to aliases.

    @property
    def target(self) -> Object | Alias:
        """The resolved target (actual object), if possible.

        Upon accessing this property, if the target is not already resolved,
        a lookup is done using the modules collection to find the target.

        See also: [`final_target`][griffe.Alias.final_target],
        [`resolve_target`][griffe.Alias.resolve_target],
        [`resolved`][griffe.Alias.resolved].
        """
        if not self.resolved:
            self.resolve_target()
        return self._target  # type: ignore[return-value]

    @target.setter
    def target(self, value: Object | Alias) -> None:
        if value is self or value.path == self.path:
            raise CyclicAliasError([self.target_path])
        self._target = value
        self.target_path = value.path
        if self.parent is not None:
            self._target.aliases[self.path] = self

    @property
    def final_target(self) -> Object:
        """The final, resolved target, if possible.

        This will iterate through the targets until a non-alias object is found.

        See also: [`target`][griffe.Alias.target],
        [`resolve_target`][griffe.Alias.resolve_target],
        [`resolved`][griffe.Alias.resolved].
        """
        # Here we quickly iterate on the alias chain,
        # remembering which path we've seen already to detect cycles.

        # The cycle detection is needed because alias chains can be created
        # as already resolved, and can contain cycles.

        # Using a dict as an ordered set.
        paths_seen: dict[str, None] = {}
        target = self
        while target.is_alias:
            if target.path in paths_seen:
                raise CyclicAliasError([*paths_seen, target.path])
            paths_seen[target.path] = None
            target = target.target  # type: ignore[assignment]
        return target  # type: ignore[return-value]

    def resolve_target(self) -> None:
        """Resolve the target.

        See also: [`target`][griffe.Alias.target],
        [`final_target`][griffe.Alias.final_target],
        [`resolved`][griffe.Alias.resolved].

        Raises:
            AliasResolutionError: When the target cannot be resolved.
                It happens when the target does not exist,
                or could not be loaded (unhandled dynamic object?),
                or when the target is from a module that was not loaded
                and added to the collection.
            CyclicAliasError: When the resolved target is the alias itself.
        """
        # Here we try to resolve the whole alias chain recursively.
        # We detect cycles by setting a "passed through" state variable
        # on each alias as we pass through it. Passing a second time
        # through an alias will raise a CyclicAliasError.

        # If a single link of the chain cannot be resolved,
        # the whole chain stays unresolved. This prevents
        # bad surprises later, in code that checks if
        # an alias is resolved by checking only
        # the first link of the chain.
        if self._passed_through:
            raise CyclicAliasError([self.target_path])
        self._passed_through = True
        try:
            self._resolve_target()
        finally:
            self._passed_through = False

    def _resolve_target(self) -> None:
        try:
            resolved = self.modules_collection.get_member(self.target_path)
        except KeyError as error:
            raise AliasResolutionError(self) from error
        if resolved is self:
            raise CyclicAliasError([self.target_path])
        if resolved.is_alias and not resolved.resolved:
            try:
                resolved.resolve_target()
            except CyclicAliasError as error:
                raise CyclicAliasError([self.target_path, *error.chain]) from error
        self._target = resolved
        if self.parent is not None:
            self._target.aliases[self.path] = self  # type: ignore[union-attr]

    def _update_target_aliases(self) -> None:
        with suppress(AttributeError, AliasResolutionError, CyclicAliasError):
            self._target.aliases[self.path] = self  # type: ignore[union-attr]

    @property
    def resolved(self) -> bool:
        """Whether this alias' target is resolved."""
        return self._target is not None

    @property
    def wildcard(self) -> str | None:
        """The module on which the wildcard import is performed (if any).

        See also: [`GriffeLoader.expand_wildcards`][griffe.GriffeLoader.expand_wildcards].
        """
        if self.name.endswith("/*"):
            return self.target_path
        return None

    def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]:  # noqa: ARG002
        """Return this alias' data as a dictionary.

        See also: [`as_json`][griffe.Alias.as_json].

        Parameters:
            full: Whether to return full info, or just base info.
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base: dict[str, Any] = {
            "kind": Kind.ALIAS,
            "name": self.name,
            "target_path": self.target_path,
        }

        if full:
            base["path"] = self.path

        if self.alias_lineno:
            base["lineno"] = self.alias_lineno
        if self.alias_endlineno:
            base["endlineno"] = self.alias_endlineno

        return base


class Module(Object):
    """The class representing a Python module."""

    kind = Kind.MODULE

    def __init__(self, *args: Any, filepath: Path | list[Path] | None = None, **kwargs: Any) -> None:
        """Initialize the module.

        Parameters:
            *args: See [`griffe.Object`][].
            filepath: The module file path (directory for namespace [sub]packages, none for builtin modules).
            **kwargs: See [`griffe.Object`][].
        """
        super().__init__(*args, **kwargs)
        self._filepath: Path | list[Path] | None = filepath
        self.overloads: dict[str, list[Function]] = defaultdict(list)
        """The overloaded signatures declared in this module."""

    def __repr__(self) -> str:
        try:
            return f"Module({self.filepath!r})"
        except BuiltinModuleError:
            return f"Module({self.name!r})"

    @property
    def filepath(self) -> Path | list[Path]:
        """The file path of this module.

        Raises:
            BuiltinModuleError: When the instance filepath is None.
        """
        if self._filepath is None:
            raise BuiltinModuleError(self.name)
        return self._filepath

    @property
    def imports_future_annotations(self) -> bool:
        """Whether this module import future annotations."""
        return (
            "annotations" in self.members
            and self.members["annotations"].is_alias
            and self.members["annotations"].target_path == "__future__.annotations"  # type: ignore[union-attr]
        )

    @property
    def is_init_module(self) -> bool:
        """Whether this module is an `__init__.py` module.

        See also: [`is_module`][griffe.Module.is_module].
        """
        if isinstance(self.filepath, list):
            return False
        try:
            return self.filepath.name.split(".", 1)[0] == "__init__"
        except BuiltinModuleError:
            return False

    @property
    def is_package(self) -> bool:
        """Whether this module is a package (top module).

        See also: [`is_subpackage`][griffe.Module.is_subpackage].
        """
        return not bool(self.parent) and self.is_init_module

    @property
    def is_subpackage(self) -> bool:
        """Whether this module is a subpackage.

        See also: [`is_package`][griffe.Module.is_package].
        """
        return bool(self.parent) and self.is_init_module

    @property
    def is_namespace_package(self) -> bool:
        """Whether this module is a namespace package (top folder, no `__init__.py`).

        See also: [`is_namespace_subpackage`][griffe.Module.is_namespace_subpackage].
        """
        try:
            return self.parent is None and isinstance(self.filepath, list)
        except BuiltinModuleError:
            return False

    @property
    def is_namespace_subpackage(self) -> bool:
        """Whether this module is a namespace subpackage.

        See also: [`is_namespace_package`][griffe.Module.is_namespace_package].
        """
        try:
            return (
                self.parent is not None
                and isinstance(self.filepath, list)
                and (
                    cast("Module", self.parent).is_namespace_package
                    or cast("Module", self.parent).is_namespace_subpackage
                )
            )
        except BuiltinModuleError:
            return False

    def as_dict(self, **kwargs: Any) -> dict[str, Any]:
        """Return this module's data as a dictionary.

        See also: [`as_json`][griffe.Module.as_json].

        Parameters:
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base = super().as_dict(**kwargs)
        if isinstance(self._filepath, list):
            base["filepath"] = [str(path) for path in self._filepath]
        elif self._filepath:
            base["filepath"] = str(self._filepath)
        else:
            base["filepath"] = None
        return base


class Class(Object):
    """The class representing a Python class."""

    kind = Kind.CLASS

    def __init__(
        self,
        *args: Any,
        bases: Sequence[Expr | str] | None = None,
        decorators: list[Decorator] | None = None,
        **kwargs: Any,
    ) -> None:
        """Initialize the class.

        Parameters:
            *args: See [`griffe.Object`][].
            bases: The list of base classes, if any.
            decorators: The class decorators, if any.
            **kwargs: See [`griffe.Object`][].
        """
        super().__init__(*args, **kwargs)

        self.bases: list[Expr | str] = list(bases) if bases else []
        """The class bases.

        See also: [`resolved_bases`][griffe.Class.resolved_bases],
        [`mro`][griffe.Class.mro].
        """

        self.decorators: list[Decorator] = decorators or []
        """The class decorators."""

        self.overloads: dict[str, list[Function]] = defaultdict(list)
        """The overloaded signatures declared in this class."""

    @property
    def parameters(self) -> Parameters:
        """The parameters of this class' `__init__` method, if any.

        This property fetches inherited members,
        and therefore is part of the consumer API:
        do not use when producing Griffe trees!
        """
        try:
            return self.all_members["__init__"].parameters  # type: ignore[union-attr]
        except KeyError:
            return Parameters()

    @property
    def resolved_bases(self) -> list[Object]:
        """Resolved class bases.

        This method is part of the consumer API:
        do not use when producing Griffe trees!

        See also: [`bases`][griffe.Class.bases],
        [`mro`][griffe.Class.mro].
        """
        resolved_bases = []
        for base in self.bases:
            base_path = base if isinstance(base, str) else base.canonical_path
            try:
                resolved_base = self.modules_collection.get_member(base_path)
                if resolved_base.is_alias:
                    resolved_base = resolved_base.final_target
            except (AliasResolutionError, CyclicAliasError, KeyError):
                logger.debug("Base class %s is not loaded, or not static, it cannot be resolved", base_path)
            else:
                resolved_bases.append(resolved_base)
        return resolved_bases

    def _mro(self, seen: tuple[str, ...] = ()) -> list[Class]:
        seen = (*seen, self.path)
        bases: list[Class] = [base for base in self.resolved_bases if base.is_class]  # type: ignore[misc]
        if not bases:
            return [self]
        for base in bases:
            if base.path in seen:
                cycle = " -> ".join(seen) + f" -> {base.path}"
                raise ValueError(f"Cannot compute C3 linearization, inheritance cycle detected: {cycle}")
        return [self, *c3linear_merge(*[base._mro(seen) for base in bases], bases)]

    def mro(self) -> list[Class]:
        """Return a list of classes in order corresponding to Python's MRO.

        See also: [`bases`][griffe.Class.bases],
        [`resolved_bases`][griffe.Class.resolved_bases].
        """
        return self._mro()[1:]  # Remove self.

    def as_dict(self, **kwargs: Any) -> dict[str, Any]:
        """Return this class' data as a dictionary.

        See also: [`as_json`][griffe.Class.as_json].

        Parameters:
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base = super().as_dict(**kwargs)
        base["bases"] = self.bases
        base["decorators"] = [dec.as_dict(**kwargs) for dec in self.decorators]
        return base


class Function(Object):
    """The class representing a Python function."""

    kind = Kind.FUNCTION

    def __init__(
        self,
        *args: Any,
        parameters: Parameters | None = None,
        returns: str | Expr | None = None,
        decorators: list[Decorator] | None = None,
        **kwargs: Any,
    ) -> None:
        """Initialize the function.

        Parameters:
            *args: See [`griffe.Object`][].
            parameters: The function parameters.
            returns: The function return annotation.
            decorators: The function decorators, if any.
            **kwargs: See [`griffe.Object`][].
        """
        super().__init__(*args, **kwargs)
        self.parameters: Parameters = parameters or Parameters()
        """The function parameters."""
        self.returns: str | Expr | None = returns
        """The function return type annotation."""
        self.decorators: list[Decorator] = decorators or []
        """The function decorators."""
        self.overloads: list[Function] | None = None
        """The overloaded signatures of this function."""

        for parameter in self.parameters:
            parameter.function = self

    @property
    def annotation(self) -> str | Expr | None:
        """The type annotation of the returned value."""
        return self.returns

    def resolve(self, name: str) -> str:
        """Resolve a name within this object's and parents' scope.

        Parameters:
            name: The name to resolve.

        Raises:
            NameResolutionError: When the name could not be resolved.

        Returns:
            The resolved name.
        """
        # We're in an `__init__` method...
        if self.parent and self.name == "__init__":
            # ...and name is a parameter name: resolve to the parameter.
            if name in self.parameters:
                return f"{self.parent.path}({name})"

            # Kind of a special case: we avoid resolving to instance-attributes from a function scope.
            # See issue https://github.com/mkdocstrings/griffe/issues/367.
            resolved = super().resolve(name)
            try:
                obj = self.modules_collection.get_member(resolved)
            except KeyError:
                return resolved
            try:
                if obj.is_attribute and "instance-attribute" in obj.labels:
                    raise NameResolutionError(name)
            except AliasResolutionError:
                pass
            return resolved
        return super().resolve(name)

    def as_dict(self, **kwargs: Any) -> dict[str, Any]:
        """Return this function's data as a dictionary.

        See also: [`as_json`][griffe.Function.as_json].

        Parameters:
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base = super().as_dict(**kwargs)
        base["decorators"] = [dec.as_dict(**kwargs) for dec in self.decorators]
        base["parameters"] = [param.as_dict(**kwargs) for param in self.parameters]
        base["returns"] = self.returns
        return base


class Attribute(Object):
    """The class representing a Python module/class/instance attribute."""

    kind = Kind.ATTRIBUTE

    def __init__(
        self,
        *args: Any,
        value: str | Expr | None = None,
        annotation: str | Expr | None = None,
        **kwargs: Any,
    ) -> None:
        """Initialize the function.

        Parameters:
            *args: See [`griffe.Object`][].
            value: The attribute value, if any.
            annotation: The attribute annotation, if any.
            **kwargs: See [`griffe.Object`][].
        """
        super().__init__(*args, **kwargs)
        self.value: str | Expr | None = value
        """The attribute value."""
        self.annotation: str | Expr | None = annotation
        """The attribute type annotation."""
        self.setter: Function | None = None
        """The setter linked to this property."""
        self.deleter: Function | None = None
        """The deleter linked to this property."""

    def as_dict(self, **kwargs: Any) -> dict[str, Any]:
        """Return this function's data as a dictionary.

        See also: [`as_json`][griffe.Attribute.as_json].

        Parameters:
            **kwargs: Additional serialization options.

        Returns:
            A dictionary.
        """
        base = super().as_dict(**kwargs)
        if self.value is not None:
            base["value"] = self.value
        if self.annotation is not None:
            base["annotation"] = self.annotation
        return base