/
dataclasses.py
1503 lines (1213 loc) · 48 KB
/
dataclasses.py
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
"""This module contains the data classes that represent Python objects.
The different objects are modules, classes, functions, and attribute
(variables like module/class/instance attributes).
"""
from __future__ import annotations
import enum
import inspect
import sys
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.docstrings.parsers import Parser, parse
from griffe.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError, NameResolutionError
from griffe.mixins import GetMembersMixin, ObjectAliasMixin, SerializationMixin, SetMembersMixin
if TYPE_CHECKING:
from griffe.collections import LinesCollection, ModulesCollection
from griffe.docstrings.dataclasses import DocstringSection
from griffe.expressions import Expression, Name
# TODO: remove once Python 3.7 support is dropped
if sys.version_info < (3, 8):
from cached_property import cached_property
else:
from functools import cached_property
class ParameterKind(enum.Enum):
"""Enumeration of the different parameter kinds.
Attributes:
positional_only: Positional-only parameter.
positional_or_keyword: Positional or keyword parameter.
var_positional: Variadic positional parameter.
keyword_only: Keyword-only parameter.
var_keyword: Variadic keyword parameter.
"""
positional_only: str = "positional-only"
positional_or_keyword: str = "positional or keyword"
var_positional: str = "variadic positional"
keyword_only: str = "keyword-only"
var_keyword: str = "variadic keyword"
class Decorator:
"""This class represents decorators.
Attributes:
lineno: The starting line number.
endlineno: The ending line number.
"""
def __init__(self, value: str, *, 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 = value
self.lineno: int | None = lineno
self.endlineno: int | None = endlineno
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.
Attributes:
value: The actual documentation string, cleaned up.
lineno: The starting line number.
endlineno: The ending line number.
parent: The parent object on which this docstring is attached.
"""
def __init__(
self,
value: str,
*,
lineno: int | None = None,
endlineno: int | None = None,
parent: Object | None = None,
parser: 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())
self.lineno: int | None = lineno
self.endlineno: int | None = endlineno
self.parent: Object | None = parent
self.parser: Parser | None = parser
self.parser_options: dict[str, Any] = parser_options or {}
def __bool__(self) -> bool:
return bool(self.value)
@cached_property
def lines(self) -> list[str]:
"""Returns the lines of the docstring.
Returns:
The docstring's lines.
"""
return self.value.split("\n")
@cached_property
def parsed(self) -> list[DocstringSection]:
"""Return the docstring, parsed into structured data.
Returns:
The parsed docstring as a list of sections.
"""
return self.parse()
def parse(self, parser: Parser | None = None, **options: Any) -> list[DocstringSection]:
"""Parse the docstring into structured data.
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, docstring_parser: Parser | None = None, **kwargs: Any) -> dict[str, Any]:
"""Return this docstring's data as a dictionary.
Parameters:
full: Whether to return full info, or just base info.
docstring_parser: The docstring parser to parse the docstring with. By default, no parsing is done.
**kwargs: Additional serialization or docstring parsing options.
Returns:
A dictionary.
"""
base: dict[str, Any] = {
"value": self.value,
"lineno": self.lineno,
"endlineno": self.endlineno,
}
if full:
base["parsed"] = self.parse(docstring_parser, **kwargs)
return base
class Parameter:
"""This class represent a function parameter.
Attributes:
name: The parameter name.
annotation: The parameter annotation, if any.
kind: The parameter kind.
default: The parameter default, if any.
"""
def __init__(
self,
name: str,
*,
annotation: str | Name | Expression | None = None,
kind: ParameterKind | None = None,
default: str | None = None,
) -> None:
"""Initialize the parameter.
Parameters:
name: The parameter name.
annotation: The parameter annotation, if any.
kind: The parameter kind.
default: The parameter default, if any.
"""
self.name: str = name
self.annotation: str | Name | Expression | None = annotation
self.kind: ParameterKind | None = kind
self.default: str | None = default
def __str__(self) -> str:
param = f"{self.name}: {self.annotation} = {self.default}"
if self.kind:
return f"[{self.kind.value}] {param}"
return param
@property
def required(self) -> bool:
"""Tell if this parameter is required.
Returns:
True or False.
"""
return self.default is None
def as_dict(self, **kwargs: Any) -> dict[str, Any]: # noqa: ARG002
"""Return this parameter's data as a dictionary.
Parameters:
**kwargs: Additional serialization options.
Returns:
A dictionary.
"""
return {
"name": self.name,
"annotation": self.annotation,
"kind": self.kind,
"default": self.default,
}
class Parameters:
"""This class is a container for parameters.
It allows to get parameters using their position (index) or their name.
"""
def __init__(self, *parameters: Parameter) -> None:
"""Initialize the parameters container.
Parameters:
*parameters: The initial parameters to add to the container.
"""
self._parameters_list: list[Parameter] = []
self._parameters_dict: dict[str, Parameter] = {}
for parameter in parameters:
self.add(parameter)
def __getitem__(self, name_or_index: int | str) -> Parameter:
if isinstance(name_or_index, int):
return self._parameters_list[name_or_index]
return self._parameters_dict[name_or_index.lstrip("*")]
def __len__(self):
return len(self._parameters_list)
def __iter__(self):
return iter(self._parameters_list)
def __contains__(self, param_name: str):
return param_name.lstrip("*") in self._parameters_dict
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 not in self._parameters_dict:
self._parameters_dict[parameter.name] = parameter
self._parameters_list.append(parameter)
else:
raise ValueError(f"parameter {parameter.name} already present")
class Kind(enum.Enum):
"""Enumeration of the different objects kinds.
Attributes:
MODULE: The module kind.
CLASS: The class kind.
FUNCTION: The function kind.
ATTRIBUTE: The attribute kind.
"""
MODULE: str = "module"
CLASS: str = "class"
FUNCTION: str = "function"
ATTRIBUTE: str = "attribute"
ALIAS: str = "alias"
class Object(GetMembersMixin, SetMembersMixin, ObjectAliasMixin, SerializationMixin):
"""An abstract class representing a Python object.
Attributes:
kind: The object kind.
name: The object name.
lineno: The object starting line, or None for modules. Lines start at 1.
endlineno: The object ending line (inclusive), or None for modules.
docstring: The object docstring.
parent: The object parent, or None if it is the top module.
members: The object members.
labels: The object labels.
"""
kind: Kind
is_alias: bool = False
is_collection: bool = False
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
self.lineno: int | None = lineno
self.endlineno: int | None = endlineno
self.docstring: Docstring | None = docstring
self.parent: Module | Class | None = parent
self.members: dict[str, Object | Alias] = {}
self.labels: set[str] = set()
self.imports: dict[str, str] = {}
self.exports: set[str] | list[str | Name] | None = None
self.aliases: dict[str, Alias] = {}
self.runtime: bool = runtime
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})>"
def __bool__(self) -> bool:
return True
def __len__(self) -> int:
return len(self.members) + sum(len(member) for member in self.members.values())
@property
def has_docstring(self) -> bool:
"""Tell if this object has a non-empty docstring."""
return bool(self.docstring)
@property
def has_docstrings(self) -> bool:
"""Tell if this object or any of its members has a non-empty docstring."""
if self.has_docstring:
return True
return any(member.has_docstrings for member in self.members.values())
def member_is_exported(self, member: Object | Alias, *, explicitely: bool = True) -> bool:
"""Tell if a member of this object is "exported".
By exported, we mean that the object is included in the `__all__` attribute
of its parent module or class. When `_all__` is not defined,
we consider the member to be *implicitely* exported,
unless it's a module and it was not imported,
and unless it's not defined at runtime.
Parameters:
member: The member to verify.
explicitely: Whether to only return True when `__all__` is defined.
Returns:
True or False.
"""
if not member.runtime:
return False
if self.exports is None:
return not explicitely and (member.is_alias or not member.is_module or member.name in self.imports)
return member.name in self.exports
def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool:
"""Tell if this object is of the given kind.
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 is_module(self) -> bool:
"""Tell if this object is a module."""
return self.kind is Kind.MODULE
@property
def is_class(self) -> bool:
"""Tell if this object is a class."""
return self.kind is Kind.CLASS
@property
def is_function(self) -> bool:
"""Tell if this object is a function."""
return self.kind is Kind.FUNCTION
@property
def is_attribute(self) -> bool:
"""Tell if this object is an attribute."""
return self.kind is Kind.ATTRIBUTE
def has_labels(self, labels: set[str]) -> bool:
"""Tell if this object has all the given labels.
Parameters:
labels: A set of labels.
Returns:
True or False.
"""
return all(label in self.labels for label in labels)
def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]:
"""Filter and return members based on predicates.
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] = {}
for name, member in self.members.items():
if all(predicate(member) for predicate in predicates):
members[name] = member
return members
@property
def modules(self) -> dict[str, Module]:
"""Return the module members.
Returns:
A dictionary of modules.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.MODULE} # type: ignore[misc]
@property
def classes(self) -> dict[str, Class]:
"""Return the class members.
Returns:
A dictionary of classes.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.CLASS} # type: ignore[misc]
@property
def functions(self) -> dict[str, Function]:
"""Return the function members.
Returns:
A dictionary of functions.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.FUNCTION} # type: ignore[misc]
@property
def attributes(self) -> dict[str, Attribute]:
"""Return the attribute members.
Returns:
A dictionary of attributes.
"""
return {name: member for name, member in self.members.items() if member.kind is Kind.ATTRIBUTE} # type: ignore[misc]
@cached_property
def module(self) -> Module:
"""Return the parent module of this object.
Raises:
ValueError: When the object is not a module and does not have a parent.
Returns:
The parent module.
"""
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")
@cached_property
def package(self) -> Module:
"""Return the absolute top module (the package) of this object.
Returns:
The parent module.
"""
module = self.module
while module.parent:
module = module.parent # type: ignore[assignment] # always a module
return module
@cached_property
def filepath(self) -> Path | list[Path]:
"""Return the file path where this object was defined.
Returns:
A file path or a list of directories.
"""
return self.module.filepath
@cached_property
def relative_package_filepath(self) -> Path:
"""Return the file path where this object was defined, relative to the top module path.
Raises:
ValueError: When the relative path could not be computed.
Returns:
A file path.
"""
package_path = self.package.filepath
if isinstance(self.filepath, list):
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)
else:
for self_path in self.filepath:
with suppress(ValueError):
return self_path.relative_to(package_path.parent.parent)
raise ValueError
if isinstance(package_path, list):
for pkg_path in package_path:
with suppress(ValueError):
return self.filepath.relative_to(pkg_path.parent)
raise ValueError
return self.filepath.relative_to(package_path.parent.parent)
@cached_property
def relative_filepath(self) -> Path:
"""Return 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.
Raises:
ValueError: When the relative path could not be computed.
Returns:
A file path.
"""
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
@cached_property
def path(self) -> str:
"""Return the dotted path of this object.
On regular objects (not aliases), the path is the canonical path.
Returns:
A dotted path.
"""
return self.canonical_path
@cached_property
def canonical_path(self) -> str:
"""Return the full dotted path of this object.
The canonical path is the path where the object was defined (not imported).
Returns:
A dotted path.
"""
if self.parent is None:
return self.name
return ".".join((self.parent.path, self.name))
@cached_property
def modules_collection(self) -> ModulesCollection:
"""Return 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.
Returns:
A modules collection.
"""
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
@cached_property
def lines_collection(self) -> LinesCollection:
"""Return the lines collection attached to this object or its parents.
Raises:
ValueError: When no modules collection can be found in the object or its parents.
Returns:
A lines collection.
"""
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
@cached_property
def lines(self) -> list[str]:
"""Return the lines containing the source of this object.
Returns:
A list of lines.
"""
try:
filepath = self.filepath
except BuiltinModuleError:
return []
if isinstance(filepath, list):
return []
# TODO: remove once Python 3.7 support is dropped
if self.lineno and self.endlineno is None and sys.version_info < (3, 8):
self.endlineno = self._endlineno
try:
lines = self.lines_collection[filepath]
except KeyError:
return []
if self.lineno is None or self.endlineno is None:
return lines
return lines[self.lineno - 1 : self.endlineno]
@cached_property
def source(self) -> str:
"""Return the source code of this object.
Returns:
The source code.
"""
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.
"""
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
if name in self.imports:
return self.imports[name]
if self.parent is None:
# could be a built-in
raise NameResolutionError(f"{name} could not be resolved in the scope of {self.path}")
if name == self.parent.name and not self.parent.is_module:
return self.parent.path
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.
Parameters:
full: Whether to return full info, or just base info.
**kwargs: Additional serialization options.
Returns:
A dictionary.
"""
base = {
"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:
base["lineno"] = self.lineno
if self.endlineno:
base["endlineno"] = self.endlineno
if self.docstring:
base["docstring"] = self.docstring
# doing this last for a prettier JSON dump
base["labels"] = self.labels
base["members"] = [member.as_dict(full=full, **kwargs) for member in self.members.values()]
return base
# TODO: remove once Python 3.7 support is dropped
@property
def _endlineno(self) -> int | None:
if self.kind is Kind.MODULE:
if isinstance(self.filepath, list):
return 0
return len(self.lines_collection[self.filepath])
if isinstance(self.filepath, list):
return None
tokens, tokens_by_line = self.lines_collection.tokens(self.filepath)
first_token_index = tokens_by_line[self.lineno][0]
blockfinder = inspect.BlockFinder()
with suppress(inspect.EndOfBlock, IndentationError):
for token in tokens[first_token_index:]:
blockfinder.tokeneater(*token)
return blockfinder.last
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.dataclasses.Kind]
Attributes:
name: The alias name.
lineno: The alias starting line number.
endlineno: The alias ending line number.
parent: The alias parent.
target_path: The alias target path.
"""
is_alias: bool = True
is_collection: bool = False
def __init__(
self,
name: str,
target: str | Object | Alias,
*,
lineno: int | None = None,
endlineno: int | None = None,
runtime: bool = True,
parent: Module | Class | None = None,
) -> 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.
"""
self.name: str = name
self.alias_lineno: int | None = lineno
self.alias_endlineno: int | None = endlineno
self.runtime: bool = runtime
self._parent: Module | Class | None = parent
self._passed_through: bool = False
if isinstance(target, str):
self._target: Object | Alias | None = None
self.target_path: str = 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})>"
def __getitem__(self, key: str | tuple[str, ...]):
# not handled by __getattr__
return self.target[key]
def __setitem__(self, key: str | tuple[str, ...], value: Object | Alias):
# not handled by __getattr__
self.target[key] = value
def __len__(self) -> int:
return 1
# SPECIAL PROXIES -------------------------------
@property
def kind(self) -> Kind:
"""Return the target's kind, or Kind.ALIAS if the target cannot be resolved.
Returns:
A kind.
"""
# custom behavior to avoid raising exceptions
try:
return self.final_target.kind
except (AliasResolutionError, CyclicAliasError):
return Kind.ALIAS
@property
def lineno(self) -> int | None:
"""Return the target lineno or the alias lineno.
Returns:
The target lineno or the alias lineno.
"""
return self.final_target.lineno
@property
def endlineno(self) -> int | None:
"""Return the target endlineno or the alias endlineno.
Returns:
The target endlineno or the alias endlineno.
"""
return self.final_target.endlineno
@property
def has_docstring(self) -> bool:
"""Tell if this alias' target has a non-empty docstring."""
try:
return self.final_target.has_docstring
except (AliasResolutionError, CyclicAliasError):
return False
@property
def has_docstrings(self) -> bool:
"""Tell if this alias' target or any of its members has a non-empty docstring."""
try:
return self.final_target.has_docstrings
except (AliasResolutionError, CyclicAliasError):
return False
@property
def parent(self) -> Module | Class | None:
"""Return the parent of this alias.
Returns:
The parent.
"""
return self._parent
@parent.setter
def parent(self, value: Module | Class) -> None:
self._parent = value
self._update_target_aliases()
@cached_property
def path(self) -> str:
"""Return the dotted path / import path of this object.
Returns:
A dotted path.
"""
return ".".join((self.parent.path, self.name)) # type: ignore[union-attr] # we assume there's always a parent
@cached_property
def modules_collection(self) -> ModulesCollection:
"""Return the modules collection attached to the alias parents.
Returns:
A modules collection.
"""
# no need to forward to the target
return self.parent.modules_collection # type: ignore[union-attr] # we assume there's always a parent
# GENERIC OBJECT PROXIES --------------------------------
@property
def docstring(self) -> Docstring | None: # noqa: D102
return self.final_target.docstring
@docstring.setter
def docstring(self, docstring: Docstring | None) -> None:
self.final_target.docstring = docstring
@property
def members(self) -> dict[str, Object | Alias]: # noqa: D102
return self.final_target.members
@property
def labels(self) -> set[str]: # noqa: D102
return self.final_target.labels
@property
def imports(self) -> dict[str, str]: # noqa: D102
return self.final_target.imports
@property
def exports(self) -> set[str] | list[str | Name] | None: # noqa: D102
return self.final_target.exports
@property
def aliases(self) -> dict[str, Alias]: # noqa: D102
return self.final_target.aliases
def member_is_exported(self, member: Object | Alias, *, explicitely: bool = True) -> bool: # noqa: D102
return self.final_target.member_is_exported(member, explicitely=explicitely)
def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool: # noqa: D102
return self.final_target.is_kind(kind)
@property
def is_module(self) -> bool: # noqa: D102
return self.final_target.is_module
@property
def is_class(self) -> bool: # noqa: D102
return self.final_target.is_class
@property
def is_function(self) -> bool: # noqa: D102
return self.final_target.is_function
@property
def is_attribute(self) -> bool: # noqa: D102
return self.final_target.is_attribute
def has_labels(self, labels: set[str]) -> bool: # noqa: D102
return self.final_target.has_labels(labels)
def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]: # noqa: D102
return self.final_target.filter_members(*predicates)
@property
def modules(self) -> dict[str, Module]: # noqa: D102
return self.final_target.modules
@property
def classes(self) -> dict[str, Class]: # noqa: D102
return self.final_target.classes
@property
def functions(self) -> dict[str, Function]: # noqa: D102
return self.final_target.functions