| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import inspect |
| 7 |
from collections import defaultdict |
| 8 |
from contextlib import suppress |
| 9 |
from dataclasses import asdict |
| 10 |
from pathlib import Path |
| 11 |
from textwrap import dedent |
| 12 |
from typing import TYPE_CHECKING, Any, Literal, cast |
| 13 |
|
| 14 |
from griffe._internal.c3linear import c3linear_merge |
| 15 |
from griffe._internal.docstrings.parsers import DocstringOptions, DocstringStyle, parse |
| 16 |
from griffe._internal.enumerations import Kind, ParameterKind, Parser, TypeParameterKind |
| 17 |
from griffe._internal.exceptions import AliasResolutionError, BuiltinModuleError, CyclicAliasError, NameResolutionError |
| 18 |
from griffe._internal.expressions import ExprCall, ExprName, ExprTuple |
| 19 |
from griffe._internal.logger import logger |
| 20 |
from griffe._internal.mixins import ObjectAliasMixin |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from collections.abc import Callable, Sequence |
| 24 |
|
| 25 |
from griffe._internal.collections import LinesCollection, ModulesCollection |
| 26 |
from griffe._internal.docstrings.models import DocstringSection |
| 27 |
from griffe._internal.expressions import Expr |
| 28 |
from griffe._internal.git import GitInfo |
| 29 |
|
| 30 |
|
| 31 |
from functools import cached_property |
| 32 |
|
| 33 |
|
| 34 |
class Decorator: |
| 35 |
"""This class represents decorators.""" |
| 36 |
|
| 37 |
def __init__(self, value: str | Expr, *, lineno: int | None, endlineno: int | None) -> None: |
| 38 |
"""Initialize the decorator. |
| 39 |
|
| 40 |
Parameters: |
| 41 |
value: The decorator code. |
| 42 |
lineno: The starting line number. |
| 43 |
endlineno: The ending line number. |
| 44 |
""" |
| 45 |
self.value: str | Expr = value |
| 46 |
"""The decorator value (as a Griffe expression or string).""" |
| 47 |
self.lineno: int | None = lineno |
| 48 |
"""The starting line number of the decorator.""" |
| 49 |
self.endlineno: int | None = endlineno |
| 50 |
"""The ending line number of the decorator.""" |
| 51 |
|
| 52 |
@property |
| 53 |
def callable_path(self) -> str: |
| 54 |
"""The path of the callable used as decorator.""" |
| 55 |
value = self.value.function if isinstance(self.value, ExprCall) else self.value |
| 56 |
return value if isinstance(value, str) else value.canonical_path |
| 57 |
|
| 58 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 59 |
"""Return this decorator's data as a dictionary. |
| 60 |
|
| 61 |
Parameters: |
| 62 |
**kwargs: Additional serialization options. |
| 63 |
|
| 64 |
Returns: |
| 65 |
A dictionary. |
| 66 |
""" |
| 67 |
return { |
| 68 |
"value": self.value, |
| 69 |
"lineno": self.lineno, |
| 70 |
"endlineno": self.endlineno, |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
class Docstring: |
| 75 |
"""This class represents docstrings.""" |
| 76 |
|
| 77 |
def __init__( |
| 78 |
self, |
| 79 |
value: str, |
| 80 |
*, |
| 81 |
lineno: int | None = None, |
| 82 |
endlineno: int | None = None, |
| 83 |
parent: Object | None = None, |
| 84 |
parser: DocstringStyle | Parser | None = None, |
| 85 |
parser_options: DocstringOptions | None = None, |
| 86 |
) -> None: |
| 87 |
"""Initialize the docstring. |
| 88 |
|
| 89 |
Parameters: |
| 90 |
value: The docstring value. |
| 91 |
lineno: The starting line number. |
| 92 |
endlineno: The ending line number. |
| 93 |
parent: The parent object on which this docstring is attached. |
| 94 |
parser: The docstring parser to use. By default, no parsing is done. |
| 95 |
parser_options: Additional docstring parsing options. |
| 96 |
""" |
| 97 |
self.value: str = inspect.cleandoc(value.rstrip()) |
| 98 |
"""The original value of the docstring, cleaned by `inspect.cleandoc`. |
| 99 |
|
| 100 |
See also: [`source`][griffe.Docstring.source]. |
| 101 |
""" |
| 102 |
|
| 103 |
self.lineno: int | None = lineno |
| 104 |
"""The starting line number of the docstring. |
| 105 |
|
| 106 |
See also: [`endlineno`][griffe.Docstring.endlineno].""" |
| 107 |
|
| 108 |
self.endlineno: int | None = endlineno |
| 109 |
"""The ending line number of the docstring. |
| 110 |
|
| 111 |
See also: [`lineno`][griffe.Docstring.lineno].""" |
| 112 |
|
| 113 |
self.parent: Object | None = parent |
| 114 |
"""The object this docstring is attached to.""" |
| 115 |
|
| 116 |
self.parser: DocstringStyle | Parser | None = parser |
| 117 |
"""The selected docstring parser. |
| 118 |
|
| 119 |
See also: [`parser_options`][griffe.Docstring.parser_options], |
| 120 |
[`parse`][griffe.Docstring.parse]. |
| 121 |
""" |
| 122 |
|
| 123 |
self.parser_options: DocstringOptions = parser_options or {} |
| 124 |
"""The configured parsing options. |
| 125 |
|
| 126 |
See also: [`parser`][griffe.Docstring.parser], |
| 127 |
[`parse`][griffe.Docstring.parse]. |
| 128 |
""" |
| 129 |
|
| 130 |
@property |
| 131 |
def lines(self) -> list[str]: |
| 132 |
"""The lines of the docstring. |
| 133 |
|
| 134 |
See also: [`source`][griffe.Docstring.source]. |
| 135 |
""" |
| 136 |
return self.value.split("\n") |
| 137 |
|
| 138 |
@property |
| 139 |
def source(self) -> str: |
| 140 |
"""The original, uncleaned value of the docstring as written in the source. |
| 141 |
|
| 142 |
It is a simple concatenation of the source lines. These source lines will include |
| 143 |
quotes (single/double/triple) and might include leading whitespace and indentation, |
| 144 |
as well as trailing comments. |
| 145 |
|
| 146 |
Raises: |
| 147 |
ValueError: If the original docstring cannot be retrieved |
| 148 |
(no parent, no line numbers, or attached to namespace package). |
| 149 |
|
| 150 |
See also: [`value`][griffe.Docstring.value]. |
| 151 |
""" |
| 152 |
if self.parent is None: |
| 153 |
raise ValueError("Cannot get original docstring without parent object") |
| 154 |
if isinstance(self.parent.filepath, list): |
| 155 |
raise ValueError("Cannot get original docstring for namespace package") |
| 156 |
if self.lineno is None or self.endlineno is None: |
| 157 |
raise ValueError("Cannot get original docstring without line numbers") |
| 158 |
return "\n".join(self.parent.lines_collection[self.parent.filepath][self.lineno - 1 : self.endlineno]) |
| 159 |
|
| 160 |
@cached_property |
| 161 |
def parsed(self) -> list[DocstringSection]: |
| 162 |
"""The docstring sections, parsed into structured data.""" |
| 163 |
return self.parse() |
| 164 |
|
| 165 |
def parse( |
| 166 |
self, |
| 167 |
parser: DocstringStyle | Parser | None = None, |
| 168 |
**options: Any, |
| 169 |
) -> list[DocstringSection]: |
| 170 |
"""Parse the docstring into structured data. |
| 171 |
|
| 172 |
See also: [`parser`][griffe.Docstring.parser], |
| 173 |
[`parser_options`][griffe.Docstring.parser_options]. |
| 174 |
|
| 175 |
Parameters: |
| 176 |
parser: The docstring parser to use. |
| 177 |
In order: use the given parser, or the self parser, or no parser (return a single text section). |
| 178 |
**options: Additional docstring parsing options. |
| 179 |
|
| 180 |
Returns: |
| 181 |
The parsed docstring as a list of sections. |
| 182 |
""" |
| 183 |
return parse(self, parser or self.parser, **(options or self.parser_options)) |
| 184 |
|
| 185 |
def as_dict( |
| 186 |
self, |
| 187 |
*, |
| 188 |
full: bool = False, |
| 189 |
**kwargs: Any, |
| 190 |
) -> dict[str, Any]: |
| 191 |
"""Return this docstring's data as a dictionary. |
| 192 |
|
| 193 |
Parameters: |
| 194 |
full: Whether to return full info, or just base info. |
| 195 |
**kwargs: Additional serialization options. |
| 196 |
|
| 197 |
Returns: |
| 198 |
A dictionary. |
| 199 |
""" |
| 200 |
base: dict[str, Any] = { |
| 201 |
"value": self.value, |
| 202 |
"lineno": self.lineno, |
| 203 |
"endlineno": self.endlineno, |
| 204 |
} |
| 205 |
if full: |
| 206 |
base["parsed"] = self.parsed |
| 207 |
return base |
| 208 |
|
| 209 |
|
| 210 |
class Parameter: |
| 211 |
"""This class represent a function parameter. |
| 212 |
|
| 213 |
See also: [`Parameters`][griffe.Parameters]. |
| 214 |
""" |
| 215 |
|
| 216 |
def __init__( |
| 217 |
self, |
| 218 |
name: str, |
| 219 |
*, |
| 220 |
annotation: str | Expr | None = None, |
| 221 |
kind: ParameterKind | None = None, |
| 222 |
default: str | Expr | None = None, |
| 223 |
docstring: Docstring | None = None, |
| 224 |
) -> None: |
| 225 |
"""Initialize the parameter. |
| 226 |
|
| 227 |
Parameters: |
| 228 |
name: The parameter name, without leading stars (`*` or `**`). |
| 229 |
annotation: The parameter annotation, if any. |
| 230 |
kind: The parameter kind. |
| 231 |
default: The parameter default, if any. |
| 232 |
docstring: The parameter docstring. |
| 233 |
""" |
| 234 |
self.name: str = name |
| 235 |
"""The parameter name.""" |
| 236 |
self.annotation: str | Expr | None = annotation |
| 237 |
"""The parameter type annotation.""" |
| 238 |
self.kind: ParameterKind | None = kind |
| 239 |
"""The parameter kind.""" |
| 240 |
self.default: str | Expr | None = default |
| 241 |
"""The parameter default value.""" |
| 242 |
self.docstring: Docstring | None = docstring |
| 243 |
"""The parameter docstring.""" |
| 244 |
|
| 245 |
|
| 246 |
self.function: Function | None = None |
| 247 |
"""The parent function of the parameter.""" |
| 248 |
|
| 249 |
def __str__(self) -> str: |
| 250 |
param = f"{self.name}: {self.annotation} = {self.default}" |
| 251 |
if self.kind: |
| 252 |
return f"[{self.kind.value}] {param}" |
| 253 |
return param |
| 254 |
|
| 255 |
def __repr__(self) -> str: |
| 256 |
return f"Parameter(name={self.name!r}, annotation={self.annotation!r}, kind={self.kind!r}, default={self.default!r})" |
| 257 |
|
| 258 |
def __eq__(self, value: object, /) -> bool: |
| 259 |
"""Parameters are equal if all their attributes except `docstring` and `function` are equal.""" |
| 260 |
if not isinstance(value, Parameter): |
| 261 |
return NotImplemented |
| 262 |
return ( |
| 263 |
self.name == value.name |
| 264 |
and self.annotation == value.annotation |
| 265 |
and self.kind == value.kind |
| 266 |
and self.default == value.default |
| 267 |
) |
| 268 |
|
| 269 |
@property |
| 270 |
def required(self) -> bool: |
| 271 |
"""Whether this parameter is required.""" |
| 272 |
return self.default is None |
| 273 |
|
| 274 |
def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]: |
| 275 |
"""Return this parameter's data as a dictionary. |
| 276 |
|
| 277 |
Parameters: |
| 278 |
**kwargs: Additional serialization options. |
| 279 |
|
| 280 |
Returns: |
| 281 |
A dictionary. |
| 282 |
""" |
| 283 |
base: dict[str, Any] = { |
| 284 |
"name": self.name, |
| 285 |
"annotation": self.annotation, |
| 286 |
"kind": self.kind, |
| 287 |
"default": self.default, |
| 288 |
} |
| 289 |
if self.docstring: |
| 290 |
base["docstring"] = self.docstring.as_dict(full=full) |
| 291 |
return base |
| 292 |
|
| 293 |
|
| 294 |
class Parameters: |
| 295 |
"""This class is a container for parameters. |
| 296 |
|
| 297 |
It allows to get parameters using their position (index) or their name: |
| 298 |
|
| 299 |
```pycon |
| 300 |
>>> parameters = Parameters(Parameter("hello")) |
| 301 |
>>> parameters[0] is parameters["hello"] |
| 302 |
True |
| 303 |
``` |
| 304 |
|
| 305 |
See also: [`Parameter`][griffe.Parameter]. |
| 306 |
""" |
| 307 |
|
| 308 |
def __init__(self, *parameters: Parameter) -> None: |
| 309 |
"""Initialize the parameters container. |
| 310 |
|
| 311 |
Parameters: |
| 312 |
*parameters: The initial parameters to add to the container. |
| 313 |
""" |
| 314 |
self._params: list[Parameter] = list(parameters) |
| 315 |
|
| 316 |
def __repr__(self) -> str: |
| 317 |
return f"Parameters({', '.join(repr(param) for param in self._params)})" |
| 318 |
|
| 319 |
def __getitem__(self, name_or_index: int | str) -> Parameter: |
| 320 |
"""Get a parameter by index or name.""" |
| 321 |
if isinstance(name_or_index, int): |
| 322 |
return self._params[name_or_index] |
| 323 |
name = name_or_index.lstrip("*") |
| 324 |
try: |
| 325 |
return next(param for param in self._params if param.name == name) |
| 326 |
except StopIteration as error: |
| 327 |
raise KeyError(f"parameter {name_or_index} not found") from error |
| 328 |
|
| 329 |
def __setitem__(self, name_or_index: int | str, parameter: Parameter) -> None: |
| 330 |
"""Set a parameter by index or name.""" |
| 331 |
if isinstance(name_or_index, int): |
| 332 |
self._params[name_or_index] = parameter |
| 333 |
else: |
| 334 |
name = name_or_index.lstrip("*") |
| 335 |
try: |
| 336 |
index = next(idx for idx, param in enumerate(self._params) if param.name == name) |
| 337 |
except StopIteration: |
| 338 |
self._params.append(parameter) |
| 339 |
else: |
| 340 |
self._params[index] = parameter |
| 341 |
|
| 342 |
def __delitem__(self, name_or_index: int | str) -> None: |
| 343 |
"""Delete a parameter by index or name.""" |
| 344 |
if isinstance(name_or_index, int): |
| 345 |
del self._params[name_or_index] |
| 346 |
else: |
| 347 |
name = name_or_index.lstrip("*") |
| 348 |
try: |
| 349 |
index = next(idx for idx, param in enumerate(self._params) if param.name == name) |
| 350 |
except StopIteration as error: |
| 351 |
raise KeyError(f"parameter {name_or_index} not found") from error |
| 352 |
del self._params[index] |
| 353 |
|
| 354 |
def __len__(self): |
| 355 |
"""The number of parameters.""" |
| 356 |
return len(self._params) |
| 357 |
|
| 358 |
def __iter__(self): |
| 359 |
"""Iterate over the parameters, in order.""" |
| 360 |
return iter(self._params) |
| 361 |
|
| 362 |
def __contains__(self, param_name: str): |
| 363 |
"""Whether a parameter with the given name is present.""" |
| 364 |
try: |
| 365 |
next(param for param in self._params if param.name == param_name.lstrip("*")) |
| 366 |
except StopIteration: |
| 367 |
return False |
| 368 |
return True |
| 369 |
|
| 370 |
def add(self, parameter: Parameter) -> None: |
| 371 |
"""Add a parameter to the container. |
| 372 |
|
| 373 |
Parameters: |
| 374 |
parameter: The function parameter to add. |
| 375 |
|
| 376 |
Raises: |
| 377 |
ValueError: When a parameter with the same name is already present. |
| 378 |
""" |
| 379 |
if parameter.name in self: |
| 380 |
raise ValueError(f"parameter {parameter.name} already present") |
| 381 |
self._params.append(parameter) |
| 382 |
|
| 383 |
|
| 384 |
class TypeParameter: |
| 385 |
"""This class represents a type parameter.""" |
| 386 |
|
| 387 |
def __init__( |
| 388 |
self, |
| 389 |
name: str, |
| 390 |
*, |
| 391 |
kind: TypeParameterKind, |
| 392 |
bound: str | Expr | None = None, |
| 393 |
constraints: Sequence[str | Expr] | None = None, |
| 394 |
default: str | Expr | None = None, |
| 395 |
) -> None: |
| 396 |
"""Initialize the type parameter. |
| 397 |
|
| 398 |
Parameters: |
| 399 |
name: The type parameter name, without leading stars (`*` or `**`). |
| 400 |
kind: The type parameter kind. |
| 401 |
bound: The type parameter bound, if any. |
| 402 |
Mutually exclusive with `constraints`. |
| 403 |
constraints: The type parameter constraints, if any. |
| 404 |
Mutually exclusive with `bound`. |
| 405 |
default: The type parameter default, if any. |
| 406 |
|
| 407 |
Raises: |
| 408 |
ValueError: When more than one of `bound` and `constraints` is set. |
| 409 |
""" |
| 410 |
if bound is not None and constraints: |
| 411 |
raise ValueError("bound and constraints are mutually exclusive") |
| 412 |
|
| 413 |
self.name: str = name |
| 414 |
"""The type parameter name.""" |
| 415 |
|
| 416 |
self.kind: TypeParameterKind = kind |
| 417 |
"""The type parameter kind.""" |
| 418 |
|
| 419 |
self.annotation: str | Expr | None |
| 420 |
"""The type parameter bound or constraints.""" |
| 421 |
|
| 422 |
if constraints: |
| 423 |
self.constraints = constraints |
| 424 |
else: |
| 425 |
self.bound = bound |
| 426 |
|
| 427 |
self.default: str | Expr | None = default |
| 428 |
"""The type parameter default value.""" |
| 429 |
|
| 430 |
def __repr__(self) -> str: |
| 431 |
return f"TypeParameter(name={self.name!r}, kind={self.kind!r}, bound={self.annotation!r}, default={self.default!r})" |
| 432 |
|
| 433 |
@property |
| 434 |
def bound(self) -> str | Expr | None: |
| 435 |
"""The type parameter bound.""" |
| 436 |
if not isinstance(self.annotation, ExprTuple): |
| 437 |
return self.annotation |
| 438 |
return None |
| 439 |
|
| 440 |
@bound.setter |
| 441 |
def bound(self, bound: str | Expr | None) -> None: |
| 442 |
self.annotation = bound |
| 443 |
|
| 444 |
@property |
| 445 |
def constraints(self) -> tuple[str | Expr, ...] | None: |
| 446 |
"""The type parameter constraints.""" |
| 447 |
if isinstance(self.annotation, ExprTuple): |
| 448 |
return tuple(self.annotation.elements) |
| 449 |
return None |
| 450 |
|
| 451 |
@constraints.setter |
| 452 |
def constraints(self, constraints: Sequence[str | Expr] | None) -> None: |
| 453 |
if constraints is not None: |
| 454 |
self.annotation = ExprTuple(constraints) |
| 455 |
else: |
| 456 |
self.annotation = None |
| 457 |
|
| 458 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 459 |
"""Return this type parameter's data as a dictionary. |
| 460 |
|
| 461 |
Parameters: |
| 462 |
**kwargs: Additional serialization options. |
| 463 |
|
| 464 |
Returns: |
| 465 |
A dictionary. |
| 466 |
""" |
| 467 |
base: dict[str, Any] = { |
| 468 |
"name": self.name, |
| 469 |
"kind": self.kind, |
| 470 |
"annotation": self.annotation, |
| 471 |
"default": self.default, |
| 472 |
} |
| 473 |
return base |
| 474 |
|
| 475 |
|
| 476 |
class TypeParameters: |
| 477 |
"""This class is a container for type parameters. |
| 478 |
|
| 479 |
It allows to get type parameters using their position (index) or their name: |
| 480 |
|
| 481 |
```pycon |
| 482 |
>>> type_parameters = TypeParameters(TypeParameter("hello"), kind=TypeParameterKind.type_var) |
| 483 |
>>> type_parameters[0] is type_parameters["hello"] |
| 484 |
True |
| 485 |
``` |
| 486 |
""" |
| 487 |
|
| 488 |
def __init__(self, *type_parameters: TypeParameter) -> None: |
| 489 |
"""Initialize the type parameters container. |
| 490 |
|
| 491 |
Parameters: |
| 492 |
*type_parameters: The initial type parameters to add to the container. |
| 493 |
""" |
| 494 |
self._type_params: list[TypeParameter] = list(type_parameters) |
| 495 |
|
| 496 |
def __repr__(self) -> str: |
| 497 |
return f"TypeParameters({', '.join(repr(type_param) for type_param in self._type_params)})" |
| 498 |
|
| 499 |
def __getitem__(self, name_or_index: int | str) -> TypeParameter: |
| 500 |
"""Get a type parameter by index or name.""" |
| 501 |
if isinstance(name_or_index, int): |
| 502 |
return self._type_params[name_or_index] |
| 503 |
name = name_or_index.lstrip("*") |
| 504 |
try: |
| 505 |
return next(param for param in self._type_params if param.name == name) |
| 506 |
except StopIteration as error: |
| 507 |
raise KeyError(f"type parameter {name_or_index} not found") from error |
| 508 |
|
| 509 |
def __setitem__(self, name_or_index: int | str, type_parameter: TypeParameter) -> None: |
| 510 |
"""Set a type parameter by index or name.""" |
| 511 |
if isinstance(name_or_index, int): |
| 512 |
self._type_params[name_or_index] = type_parameter |
| 513 |
else: |
| 514 |
name = name_or_index.lstrip("*") |
| 515 |
try: |
| 516 |
index = next(idx for idx, param in enumerate(self._type_params) if param.name == name) |
| 517 |
except StopIteration: |
| 518 |
self._type_params.append(type_parameter) |
| 519 |
else: |
| 520 |
self._type_params[index] = type_parameter |
| 521 |
|
| 522 |
def __delitem__(self, name_or_index: int | str) -> None: |
| 523 |
"""Delete a type parameter by index or name.""" |
| 524 |
if isinstance(name_or_index, int): |
| 525 |
del self._type_params[name_or_index] |
| 526 |
else: |
| 527 |
name = name_or_index.lstrip("*") |
| 528 |
try: |
| 529 |
index = next(idx for idx, param in enumerate(self._type_params) if param.name == name) |
| 530 |
except StopIteration as error: |
| 531 |
raise KeyError(f"type parameter {name_or_index} not found") from error |
| 532 |
del self._type_params[index] |
| 533 |
|
| 534 |
def __len__(self): |
| 535 |
"""The number of type parameters.""" |
| 536 |
return len(self._type_params) |
| 537 |
|
| 538 |
def __iter__(self): |
| 539 |
"""Iterate over the type parameters, in order.""" |
| 540 |
return iter(self._type_params) |
| 541 |
|
| 542 |
def __contains__(self, type_param_name: str): |
| 543 |
"""Whether a type parameter with the given name is present.""" |
| 544 |
try: |
| 545 |
next(param for param in self._type_params if param.name == type_param_name.lstrip("*")) |
| 546 |
except StopIteration: |
| 547 |
return False |
| 548 |
return True |
| 549 |
|
| 550 |
def add(self, type_parameter: TypeParameter) -> None: |
| 551 |
"""Add a type parameter to the container. |
| 552 |
|
| 553 |
Parameters: |
| 554 |
type_parameter: The function parameter to add. |
| 555 |
|
| 556 |
Raises: |
| 557 |
ValueError: When a type parameter with the same name is already present. |
| 558 |
""" |
| 559 |
if type_parameter.name in self: |
| 560 |
raise ValueError(f"type parameter {type_parameter.name} already present") |
| 561 |
self._type_params.append(type_parameter) |
| 562 |
|
| 563 |
|
| 564 |
class Object(ObjectAliasMixin): |
| 565 |
"""An abstract class representing a Python object.""" |
| 566 |
|
| 567 |
kind: Kind |
| 568 |
"""The object kind.""" |
| 569 |
is_alias: bool = False |
| 570 |
"""Always false for objects.""" |
| 571 |
is_collection: bool = False |
| 572 |
"""Always false for objects.""" |
| 573 |
inherited: bool = False |
| 574 |
"""Always false for objects. |
| 575 |
|
| 576 |
Only aliases can be marked as inherited. |
| 577 |
""" |
| 578 |
|
| 579 |
def __init__( |
| 580 |
self, |
| 581 |
name: str, |
| 582 |
*, |
| 583 |
lineno: int | None = None, |
| 584 |
endlineno: int | None = None, |
| 585 |
runtime: bool = True, |
| 586 |
docstring: Docstring | None = None, |
| 587 |
type_parameters: TypeParameters | None = None, |
| 588 |
parent: Module | Class | None = None, |
| 589 |
lines_collection: LinesCollection | None = None, |
| 590 |
modules_collection: ModulesCollection | None = None, |
| 591 |
git_info: GitInfo | None = None, |
| 592 |
analysis: Literal["static", "dynamic"] | None = None, |
| 593 |
) -> None: |
| 594 |
"""Initialize the object. |
| 595 |
|
| 596 |
Parameters: |
| 597 |
name: The object name, as declared in the code. |
| 598 |
lineno: The object starting line, or None for modules. Lines start at 1. |
| 599 |
endlineno: The object ending line (inclusive), or None for modules. |
| 600 |
runtime: Whether this object is present at runtime or not. |
| 601 |
docstring: The object docstring. |
| 602 |
type_parameters: The object type parameters, if any. |
| 603 |
parent: The object parent. |
| 604 |
lines_collection: A collection of source code lines. |
| 605 |
modules_collection: A collection of modules. |
| 606 |
git_info: Git information. |
| 607 |
analysis: The type of analysis used to load this object. |
| 608 |
None means the object was created manually. |
| 609 |
""" |
| 610 |
self.name: str = name |
| 611 |
"""The object name.""" |
| 612 |
|
| 613 |
self.lineno: int | None = lineno |
| 614 |
"""The starting line number of the object. |
| 615 |
|
| 616 |
See also: [`endlineno`][griffe.Object.endlineno]. |
| 617 |
""" |
| 618 |
|
| 619 |
self.endlineno: int | None = endlineno |
| 620 |
"""The ending line number of the object. |
| 621 |
|
| 622 |
See also: [`lineno`][griffe.Object.lineno]. |
| 623 |
""" |
| 624 |
|
| 625 |
self.docstring: Docstring | None = docstring |
| 626 |
"""The object docstring. |
| 627 |
|
| 628 |
See also: [`has_docstring`][griffe.Object.has_docstring], |
| 629 |
[`has_docstrings`][griffe.Object.has_docstrings]. |
| 630 |
""" |
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
|
| 635 |
self.type_parameters: TypeParameters = type_parameters or TypeParameters() |
| 636 |
"""The object type parameters.""" |
| 637 |
|
| 638 |
self.parent: Module | Class | None = parent |
| 639 |
"""The parent of the object (none if top module).""" |
| 640 |
|
| 641 |
self.members: dict[str, Object | Alias] = {} |
| 642 |
"""The object members (modules, classes, functions, attributes, type aliases). |
| 643 |
|
| 644 |
See also: [`inherited_members`][griffe.Object.inherited_members], |
| 645 |
[`get_member`][griffe.Object.get_member], |
| 646 |
[`set_member`][griffe.Object.set_member], |
| 647 |
[`filter_members`][griffe.Object.filter_members]. |
| 648 |
""" |
| 649 |
|
| 650 |
self.labels: set[str] = set() |
| 651 |
"""The object labels (`property`, `dataclass`, etc.). |
| 652 |
|
| 653 |
See also: [`has_labels`][griffe.Object.has_labels].""" |
| 654 |
|
| 655 |
self.imports: dict[str, str] = {} |
| 656 |
"""The other objects imported by this object. |
| 657 |
|
| 658 |
Keys are the names within the object (`from ... import ... as AS_NAME`), |
| 659 |
while the values are the actual names of the objects (`from ... import REAL_NAME as ...`). |
| 660 |
""" |
| 661 |
|
| 662 |
self.exports: list[str | ExprName] | None = None |
| 663 |
"""The names of the objects exported by this (module) object through the `__all__` variable. |
| 664 |
|
| 665 |
Exports can contain string (object names) or resolvable names, |
| 666 |
like other lists of exports coming from submodules: |
| 667 |
|
| 668 |
```python |
| 669 |
from .submodule import __all__ as submodule_all |
| 670 |
|
| 671 |
__all__ = ["hello", *submodule_all] |
| 672 |
``` |
| 673 |
|
| 674 |
Exports get expanded by the loader before it expands wildcards and resolves aliases. |
| 675 |
|
| 676 |
See also: [`GriffeLoader.expand_exports`][griffe.GriffeLoader.expand_exports]. |
| 677 |
""" |
| 678 |
|
| 679 |
self.aliases: dict[str, Alias] = {} |
| 680 |
"""The aliases pointing to this object.""" |
| 681 |
|
| 682 |
self.runtime: bool = runtime |
| 683 |
"""Whether this object is available at runtime. |
| 684 |
|
| 685 |
Typically, type-guarded objects (under an `if TYPE_CHECKING` condition) |
| 686 |
are not available at runtime. |
| 687 |
""" |
| 688 |
|
| 689 |
self.extra: dict[str, dict[str, Any]] = defaultdict(dict) |
| 690 |
"""Namespaced dictionaries storing extra metadata for this object, used by extensions.""" |
| 691 |
|
| 692 |
self.public: bool | None = None |
| 693 |
"""Whether this object is public.""" |
| 694 |
|
| 695 |
self.deprecated: bool | str | None = None |
| 696 |
"""Whether this object is deprecated (boolean or deprecation message).""" |
| 697 |
|
| 698 |
self.analysis: Literal["static", "dynamic"] | None = analysis |
| 699 |
"""The type of analysis used to load this object. |
| 700 |
|
| 701 |
None means the object was created manually. |
| 702 |
""" |
| 703 |
|
| 704 |
self._lines_collection: LinesCollection | None = lines_collection |
| 705 |
self._modules_collection: ModulesCollection | None = modules_collection |
| 706 |
self._git_info: GitInfo | None = git_info |
| 707 |
self._source_link: str | None = None |
| 708 |
|
| 709 |
|
| 710 |
if docstring: |
| 711 |
docstring.parent = self |
| 712 |
|
| 713 |
def __repr__(self) -> str: |
| 714 |
return f"{self.__class__.__name__}({self.name!r}, {self.lineno!r}, {self.endlineno!r})" |
| 715 |
|
| 716 |
|
| 717 |
def __bool__(self) -> bool: |
| 718 |
"""An object is always true-ish.""" |
| 719 |
return True |
| 720 |
|
| 721 |
def __len__(self) -> int: |
| 722 |
"""The number of members in this object, recursively.""" |
| 723 |
return len(self.members) + sum(len(member) for member in self.members.values()) |
| 724 |
|
| 725 |
@property |
| 726 |
def git_info(self) -> GitInfo | None: |
| 727 |
"""Git information for this object, if available.""" |
| 728 |
if self._git_info is not None or self.parent is None: |
| 729 |
return self._git_info |
| 730 |
return self.parent.git_info |
| 731 |
|
| 732 |
@git_info.setter |
| 733 |
def git_info(self, value: GitInfo | None) -> None: |
| 734 |
"""Set the Git information for this object.""" |
| 735 |
self._git_info = value |
| 736 |
|
| 737 |
@property |
| 738 |
def source_link(self) -> str | None: |
| 739 |
"""Source link for this object, if available.""" |
| 740 |
if self._source_link is not None: |
| 741 |
return self._source_link |
| 742 |
with suppress(BuiltinModuleError, ValueError): |
| 743 |
if (git_info := self.git_info) and isinstance(self.filepath, Path): |
| 744 |
|
| 745 |
|
| 746 |
filepath = self.filepath.relative_to(git_info.repository) |
| 747 |
if self.lineno is not None and self.endlineno is not None: |
| 748 |
self._source_link = git_info.get_source_link(filepath, self.lineno, self.endlineno) |
| 749 |
return self._source_link |
| 750 |
|
| 751 |
@source_link.setter |
| 752 |
def source_link(self, value: str | None) -> None: |
| 753 |
"""Set the source link for this object.""" |
| 754 |
self._source_link = value |
| 755 |
|
| 756 |
@property |
| 757 |
def has_docstring(self) -> bool: |
| 758 |
"""Whether this object has a docstring (empty or not). |
| 759 |
|
| 760 |
See also: [`docstring`][griffe.Object.docstring], |
| 761 |
[`has_docstrings`][griffe.Object.has_docstrings]. |
| 762 |
""" |
| 763 |
return bool(self.docstring) |
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
|
| 772 |
|
| 773 |
@property |
| 774 |
def has_docstrings(self) -> bool: |
| 775 |
"""Whether this object or any of its members has a docstring (empty or not). |
| 776 |
|
| 777 |
Inherited members are not considered. Imported members are not considered, |
| 778 |
unless they are also public. |
| 779 |
|
| 780 |
See also: [`docstring`][griffe.Object.docstring], |
| 781 |
[`has_docstring`][griffe.Object.has_docstring]. |
| 782 |
""" |
| 783 |
if self.has_docstring: |
| 784 |
return True |
| 785 |
for member in self.members.values(): |
| 786 |
try: |
| 787 |
if (not member.is_imported or member.is_public) and member.has_docstrings: |
| 788 |
return True |
| 789 |
except AliasResolutionError: |
| 790 |
continue |
| 791 |
return False |
| 792 |
|
| 793 |
def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool: |
| 794 |
"""Tell if this object is of the given kind. |
| 795 |
|
| 796 |
See also: [`is_module`][griffe.Object.is_module], |
| 797 |
[`is_class`][griffe.Object.is_class], |
| 798 |
[`is_function`][griffe.Object.is_function], |
| 799 |
[`is_attribute`][griffe.Object.is_attribute], |
| 800 |
[`is_type_alias`][griffe.Object.is_type_alias], |
| 801 |
[`is_alias`][griffe.Object.is_alias]. |
| 802 |
|
| 803 |
Parameters: |
| 804 |
kind: An instance or set of kinds (strings or enumerations). |
| 805 |
|
| 806 |
Raises: |
| 807 |
ValueError: When an empty set is given as argument. |
| 808 |
|
| 809 |
Returns: |
| 810 |
True or False. |
| 811 |
""" |
| 812 |
if isinstance(kind, set): |
| 813 |
if not kind: |
| 814 |
raise ValueError("kind must not be an empty set") |
| 815 |
return self.kind in (knd if isinstance(knd, Kind) else Kind(knd) for knd in kind) |
| 816 |
if isinstance(kind, str): |
| 817 |
kind = Kind(kind) |
| 818 |
return self.kind is kind |
| 819 |
|
| 820 |
@property |
| 821 |
def inherited_members(self) -> dict[str, Alias]: |
| 822 |
"""Members that are inherited from base classes. |
| 823 |
|
| 824 |
This method is part of the consumer API: |
| 825 |
do not use when producing Griffe trees! |
| 826 |
|
| 827 |
See also: [`members`][griffe.Object.members]. |
| 828 |
""" |
| 829 |
if not isinstance(self, Class): |
| 830 |
return {} |
| 831 |
try: |
| 832 |
mro = self.mro() |
| 833 |
except ValueError as error: |
| 834 |
logger.debug(error) |
| 835 |
return {} |
| 836 |
inherited_members = {} |
| 837 |
for base in reversed(mro): |
| 838 |
for name, member in base.members.items(): |
| 839 |
if name not in self.members: |
| 840 |
inherited_members[name] = Alias(name, member, parent=self, inherited=True) |
| 841 |
return inherited_members |
| 842 |
|
| 843 |
@property |
| 844 |
def is_module(self) -> bool: |
| 845 |
"""Whether this object is a module. |
| 846 |
|
| 847 |
See also: [`is_init_module`][griffe.Object.is_init_module]. |
| 848 |
[`is_class`][griffe.Object.is_class], |
| 849 |
[`is_function`][griffe.Object.is_function], |
| 850 |
[`is_attribute`][griffe.Object.is_attribute], |
| 851 |
[`is_type_alias`][griffe.Object.is_type_alias], |
| 852 |
[`is_alias`][griffe.Object.is_alias], |
| 853 |
[`is_kind`][griffe.Object.is_kind]. |
| 854 |
""" |
| 855 |
return self.kind is Kind.MODULE |
| 856 |
|
| 857 |
@property |
| 858 |
def is_class(self) -> bool: |
| 859 |
"""Whether this object is a class. |
| 860 |
|
| 861 |
See also: [`is_module`][griffe.Object.is_module]. |
| 862 |
[`is_function`][griffe.Object.is_function], |
| 863 |
[`is_attribute`][griffe.Object.is_attribute], |
| 864 |
[`is_type_alias`][griffe.Object.is_type_alias], |
| 865 |
[`is_alias`][griffe.Object.is_alias], |
| 866 |
[`is_kind`][griffe.Object.is_kind]. |
| 867 |
""" |
| 868 |
return self.kind is Kind.CLASS |
| 869 |
|
| 870 |
@property |
| 871 |
def is_function(self) -> bool: |
| 872 |
"""Whether this object is a function. |
| 873 |
|
| 874 |
See also: [`is_module`][griffe.Object.is_module]. |
| 875 |
[`is_class`][griffe.Object.is_class], |
| 876 |
[`is_attribute`][griffe.Object.is_attribute], |
| 877 |
[`is_type_alias`][griffe.Object.is_type_alias], |
| 878 |
[`is_alias`][griffe.Object.is_alias], |
| 879 |
[`is_kind`][griffe.Object.is_kind]. |
| 880 |
""" |
| 881 |
return self.kind is Kind.FUNCTION |
| 882 |
|
| 883 |
@property |
| 884 |
def is_attribute(self) -> bool: |
| 885 |
"""Whether this object is an attribute. |
| 886 |
|
| 887 |
See also: [`is_module`][griffe.Object.is_module]. |
| 888 |
[`is_class`][griffe.Object.is_class], |
| 889 |
[`is_function`][griffe.Object.is_function], |
| 890 |
[`is_type_alias`][griffe.Object.is_type_alias], |
| 891 |
[`is_alias`][griffe.Object.is_alias], |
| 892 |
[`is_kind`][griffe.Object.is_kind]. |
| 893 |
""" |
| 894 |
return self.kind is Kind.ATTRIBUTE |
| 895 |
|
| 896 |
@property |
| 897 |
def is_type_alias(self) -> bool: |
| 898 |
"""Whether this object is a type alias. |
| 899 |
|
| 900 |
See also: [`is_module`][griffe.Object.is_module]. |
| 901 |
[`is_class`][griffe.Object.is_class], |
| 902 |
[`is_function`][griffe.Object.is_function], |
| 903 |
[`is_attribute`][griffe.Object.is_attribute], |
| 904 |
[`is_alias`][griffe.Object.is_alias], |
| 905 |
[`is_kind`][griffe.Object.is_kind]. |
| 906 |
""" |
| 907 |
return self.kind is Kind.TYPE_ALIAS |
| 908 |
|
| 909 |
@property |
| 910 |
def is_init_method(self) -> bool: |
| 911 |
"""Whether this function is an `__init__` method.""" |
| 912 |
return False |
| 913 |
|
| 914 |
@property |
| 915 |
def is_init_module(self) -> bool: |
| 916 |
"""Whether this object is an `__init__.py` module. |
| 917 |
|
| 918 |
See also: [`is_module`][griffe.Object.is_module]. |
| 919 |
""" |
| 920 |
return False |
| 921 |
|
| 922 |
@property |
| 923 |
def is_package(self) -> bool: |
| 924 |
"""Whether this object is a package (top module). |
| 925 |
|
| 926 |
See also: [`is_subpackage`][griffe.Object.is_subpackage]. |
| 927 |
""" |
| 928 |
return False |
| 929 |
|
| 930 |
@property |
| 931 |
def is_subpackage(self) -> bool: |
| 932 |
"""Whether this object is a subpackage. |
| 933 |
|
| 934 |
See also: [`is_package`][griffe.Object.is_package]. |
| 935 |
""" |
| 936 |
return False |
| 937 |
|
| 938 |
@property |
| 939 |
def is_namespace_package(self) -> bool: |
| 940 |
"""Whether this object is a namespace package (top folder, no `__init__.py`). |
| 941 |
|
| 942 |
See also: [`is_namespace_subpackage`][griffe.Object.is_namespace_subpackage]. |
| 943 |
""" |
| 944 |
return False |
| 945 |
|
| 946 |
@property |
| 947 |
def is_namespace_subpackage(self) -> bool: |
| 948 |
"""Whether this object is a namespace subpackage. |
| 949 |
|
| 950 |
See also: [`is_namespace_package`][griffe.Object.is_namespace_package]. |
| 951 |
""" |
| 952 |
return False |
| 953 |
|
| 954 |
def has_labels(self, *labels: str) -> bool: |
| 955 |
"""Tell if this object has all the given labels. |
| 956 |
|
| 957 |
See also: [`labels`][griffe.Object.labels]. |
| 958 |
|
| 959 |
Parameters: |
| 960 |
*labels: Labels that must be present. |
| 961 |
|
| 962 |
Returns: |
| 963 |
True or False. |
| 964 |
""" |
| 965 |
return set(labels).issubset(self.labels) |
| 966 |
|
| 967 |
def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]: |
| 968 |
"""Filter and return members based on predicates. |
| 969 |
|
| 970 |
See also: [`members`][griffe.Object.members]. |
| 971 |
|
| 972 |
Parameters: |
| 973 |
*predicates: A list of predicates, i.e. callables accepting a member as argument and returning a boolean. |
| 974 |
|
| 975 |
Returns: |
| 976 |
A dictionary of members. |
| 977 |
""" |
| 978 |
if not predicates: |
| 979 |
return self.members |
| 980 |
members: dict[str, Object | Alias] = { |
| 981 |
name: member for name, member in self.members.items() if all(predicate(member) for predicate in predicates) |
| 982 |
} |
| 983 |
return members |
| 984 |
|
| 985 |
@property |
| 986 |
def module(self) -> Module: |
| 987 |
"""The parent module of this object. |
| 988 |
|
| 989 |
See also: [`package`][griffe.Object.package]. |
| 990 |
|
| 991 |
Examples: |
| 992 |
>>> import griffe |
| 993 |
>>> markdown = griffe.load("markdown") |
| 994 |
>>> markdown["core.Markdown.references"].module |
| 995 |
Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/core.py')) |
| 996 |
>>> # The `module` of a module is itself. |
| 997 |
>>> markdown["core"].module |
| 998 |
Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/core.py')) |
| 999 |
|
| 1000 |
Raises: |
| 1001 |
ValueError: When the object is not a module and does not have a parent. |
| 1002 |
""" |
| 1003 |
if isinstance(self, Module): |
| 1004 |
return self |
| 1005 |
if self.parent is not None: |
| 1006 |
return self.parent.module |
| 1007 |
raise ValueError(f"Object {self.name} does not have a parent module") |
| 1008 |
|
| 1009 |
@property |
| 1010 |
def package(self) -> Module: |
| 1011 |
"""The absolute top module (the package) of this object. |
| 1012 |
|
| 1013 |
See also: [`module`][griffe.Object.module]. |
| 1014 |
|
| 1015 |
Examples: |
| 1016 |
>>> import griffe |
| 1017 |
>>> markdown = griffe.load("markdown") |
| 1018 |
>>> markdown["core.Markdown.references"].package |
| 1019 |
Module(PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/__init__.py')) |
| 1020 |
""" |
| 1021 |
module = self.module |
| 1022 |
while module.parent: |
| 1023 |
module = module.parent |
| 1024 |
return module |
| 1025 |
|
| 1026 |
@property |
| 1027 |
def filepath(self) -> Path | list[Path]: |
| 1028 |
"""The file path (or directory list for namespace packages) where this object was defined. |
| 1029 |
|
| 1030 |
See also: [`relative_filepath`][griffe.Object.relative_filepath], |
| 1031 |
[`relative_package_filepath`][griffe.Object.relative_package_filepath]. |
| 1032 |
|
| 1033 |
Examples: |
| 1034 |
>>> import griffe |
| 1035 |
>>> markdown = griffe.load("markdown") |
| 1036 |
>>> markdown.filepath |
| 1037 |
PosixPath('~/project/.venv/lib/python3.11/site-packages/markdown/__init__.py') |
| 1038 |
""" |
| 1039 |
return self.module.filepath |
| 1040 |
|
| 1041 |
@property |
| 1042 |
def relative_package_filepath(self) -> Path: |
| 1043 |
"""The file path where this object was defined, relative to the top module path. |
| 1044 |
|
| 1045 |
See also: [`filepath`][griffe.Object.filepath], |
| 1046 |
[`relative_filepath`][griffe.Object.relative_filepath]. |
| 1047 |
|
| 1048 |
Raises: |
| 1049 |
ValueError: When the relative path could not be computed. |
| 1050 |
""" |
| 1051 |
package_path = self.package.filepath |
| 1052 |
|
| 1053 |
|
| 1054 |
if isinstance(self.filepath, list): |
| 1055 |
|
| 1056 |
if isinstance(package_path, list): |
| 1057 |
for pkg_path in package_path: |
| 1058 |
for self_path in self.filepath: |
| 1059 |
with suppress(ValueError): |
| 1060 |
return self_path.relative_to(pkg_path.parent) |
| 1061 |
|
| 1062 |
|
| 1063 |
|
| 1064 |
|
| 1065 |
else: |
| 1066 |
for self_path in self.filepath: |
| 1067 |
with suppress(ValueError): |
| 1068 |
return self_path.relative_to(package_path.parent.parent) |
| 1069 |
raise ValueError |
| 1070 |
|
| 1071 |
|
| 1072 |
|
| 1073 |
if isinstance(package_path, list): |
| 1074 |
for pkg_path in package_path: |
| 1075 |
with suppress(ValueError): |
| 1076 |
return self.filepath.relative_to(pkg_path.parent) |
| 1077 |
raise ValueError |
| 1078 |
|
| 1079 |
|
| 1080 |
|
| 1081 |
|
| 1082 |
|
| 1083 |
return self.filepath.relative_to(package_path.parent.parent) |
| 1084 |
|
| 1085 |
@property |
| 1086 |
def relative_filepath(self) -> Path: |
| 1087 |
"""The file path where this object was defined, relative to the current working directory. |
| 1088 |
|
| 1089 |
If this object's file path is not relative to the current working directory, return its absolute path. |
| 1090 |
|
| 1091 |
See also: [`filepath`][griffe.Object.filepath], |
| 1092 |
[`relative_package_filepath`][griffe.Object.relative_package_filepath]. |
| 1093 |
|
| 1094 |
Raises: |
| 1095 |
ValueError: When the relative path could not be computed. |
| 1096 |
""" |
| 1097 |
cwd = Path.cwd() |
| 1098 |
if isinstance(self.filepath, list): |
| 1099 |
for self_path in self.filepath: |
| 1100 |
with suppress(ValueError): |
| 1101 |
return self_path.relative_to(cwd) |
| 1102 |
raise ValueError(f"No directory in {self.filepath!r} is relative to the current working directory {cwd}") |
| 1103 |
try: |
| 1104 |
return self.filepath.relative_to(cwd) |
| 1105 |
except ValueError: |
| 1106 |
return self.filepath |
| 1107 |
|
| 1108 |
@property |
| 1109 |
def path(self) -> str: |
| 1110 |
"""The dotted path of this object. |
| 1111 |
|
| 1112 |
On regular objects (not aliases), the path is the canonical path. |
| 1113 |
|
| 1114 |
See also: [`canonical_path`][griffe.Object.canonical_path]. |
| 1115 |
|
| 1116 |
Examples: |
| 1117 |
>>> import griffe |
| 1118 |
>>> markdown = griffe.load("markdown") |
| 1119 |
>>> markdown["core.Markdown.references"].path |
| 1120 |
'markdown.core.Markdown.references' |
| 1121 |
""" |
| 1122 |
return self.canonical_path |
| 1123 |
|
| 1124 |
@property |
| 1125 |
def canonical_path(self) -> str: |
| 1126 |
"""The full dotted path of this object. |
| 1127 |
|
| 1128 |
The canonical path is the path where the object was defined (not imported). |
| 1129 |
|
| 1130 |
See also: [`path`][griffe.Object.path]. |
| 1131 |
""" |
| 1132 |
if self.parent is None: |
| 1133 |
return self.name |
| 1134 |
return f"{self.parent.path}.{self.name}" |
| 1135 |
|
| 1136 |
@property |
| 1137 |
def modules_collection(self) -> ModulesCollection: |
| 1138 |
"""The modules collection attached to this object or its parents. |
| 1139 |
|
| 1140 |
Raises: |
| 1141 |
ValueError: When no modules collection can be found in the object or its parents. |
| 1142 |
""" |
| 1143 |
if self._modules_collection is not None: |
| 1144 |
return self._modules_collection |
| 1145 |
if self.parent is None: |
| 1146 |
raise ValueError("no modules collection in this object or its parents") |
| 1147 |
return self.parent.modules_collection |
| 1148 |
|
| 1149 |
@property |
| 1150 |
def lines_collection(self) -> LinesCollection: |
| 1151 |
"""The lines collection attached to this object or its parents. |
| 1152 |
|
| 1153 |
See also: [`lines`][griffe.Object.lines], |
| 1154 |
[`source`][griffe.Object.source]. |
| 1155 |
|
| 1156 |
Raises: |
| 1157 |
ValueError: When no modules collection can be found in the object or its parents. |
| 1158 |
""" |
| 1159 |
if self._lines_collection is not None: |
| 1160 |
return self._lines_collection |
| 1161 |
if self.parent is None: |
| 1162 |
raise ValueError("no lines collection in this object or its parents") |
| 1163 |
return self.parent.lines_collection |
| 1164 |
|
| 1165 |
@property |
| 1166 |
def lines(self) -> list[str]: |
| 1167 |
"""The lines containing the source of this object. |
| 1168 |
|
| 1169 |
See also: [`lines_collection`][griffe.Object.lines_collection], |
| 1170 |
[`source`][griffe.Object.source]. |
| 1171 |
""" |
| 1172 |
try: |
| 1173 |
filepath = self.filepath |
| 1174 |
except BuiltinModuleError: |
| 1175 |
return [] |
| 1176 |
if isinstance(filepath, list): |
| 1177 |
return [] |
| 1178 |
try: |
| 1179 |
lines = self.lines_collection[filepath] |
| 1180 |
except KeyError: |
| 1181 |
return [] |
| 1182 |
if self.is_module: |
| 1183 |
return lines |
| 1184 |
if self.lineno is None or self.endlineno is None: |
| 1185 |
return [] |
| 1186 |
return lines[self.lineno - 1 : self.endlineno] |
| 1187 |
|
| 1188 |
@property |
| 1189 |
def source(self) -> str: |
| 1190 |
"""The source code of this object. |
| 1191 |
|
| 1192 |
See also: [`lines`][griffe.Object.lines], |
| 1193 |
[`lines_collection`][griffe.Object.lines_collection]. |
| 1194 |
""" |
| 1195 |
return dedent("\n".join(self.lines)) |
| 1196 |
|
| 1197 |
def resolve(self, name: str) -> str: |
| 1198 |
"""Resolve a name within this object's and parents' scope. |
| 1199 |
|
| 1200 |
Parameters: |
| 1201 |
name: The name to resolve. |
| 1202 |
|
| 1203 |
Raises: |
| 1204 |
NameResolutionError: When the name could not be resolved. |
| 1205 |
|
| 1206 |
Returns: |
| 1207 |
The resolved name. |
| 1208 |
""" |
| 1209 |
|
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
if name in self.type_parameters: |
| 1214 |
type_parameter = self.type_parameters[name] |
| 1215 |
if type_parameter.kind is TypeParameterKind.type_var_tuple: |
| 1216 |
prefix = "*" |
| 1217 |
elif type_parameter.kind is TypeParameterKind.param_spec: |
| 1218 |
prefix = "**" |
| 1219 |
else: |
| 1220 |
prefix = "" |
| 1221 |
return f"{self.path}[{prefix}{name}]" |
| 1222 |
|
| 1223 |
|
| 1224 |
if name in self.members: |
| 1225 |
if self.members[name].is_alias: |
| 1226 |
return self.members[name].target_path |
| 1227 |
return self.members[name].path |
| 1228 |
|
| 1229 |
|
| 1230 |
if self.parent is None: |
| 1231 |
raise NameResolutionError(f"{name} could not be resolved in the scope of {self.path}") |
| 1232 |
|
| 1233 |
|
| 1234 |
if name == self.parent.name and not self.parent.is_module: |
| 1235 |
return self.parent.path |
| 1236 |
|
| 1237 |
|
| 1238 |
return self.parent.resolve(name) |
| 1239 |
|
| 1240 |
def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]: |
| 1241 |
"""Return this object's data as a dictionary. |
| 1242 |
|
| 1243 |
See also: [`as_json`][griffe.Object.as_json]. |
| 1244 |
|
| 1245 |
Parameters: |
| 1246 |
full: Whether to return full info, or just base info. |
| 1247 |
**kwargs: Additional serialization options. |
| 1248 |
|
| 1249 |
Returns: |
| 1250 |
A dictionary. |
| 1251 |
""" |
| 1252 |
base: dict[str, Any] = { |
| 1253 |
"kind": self.kind, |
| 1254 |
"name": self.name, |
| 1255 |
"runtime": self.runtime, |
| 1256 |
} |
| 1257 |
|
| 1258 |
if self.public is not None: |
| 1259 |
base["public"] = self.public |
| 1260 |
if self.exports is not None: |
| 1261 |
base["exports"] = [str(export) for export in self.exports] |
| 1262 |
if self.imports: |
| 1263 |
base["imports"] = self.imports |
| 1264 |
if self.deprecated is not None: |
| 1265 |
base["deprecated"] = self.deprecated |
| 1266 |
if self.lineno is not None: |
| 1267 |
base["lineno"] = self.lineno |
| 1268 |
if self.endlineno is not None: |
| 1269 |
base["endlineno"] = self.endlineno |
| 1270 |
if self.docstring: |
| 1271 |
base["docstring"] = self.docstring |
| 1272 |
if self.type_parameters: |
| 1273 |
base["type_parameters"] = [type_param.as_dict(**kwargs) for type_param in self.type_parameters] |
| 1274 |
if self.labels: |
| 1275 |
base["labels"] = self.labels |
| 1276 |
if self.members: |
| 1277 |
base["members"] = {name: member.as_dict(full=full, **kwargs) for name, member in self.members.items()} |
| 1278 |
if self.analysis: |
| 1279 |
base["analysis"] = self.analysis |
| 1280 |
if self._git_info is not None: |
| 1281 |
base["git_info"] = asdict(self._git_info) |
| 1282 |
if self._source_link is not None: |
| 1283 |
base["source_link"] = self._source_link |
| 1284 |
|
| 1285 |
|
| 1286 |
if full: |
| 1287 |
base.update( |
| 1288 |
{ |
| 1289 |
"path": self.path, |
| 1290 |
"filepath": self.filepath, |
| 1291 |
"relative_package_filepath": self.relative_package_filepath, |
| 1292 |
"is_public": self.is_public, |
| 1293 |
"is_deprecated": self.is_deprecated, |
| 1294 |
"is_private": self.is_private, |
| 1295 |
"is_class_private": self.is_class_private, |
| 1296 |
"is_special": self.is_special, |
| 1297 |
"is_imported": self.is_imported, |
| 1298 |
"is_exported": self.is_exported, |
| 1299 |
"is_wildcard_exposed": self.is_wildcard_exposed, |
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
|
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
|
| 1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 1315 |
}, |
| 1316 |
) |
| 1317 |
|
| 1318 |
with suppress(ValueError): |
| 1319 |
base["relative_filepath"] = self.relative_filepath |
| 1320 |
|
| 1321 |
if "source_link" not in base and (source_link := self.source_link) is not None: |
| 1322 |
base["source_link"] = source_link |
| 1323 |
|
| 1324 |
return base |
| 1325 |
|
| 1326 |
|
| 1327 |
class Alias(ObjectAliasMixin): |
| 1328 |
"""This class represents an alias, or indirection, to an object declared in another module. |
| 1329 |
|
| 1330 |
Aliases represent objects that are in the scope of a module or class, |
| 1331 |
but were imported from another module. |
| 1332 |
|
| 1333 |
They behave almost exactly like regular objects, to a few exceptions: |
| 1334 |
|
| 1335 |
- line numbers are those of the alias, not the target |
| 1336 |
- the path is the alias path, not the canonical one |
| 1337 |
- the name can be different from the target's |
| 1338 |
- if the target can be resolved, the kind is the target's kind |
| 1339 |
- if the target cannot be resolved, the kind becomes [Kind.ALIAS][griffe.Kind] |
| 1340 |
""" |
| 1341 |
|
| 1342 |
is_alias: bool = True |
| 1343 |
"""Always true for aliases.""" |
| 1344 |
is_collection: bool = False |
| 1345 |
"""Always false for aliases. |
| 1346 |
|
| 1347 |
See also: [`ModulesCollection`][griffe.ModulesCollection]. |
| 1348 |
""" |
| 1349 |
|
| 1350 |
def __init__( |
| 1351 |
self, |
| 1352 |
name: str, |
| 1353 |
target: str | Object | Alias, |
| 1354 |
*, |
| 1355 |
lineno: int | None = None, |
| 1356 |
endlineno: int | None = None, |
| 1357 |
runtime: bool = True, |
| 1358 |
parent: Module | Class | Alias | None = None, |
| 1359 |
inherited: bool = False, |
| 1360 |
wildcard_imported: bool = False, |
| 1361 |
analysis: Literal["static", "dynamic"] | None = None, |
| 1362 |
) -> None: |
| 1363 |
"""Initialize the alias. |
| 1364 |
|
| 1365 |
Parameters: |
| 1366 |
name: The alias name. |
| 1367 |
target: If it's a string, the target resolution is delayed until accessing the target property. |
| 1368 |
If it's an object, or even another alias, the target is immediately set. |
| 1369 |
lineno: The alias starting line number. |
| 1370 |
endlineno: The alias ending line number. |
| 1371 |
runtime: Whether this alias is present at runtime or not. |
| 1372 |
parent: The alias parent. |
| 1373 |
inherited: Whether this alias wraps an inherited member. |
| 1374 |
wildcard_imported: Whether this alias was created using a wildcard import. |
| 1375 |
analysis: The type of analysis used to load this alias. |
| 1376 |
None means the alias was created manually. |
| 1377 |
""" |
| 1378 |
self.name: str = name |
| 1379 |
"""The alias name.""" |
| 1380 |
|
| 1381 |
self.alias_lineno: int | None = lineno |
| 1382 |
"""The starting line number of the alias.""" |
| 1383 |
|
| 1384 |
self.alias_endlineno: int | None = endlineno |
| 1385 |
"""The ending line number of the alias.""" |
| 1386 |
|
| 1387 |
self.runtime: bool = runtime |
| 1388 |
"""Whether this alias is available at runtime.""" |
| 1389 |
|
| 1390 |
self.inherited: bool = inherited |
| 1391 |
"""Whether this alias represents an inherited member.""" |
| 1392 |
|
| 1393 |
self.wildcard_imported: bool = wildcard_imported |
| 1394 |
"""Whether this alias was created using a wildcard import.""" |
| 1395 |
|
| 1396 |
self.public: bool | None = None |
| 1397 |
"""Whether this alias is public.""" |
| 1398 |
|
| 1399 |
self.deprecated: str | bool | None = None |
| 1400 |
"""Whether this alias is deprecated (boolean or deprecation message).""" |
| 1401 |
|
| 1402 |
self.analysis: Literal["static", "dynamic"] | None = analysis |
| 1403 |
"""The type of analysis used to load this alias. |
| 1404 |
|
| 1405 |
None means the alias was created manually. |
| 1406 |
""" |
| 1407 |
|
| 1408 |
self._parent: Module | Class | Alias | None = parent |
| 1409 |
self._passed_through: bool = False |
| 1410 |
|
| 1411 |
self.target_path: str |
| 1412 |
"""The path of this alias' target.""" |
| 1413 |
|
| 1414 |
if isinstance(target, str): |
| 1415 |
self._target: Object | Alias | None = None |
| 1416 |
self.target_path = target |
| 1417 |
else: |
| 1418 |
self._target = target |
| 1419 |
self.target_path = target.path |
| 1420 |
self._update_target_aliases() |
| 1421 |
|
| 1422 |
def __repr__(self) -> str: |
| 1423 |
return f"Alias({self.name!r}, {self.target_path!r})" |
| 1424 |
|
| 1425 |
|
| 1426 |
def __bool__(self) -> bool: |
| 1427 |
"""An alias is always true-ish.""" |
| 1428 |
return True |
| 1429 |
|
| 1430 |
def __len__(self) -> int: |
| 1431 |
"""The length of an alias is always 1.""" |
| 1432 |
return 1 |
| 1433 |
|
| 1434 |
|
| 1435 |
|
| 1436 |
|
| 1437 |
|
| 1438 |
@property |
| 1439 |
def kind(self) -> Kind: |
| 1440 |
"""The target's kind, or `Kind.ALIAS` if the target cannot be resolved. |
| 1441 |
|
| 1442 |
See also: [`is_kind`][griffe.Alias.is_kind]. |
| 1443 |
""" |
| 1444 |
|
| 1445 |
try: |
| 1446 |
return self.final_target.kind |
| 1447 |
except (AliasResolutionError, CyclicAliasError): |
| 1448 |
return Kind.ALIAS |
| 1449 |
|
| 1450 |
@property |
| 1451 |
def has_docstring(self) -> bool: |
| 1452 |
"""Whether this alias' target has a non-empty docstring. |
| 1453 |
|
| 1454 |
See also: [`has_docstrings`][griffe.Alias.has_docstrings], |
| 1455 |
[`docstring`][griffe.Alias.docstring]. |
| 1456 |
""" |
| 1457 |
try: |
| 1458 |
return self.final_target.has_docstring |
| 1459 |
except (AliasResolutionError, CyclicAliasError): |
| 1460 |
return False |
| 1461 |
|
| 1462 |
@property |
| 1463 |
def has_docstrings(self) -> bool: |
| 1464 |
"""Whether this alias' target or any of its members has a non-empty docstring. |
| 1465 |
|
| 1466 |
See also: [`has_docstring`][griffe.Alias.has_docstring], |
| 1467 |
[`docstring`][griffe.Alias.docstring]. |
| 1468 |
""" |
| 1469 |
try: |
| 1470 |
return self.final_target.has_docstrings |
| 1471 |
except (AliasResolutionError, CyclicAliasError): |
| 1472 |
return False |
| 1473 |
|
| 1474 |
@property |
| 1475 |
def parent(self) -> Module | Class | Alias | None: |
| 1476 |
"""The parent of this alias.""" |
| 1477 |
return self._parent |
| 1478 |
|
| 1479 |
@parent.setter |
| 1480 |
def parent(self, value: Module | Class | Alias) -> None: |
| 1481 |
self._parent = value |
| 1482 |
self._update_target_aliases() |
| 1483 |
|
| 1484 |
@property |
| 1485 |
def path(self) -> str: |
| 1486 |
"""The dotted path / import path of this object. |
| 1487 |
|
| 1488 |
See also: [`canonical_path`][griffe.Alias.canonical_path]. |
| 1489 |
""" |
| 1490 |
return f"{self.parent.path}.{self.name}" |
| 1491 |
|
| 1492 |
@property |
| 1493 |
def modules_collection(self) -> ModulesCollection: |
| 1494 |
"""The modules collection attached to the alias parents.""" |
| 1495 |
|
| 1496 |
return self.parent.modules_collection |
| 1497 |
|
| 1498 |
@property |
| 1499 |
def members(self) -> dict[str, Object | Alias]: |
| 1500 |
"""The target's members (modules, classes, functions, attributes, type aliases). |
| 1501 |
|
| 1502 |
See also: [`inherited_members`][griffe.Alias.inherited_members], |
| 1503 |
[`get_member`][griffe.Alias.get_member], |
| 1504 |
[`set_member`][griffe.Alias.set_member], |
| 1505 |
[`filter_members`][griffe.Alias.filter_members]. |
| 1506 |
""" |
| 1507 |
final_target = self.final_target |
| 1508 |
|
| 1509 |
|
| 1510 |
|
| 1511 |
|
| 1512 |
|
| 1513 |
return { |
| 1514 |
name: Alias(name, target=member, parent=self, inherited=False) |
| 1515 |
for name, member in final_target.members.items() |
| 1516 |
} |
| 1517 |
|
| 1518 |
@property |
| 1519 |
def inherited_members(self) -> dict[str, Alias]: |
| 1520 |
"""Members that are inherited from base classes. |
| 1521 |
|
| 1522 |
Each inherited member of the target will be wrapped in an alias, |
| 1523 |
to preserve correct object access paths. |
| 1524 |
|
| 1525 |
This method is part of the consumer API: |
| 1526 |
do not use when producing Griffe trees! |
| 1527 |
|
| 1528 |
See also: [`members`][griffe.Alias.members]. |
| 1529 |
""" |
| 1530 |
final_target = self.final_target |
| 1531 |
|
| 1532 |
|
| 1533 |
|
| 1534 |
|
| 1535 |
|
| 1536 |
return { |
| 1537 |
name: Alias(name, target=member, parent=self, inherited=True) |
| 1538 |
for name, member in final_target.inherited_members.items() |
| 1539 |
} |
| 1540 |
|
| 1541 |
def as_json(self, *, full: bool = False, **kwargs: Any) -> str: |
| 1542 |
"""Return this target's data as a JSON string. |
| 1543 |
|
| 1544 |
See also: [`as_dict`][griffe.Alias.as_dict]. |
| 1545 |
|
| 1546 |
Parameters: |
| 1547 |
full: Whether to return full info, or just base info. |
| 1548 |
**kwargs: Additional serialization options passed to encoder. |
| 1549 |
|
| 1550 |
Returns: |
| 1551 |
A JSON string. |
| 1552 |
""" |
| 1553 |
try: |
| 1554 |
return self.final_target.as_json(full=full, **kwargs) |
| 1555 |
except (AliasResolutionError, CyclicAliasError): |
| 1556 |
return super().as_json(full=full, **kwargs) |
| 1557 |
|
| 1558 |
|
| 1559 |
|
| 1560 |
|
| 1561 |
|
| 1562 |
|
| 1563 |
@property |
| 1564 |
def git_info(self) -> GitInfo | None: |
| 1565 |
"""Get the Git information for this object, if available.""" |
| 1566 |
return self.final_target.git_info |
| 1567 |
|
| 1568 |
@git_info.setter |
| 1569 |
def git_info(self, value: GitInfo | None) -> None: |
| 1570 |
"""Set the Git information for this object.""" |
| 1571 |
self.final_target.git_info = value |
| 1572 |
|
| 1573 |
@property |
| 1574 |
def source_link(self) -> str | None: |
| 1575 |
"""Get the source link for this object, if available.""" |
| 1576 |
return self.final_target.source_link |
| 1577 |
|
| 1578 |
@source_link.setter |
| 1579 |
def source_link(self, value: str | None) -> None: |
| 1580 |
"""Set the source link for this object.""" |
| 1581 |
self.final_target.source_link = value |
| 1582 |
|
| 1583 |
@property |
| 1584 |
def extra(self) -> dict: |
| 1585 |
"""Namespaced dictionaries storing extra metadata for this object, used by extensions.""" |
| 1586 |
return self.final_target.extra |
| 1587 |
|
| 1588 |
@property |
| 1589 |
def lineno(self) -> int | None: |
| 1590 |
"""The starting line number of the target object. |
| 1591 |
|
| 1592 |
See also: [`endlineno`][griffe.Alias.endlineno]. |
| 1593 |
""" |
| 1594 |
return self.final_target.lineno |
| 1595 |
|
| 1596 |
@lineno.setter |
| 1597 |
def lineno(self, lineno: int | None) -> None: |
| 1598 |
self.final_target.lineno = lineno |
| 1599 |
|
| 1600 |
@property |
| 1601 |
def endlineno(self) -> int | None: |
| 1602 |
"""The ending line number of the target object. |
| 1603 |
|
| 1604 |
See also: [`lineno`][griffe.Alias.lineno]. |
| 1605 |
""" |
| 1606 |
return self.final_target.endlineno |
| 1607 |
|
| 1608 |
@endlineno.setter |
| 1609 |
def endlineno(self, endlineno: int | None) -> None: |
| 1610 |
self.final_target.endlineno = endlineno |
| 1611 |
|
| 1612 |
@property |
| 1613 |
def docstring(self) -> Docstring | None: |
| 1614 |
"""The target docstring. |
| 1615 |
|
| 1616 |
See also: [`has_docstring`][griffe.Alias.has_docstring], |
| 1617 |
[`has_docstrings`][griffe.Alias.has_docstrings]. |
| 1618 |
""" |
| 1619 |
return self.final_target.docstring |
| 1620 |
|
| 1621 |
@docstring.setter |
| 1622 |
def docstring(self, docstring: Docstring | None) -> None: |
| 1623 |
self.final_target.docstring = docstring |
| 1624 |
|
| 1625 |
@property |
| 1626 |
def type_parameters(self) -> TypeParameters: |
| 1627 |
"""The target type parameters.""" |
| 1628 |
return self.final_target.type_parameters |
| 1629 |
|
| 1630 |
@type_parameters.setter |
| 1631 |
def type_parameters(self, type_parameters: TypeParameters) -> None: |
| 1632 |
self.final_target.type_parameters = type_parameters |
| 1633 |
|
| 1634 |
@property |
| 1635 |
def labels(self) -> set[str]: |
| 1636 |
"""The target labels (`property`, `dataclass`, etc.). |
| 1637 |
|
| 1638 |
See also: [`has_labels`][griffe.Alias.has_labels]. |
| 1639 |
""" |
| 1640 |
return self.final_target.labels |
| 1641 |
|
| 1642 |
@property |
| 1643 |
def imports(self) -> dict[str, str]: |
| 1644 |
"""The other objects imported by this alias' target. |
| 1645 |
|
| 1646 |
Keys are the names within the object (`from ... import ... as AS_NAME`), |
| 1647 |
while the values are the actual names of the objects (`from ... import REAL_NAME as ...`). |
| 1648 |
|
| 1649 |
See also: [`is_imported`][griffe.Alias.is_imported]. |
| 1650 |
""" |
| 1651 |
return self.final_target.imports |
| 1652 |
|
| 1653 |
@property |
| 1654 |
def exports(self) -> list[str | ExprName] | None: |
| 1655 |
"""The names of the objects exported by this (module) object through the `__all__` variable. |
| 1656 |
|
| 1657 |
Exports can contain string (object names) or resolvable names, |
| 1658 |
like other lists of exports coming from submodules: |
| 1659 |
|
| 1660 |
```python |
| 1661 |
from .submodule import __all__ as submodule_all |
| 1662 |
|
| 1663 |
__all__ = ["hello", *submodule_all] |
| 1664 |
``` |
| 1665 |
|
| 1666 |
Exports get expanded by the loader before it expands wildcards and resolves aliases. |
| 1667 |
|
| 1668 |
See also: [`GriffeLoader.expand_exports`][griffe.GriffeLoader.expand_exports]. |
| 1669 |
""" |
| 1670 |
return self.final_target.exports |
| 1671 |
|
| 1672 |
@property |
| 1673 |
def aliases(self) -> dict[str, Alias]: |
| 1674 |
"""The aliases pointing to this object.""" |
| 1675 |
return self.final_target.aliases |
| 1676 |
|
| 1677 |
def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool: |
| 1678 |
"""Tell if this object is of the given kind. |
| 1679 |
|
| 1680 |
See also: [`is_module`][griffe.Alias.is_module], |
| 1681 |
[`is_class`][griffe.Alias.is_class], |
| 1682 |
[`is_function`][griffe.Alias.is_function], |
| 1683 |
[`is_attribute`][griffe.Alias.is_attribute], |
| 1684 |
[`is_type_alias`][griffe.Alias.is_type_alias], |
| 1685 |
[`is_alias`][griffe.Alias.is_alias]. |
| 1686 |
|
| 1687 |
Parameters: |
| 1688 |
kind: An instance or set of kinds (strings or enumerations). |
| 1689 |
|
| 1690 |
Raises: |
| 1691 |
ValueError: When an empty set is given as argument. |
| 1692 |
|
| 1693 |
Returns: |
| 1694 |
True or False. |
| 1695 |
""" |
| 1696 |
return self.final_target.is_kind(kind) |
| 1697 |
|
| 1698 |
@property |
| 1699 |
def is_module(self) -> bool: |
| 1700 |
"""Whether this object is a module. |
| 1701 |
|
| 1702 |
See also: [`is_init_module`][griffe.Alias.is_init_module]. |
| 1703 |
[`is_class`][griffe.Alias.is_class], |
| 1704 |
[`is_function`][griffe.Alias.is_function], |
| 1705 |
[`is_attribute`][griffe.Alias.is_attribute], |
| 1706 |
[`is_type_alias`][griffe.Alias.is_type_alias], |
| 1707 |
[`is_alias`][griffe.Alias.is_alias], |
| 1708 |
[`is_kind`][griffe.Alias.is_kind]. |
| 1709 |
""" |
| 1710 |
return self.final_target.is_module |
| 1711 |
|
| 1712 |
@property |
| 1713 |
def is_class(self) -> bool: |
| 1714 |
"""Whether this object is a class. |
| 1715 |
|
| 1716 |
See also: [`is_module`][griffe.Alias.is_module], |
| 1717 |
[`is_function`][griffe.Alias.is_function], |
| 1718 |
[`is_attribute`][griffe.Alias.is_attribute], |
| 1719 |
[`is_type_alias`][griffe.Alias.is_type_alias], |
| 1720 |
[`is_alias`][griffe.Alias.is_alias], |
| 1721 |
[`is_kind`][griffe.Alias.is_kind]. |
| 1722 |
""" |
| 1723 |
return self.final_target.is_class |
| 1724 |
|
| 1725 |
@property |
| 1726 |
def is_function(self) -> bool: |
| 1727 |
"""Whether this object is a function. |
| 1728 |
|
| 1729 |
See also: [`is_module`][griffe.Alias.is_module], |
| 1730 |
[`is_class`][griffe.Alias.is_class], |
| 1731 |
[`is_attribute`][griffe.Alias.is_attribute], |
| 1732 |
[`is_type_alias`][griffe.Alias.is_type_alias], |
| 1733 |
[`is_alias`][griffe.Alias.is_alias], |
| 1734 |
[`is_kind`][griffe.Alias.is_kind]. |
| 1735 |
""" |
| 1736 |
return self.final_target.is_function |
| 1737 |
|
| 1738 |
@property |
| 1739 |
def is_attribute(self) -> bool: |
| 1740 |
"""Whether this object is an attribute. |
| 1741 |
|
| 1742 |
See also: [`is_module`][griffe.Alias.is_module], |
| 1743 |
[`is_class`][griffe.Alias.is_class], |
| 1744 |
[`is_function`][griffe.Alias.is_function], |
| 1745 |
[`is_type_alias`][griffe.Alias.is_type_alias], |
| 1746 |
[`is_alias`][griffe.Alias.is_alias], |
| 1747 |
[`is_kind`][griffe.Alias.is_kind]. |
| 1748 |
""" |
| 1749 |
return self.final_target.is_attribute |
| 1750 |
|
| 1751 |
@property |
| 1752 |
def is_type_alias(self) -> bool: |
| 1753 |
"""Whether this object is a type alias. |
| 1754 |
|
| 1755 |
See also: [`is_module`][griffe.Alias.is_module], |
| 1756 |
[`is_class`][griffe.Alias.is_class], |
| 1757 |
[`is_function`][griffe.Alias.is_function], |
| 1758 |
[`is_attribute`][griffe.Alias.is_attribute], |
| 1759 |
[`is_alias`][griffe.Alias.is_alias], |
| 1760 |
[`is_kind`][griffe.Alias.is_kind]. |
| 1761 |
""" |
| 1762 |
return self.final_target.is_type_alias |
| 1763 |
|
| 1764 |
def has_labels(self, *labels: str) -> bool: |
| 1765 |
"""Tell if this object has all the given labels. |
| 1766 |
|
| 1767 |
See also: [`labels`][griffe.Alias.labels]. |
| 1768 |
|
| 1769 |
Parameters: |
| 1770 |
*labels: Labels that must be present. |
| 1771 |
|
| 1772 |
Returns: |
| 1773 |
True or False. |
| 1774 |
""" |
| 1775 |
return self.final_target.has_labels(*labels) |
| 1776 |
|
| 1777 |
def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]: |
| 1778 |
"""Filter and return members based on predicates. |
| 1779 |
|
| 1780 |
See also: [`members`][griffe.Alias.members], |
| 1781 |
[`get_member`][griffe.Alias.get_member], |
| 1782 |
[`set_member`][griffe.Alias.set_member]. |
| 1783 |
|
| 1784 |
Parameters: |
| 1785 |
*predicates: A list of predicates, i.e. callables accepting a member as argument and returning a boolean. |
| 1786 |
|
| 1787 |
Returns: |
| 1788 |
A dictionary of members. |
| 1789 |
""" |
| 1790 |
return self.final_target.filter_members(*predicates) |
| 1791 |
|
| 1792 |
@property |
| 1793 |
def module(self) -> Module: |
| 1794 |
"""The parent module of this object. |
| 1795 |
|
| 1796 |
See also: [`package`][griffe.Alias.package]. |
| 1797 |
|
| 1798 |
Raises: |
| 1799 |
ValueError: When the object is not a module and does not have a parent. |
| 1800 |
""" |
| 1801 |
return self.final_target.module |
| 1802 |
|
| 1803 |
@property |
| 1804 |
def package(self) -> Module: |
| 1805 |
"""The absolute top module (the package) of this object. |
| 1806 |
|
| 1807 |
See also: [`module`][griffe.Alias.module]. |
| 1808 |
""" |
| 1809 |
return self.final_target.package |
| 1810 |
|
| 1811 |
@property |
| 1812 |
def filepath(self) -> Path | list[Path]: |
| 1813 |
"""The file path (or directory list for namespace packages) where this object was defined. |
| 1814 |
|
| 1815 |
See also: [`relative_filepath`][griffe.Alias.relative_filepath], |
| 1816 |
[`relative_package_filepath`][griffe.Alias.relative_package_filepath]. |
| 1817 |
""" |
| 1818 |
return self.final_target.filepath |
| 1819 |
|
| 1820 |
@property |
| 1821 |
def relative_filepath(self) -> Path: |
| 1822 |
"""The file path where this object was defined, relative to the current working directory. |
| 1823 |
|
| 1824 |
If this object's file path is not relative to the current working directory, return its absolute path. |
| 1825 |
|
| 1826 |
See also: [`filepath`][griffe.Alias.filepath], |
| 1827 |
[`relative_package_filepath`][griffe.Alias.relative_package_filepath]. |
| 1828 |
|
| 1829 |
Raises: |
| 1830 |
ValueError: When the relative path could not be computed. |
| 1831 |
""" |
| 1832 |
return self.final_target.relative_filepath |
| 1833 |
|
| 1834 |
@property |
| 1835 |
def relative_package_filepath(self) -> Path: |
| 1836 |
"""The file path where this object was defined, relative to the top module path. |
| 1837 |
|
| 1838 |
See also: [`filepath`][griffe.Alias.filepath], |
| 1839 |
[`relative_filepath`][griffe.Alias.relative_filepath]. |
| 1840 |
|
| 1841 |
Raises: |
| 1842 |
ValueError: When the relative path could not be computed. |
| 1843 |
""" |
| 1844 |
return self.final_target.relative_package_filepath |
| 1845 |
|
| 1846 |
@property |
| 1847 |
def canonical_path(self) -> str: |
| 1848 |
"""The full dotted path of this object. |
| 1849 |
|
| 1850 |
The canonical path is the path where the object was defined (not imported). |
| 1851 |
|
| 1852 |
See also: [`path`][griffe.Alias.path]. |
| 1853 |
""" |
| 1854 |
return self.final_target.canonical_path |
| 1855 |
|
| 1856 |
@property |
| 1857 |
def lines_collection(self) -> LinesCollection: |
| 1858 |
"""The lines collection attached to this object or its parents. |
| 1859 |
|
| 1860 |
See also: [`lines`][griffe.Alias.lines], |
| 1861 |
[`source`][griffe.Alias.source]. |
| 1862 |
|
| 1863 |
Raises: |
| 1864 |
ValueError: When no modules collection can be found in the object or its parents. |
| 1865 |
""" |
| 1866 |
return self.final_target.lines_collection |
| 1867 |
|
| 1868 |
@property |
| 1869 |
def lines(self) -> list[str]: |
| 1870 |
"""The lines containing the source of this object. |
| 1871 |
|
| 1872 |
See also: [`source`][griffe.Alias.source], |
| 1873 |
[`lines_collection`][griffe.Alias.lines_collection]. |
| 1874 |
""" |
| 1875 |
return self.final_target.lines |
| 1876 |
|
| 1877 |
@property |
| 1878 |
def source(self) -> str: |
| 1879 |
"""The source code of this object. |
| 1880 |
|
| 1881 |
See also: [`lines`][griffe.Alias.lines], |
| 1882 |
[`lines_collection`][griffe.Alias.lines_collection]. |
| 1883 |
""" |
| 1884 |
return self.final_target.source |
| 1885 |
|
| 1886 |
def resolve(self, name: str) -> str: |
| 1887 |
"""Resolve a name within this object's and parents' scope. |
| 1888 |
|
| 1889 |
Parameters: |
| 1890 |
name: The name to resolve. |
| 1891 |
|
| 1892 |
Raises: |
| 1893 |
NameResolutionError: When the name could not be resolved. |
| 1894 |
|
| 1895 |
Returns: |
| 1896 |
The resolved name. |
| 1897 |
""" |
| 1898 |
return self.final_target.resolve(name) |
| 1899 |
|
| 1900 |
|
| 1901 |
|
| 1902 |
|
| 1903 |
|
| 1904 |
|
| 1905 |
@property |
| 1906 |
def _filepath(self) -> Path | list[Path] | None: |
| 1907 |
return cast("Module", self.final_target)._filepath |
| 1908 |
|
| 1909 |
@property |
| 1910 |
def bases(self) -> list[Expr | str]: |
| 1911 |
"""The class bases. |
| 1912 |
|
| 1913 |
See also: [`Class`][griffe.Class], |
| 1914 |
[`resolved_bases`][griffe.Alias.resolved_bases], |
| 1915 |
[`mro`][griffe.Alias.mro]. |
| 1916 |
""" |
| 1917 |
return cast("Class", self.final_target).bases |
| 1918 |
|
| 1919 |
@property |
| 1920 |
def keywords(self) -> dict[str, Expr | str]: |
| 1921 |
"""The class keywords.""" |
| 1922 |
return cast("Class", self.final_target).keywords |
| 1923 |
|
| 1924 |
@property |
| 1925 |
def decorators(self) -> list[Decorator]: |
| 1926 |
"""The class/function decorators. |
| 1927 |
|
| 1928 |
See also: [`Function`][griffe.Function], |
| 1929 |
[`Class`][griffe.Class]. |
| 1930 |
""" |
| 1931 |
return cast("Class | Function", self.target).decorators |
| 1932 |
|
| 1933 |
@property |
| 1934 |
def imports_future_annotations(self) -> bool: |
| 1935 |
"""Whether this module import future annotations.""" |
| 1936 |
return cast("Module", self.final_target).imports_future_annotations |
| 1937 |
|
| 1938 |
@property |
| 1939 |
def is_init_method(self) -> bool: |
| 1940 |
"""Whether this method is an `__init__` method.""" |
| 1941 |
return cast("Function", self.final_target).is_init_method |
| 1942 |
|
| 1943 |
@property |
| 1944 |
def is_init_module(self) -> bool: |
| 1945 |
"""Whether this module is an `__init__.py` module. |
| 1946 |
|
| 1947 |
See also: [`is_module`][griffe.Alias.is_module]. |
| 1948 |
""" |
| 1949 |
return cast("Module", self.final_target).is_init_module |
| 1950 |
|
| 1951 |
@property |
| 1952 |
def is_package(self) -> bool: |
| 1953 |
"""Whether this module is a package (top module). |
| 1954 |
|
| 1955 |
See also: [`is_subpackage`][griffe.Alias.is_subpackage]. |
| 1956 |
""" |
| 1957 |
return cast("Module", self.final_target).is_package |
| 1958 |
|
| 1959 |
@property |
| 1960 |
def is_subpackage(self) -> bool: |
| 1961 |
"""Whether this module is a subpackage. |
| 1962 |
|
| 1963 |
See also: [`is_package`][griffe.Alias.is_package]. |
| 1964 |
""" |
| 1965 |
return cast("Module", self.final_target).is_subpackage |
| 1966 |
|
| 1967 |
@property |
| 1968 |
def is_namespace_package(self) -> bool: |
| 1969 |
"""Whether this module is a namespace package (top folder, no `__init__.py`). |
| 1970 |
|
| 1971 |
See also: [`is_namespace_subpackage`][griffe.Alias.is_namespace_subpackage]. |
| 1972 |
""" |
| 1973 |
return cast("Module", self.final_target).is_namespace_package |
| 1974 |
|
| 1975 |
@property |
| 1976 |
def is_namespace_subpackage(self) -> bool: |
| 1977 |
"""Whether this module is a namespace subpackage. |
| 1978 |
|
| 1979 |
See also: [`is_namespace_package`][griffe.Alias.is_namespace_package]. |
| 1980 |
""" |
| 1981 |
return cast("Module", self.final_target).is_namespace_subpackage |
| 1982 |
|
| 1983 |
@property |
| 1984 |
def overloads(self) -> dict[str, list[Function]] | list[Function] | None: |
| 1985 |
"""The overloaded signatures declared in this class/module or for this function.""" |
| 1986 |
return cast("Module | Class | Function", self.final_target).overloads |
| 1987 |
|
| 1988 |
@overloads.setter |
| 1989 |
def overloads(self, overloads: list[Function] | None) -> None: |
| 1990 |
cast("Module | Class | Function", self.final_target).overloads = overloads |
| 1991 |
|
| 1992 |
@property |
| 1993 |
def parameters(self) -> Parameters: |
| 1994 |
"""The parameters of the current function or `__init__` method for classes. |
| 1995 |
|
| 1996 |
This property can fetch inherited members, |
| 1997 |
and therefore is part of the consumer API: |
| 1998 |
do not use when producing Griffe trees! |
| 1999 |
""" |
| 2000 |
return cast("Class | Function", self.final_target).parameters |
| 2001 |
|
| 2002 |
@property |
| 2003 |
def returns(self) -> str | Expr | None: |
| 2004 |
"""The function return type annotation.""" |
| 2005 |
return cast("Function", self.final_target).returns |
| 2006 |
|
| 2007 |
@returns.setter |
| 2008 |
def returns(self, returns: str | Expr | None) -> None: |
| 2009 |
cast("Function", self.final_target).returns = returns |
| 2010 |
|
| 2011 |
@property |
| 2012 |
def setter(self) -> Function | None: |
| 2013 |
"""The setter linked to this function (property).""" |
| 2014 |
return cast("Attribute", self.final_target).setter |
| 2015 |
|
| 2016 |
@property |
| 2017 |
def deleter(self) -> Function | None: |
| 2018 |
"""The deleter linked to this function (property).""" |
| 2019 |
return cast("Attribute", self.final_target).deleter |
| 2020 |
|
| 2021 |
@property |
| 2022 |
def value(self) -> str | Expr | None: |
| 2023 |
"""The attribute or type alias value.""" |
| 2024 |
return cast("Attribute | TypeAlias", self.final_target).value |
| 2025 |
|
| 2026 |
@value.setter |
| 2027 |
def value(self, value: str | Expr | None) -> None: |
| 2028 |
cast("Attribute", self.final_target).value = value |
| 2029 |
|
| 2030 |
@property |
| 2031 |
def annotation(self) -> str | Expr | None: |
| 2032 |
"""The attribute type annotation.""" |
| 2033 |
return cast("Attribute", self.final_target).annotation |
| 2034 |
|
| 2035 |
@annotation.setter |
| 2036 |
def annotation(self, annotation: str | Expr | None) -> None: |
| 2037 |
cast("Attribute", self.final_target).annotation = annotation |
| 2038 |
|
| 2039 |
@property |
| 2040 |
def resolved_bases(self) -> list[Object]: |
| 2041 |
"""Resolved class bases. |
| 2042 |
|
| 2043 |
This method is part of the consumer API: |
| 2044 |
do not use when producing Griffe trees! |
| 2045 |
""" |
| 2046 |
return cast("Class", self.final_target).resolved_bases |
| 2047 |
|
| 2048 |
def mro(self) -> list[Class]: |
| 2049 |
"""Return a list of classes in order corresponding to Python's MRO.""" |
| 2050 |
return cast("Class", self.final_target).mro() |
| 2051 |
|
| 2052 |
def signature(self, *, return_type: bool = False, name: str | None = None) -> str: |
| 2053 |
"""Construct the class/function signature. |
| 2054 |
|
| 2055 |
Parameters: |
| 2056 |
return_type: Whether to include the return type in the signature. |
| 2057 |
name: The name of the class/function to use in the signature. |
| 2058 |
|
| 2059 |
Returns: |
| 2060 |
A string representation of the class/function signature. |
| 2061 |
""" |
| 2062 |
return cast("Class | Function", self.final_target).signature(return_type=return_type, name=name) |
| 2063 |
|
| 2064 |
|
| 2065 |
|
| 2066 |
|
| 2067 |
|
| 2068 |
@property |
| 2069 |
def target(self) -> Object | Alias: |
| 2070 |
"""The resolved target (actual object), if possible. |
| 2071 |
|
| 2072 |
Upon accessing this property, if the target is not already resolved, |
| 2073 |
a lookup is done using the modules collection to find the target. |
| 2074 |
|
| 2075 |
See also: [`final_target`][griffe.Alias.final_target], |
| 2076 |
[`resolve_target`][griffe.Alias.resolve_target], |
| 2077 |
[`resolved`][griffe.Alias.resolved]. |
| 2078 |
""" |
| 2079 |
if not self.resolved: |
| 2080 |
self.resolve_target() |
| 2081 |
return self._target |
| 2082 |
|
| 2083 |
@target.setter |
| 2084 |
def target(self, value: Object | Alias) -> None: |
| 2085 |
if value is self or value.path == self.path: |
| 2086 |
raise CyclicAliasError([self.target_path]) |
| 2087 |
self._target = value |
| 2088 |
self.target_path = value.path |
| 2089 |
if self.parent is not None: |
| 2090 |
self._target.aliases[self.path] = self |
| 2091 |
|
| 2092 |
@property |
| 2093 |
def final_target(self) -> Object: |
| 2094 |
"""The final, resolved target, if possible. |
| 2095 |
|
| 2096 |
This will iterate through the targets until a non-alias object is found. |
| 2097 |
|
| 2098 |
See also: [`target`][griffe.Alias.target], |
| 2099 |
[`resolve_target`][griffe.Alias.resolve_target], |
| 2100 |
[`resolved`][griffe.Alias.resolved]. |
| 2101 |
""" |
| 2102 |
|
| 2103 |
|
| 2104 |
|
| 2105 |
|
| 2106 |
|
| 2107 |
|
| 2108 |
|
| 2109 |
paths_seen: dict[str, None] = {} |
| 2110 |
target = self |
| 2111 |
while target.is_alias: |
| 2112 |
if target.path in paths_seen: |
| 2113 |
raise CyclicAliasError([*paths_seen, target.path]) |
| 2114 |
paths_seen[target.path] = None |
| 2115 |
target = target.target |
| 2116 |
return target |
| 2117 |
|
| 2118 |
def resolve_target(self) -> None: |
| 2119 |
"""Resolve the target. |
| 2120 |
|
| 2121 |
See also: [`target`][griffe.Alias.target], |
| 2122 |
[`final_target`][griffe.Alias.final_target], |
| 2123 |
[`resolved`][griffe.Alias.resolved]. |
| 2124 |
|
| 2125 |
Raises: |
| 2126 |
AliasResolutionError: When the target cannot be resolved. |
| 2127 |
It happens when the target does not exist, |
| 2128 |
or could not be loaded (unhandled dynamic object?), |
| 2129 |
or when the target is from a module that was not loaded |
| 2130 |
and added to the collection. |
| 2131 |
CyclicAliasError: When the resolved target is the alias itself. |
| 2132 |
""" |
| 2133 |
|
| 2134 |
|
| 2135 |
|
| 2136 |
|
| 2137 |
|
| 2138 |
|
| 2139 |
|
| 2140 |
|
| 2141 |
|
| 2142 |
|
| 2143 |
if self._passed_through: |
| 2144 |
raise CyclicAliasError([self.target_path]) |
| 2145 |
self._passed_through = True |
| 2146 |
try: |
| 2147 |
self._resolve_target() |
| 2148 |
finally: |
| 2149 |
self._passed_through = False |
| 2150 |
|
| 2151 |
def _resolve_target(self) -> None: |
| 2152 |
try: |
| 2153 |
resolved = self.modules_collection.get_member(self.target_path) |
| 2154 |
except KeyError as error: |
| 2155 |
raise AliasResolutionError(self) from error |
| 2156 |
if resolved is self: |
| 2157 |
raise CyclicAliasError([self.target_path]) |
| 2158 |
if resolved.is_alias and not resolved.resolved: |
| 2159 |
try: |
| 2160 |
resolved.resolve_target() |
| 2161 |
except CyclicAliasError as error: |
| 2162 |
raise CyclicAliasError([self.target_path, *error.chain]) from error |
| 2163 |
self._target = resolved |
| 2164 |
if self.parent is not None: |
| 2165 |
self._target.aliases[self.path] = self |
| 2166 |
|
| 2167 |
def _update_target_aliases(self) -> None: |
| 2168 |
with suppress(AttributeError, AliasResolutionError, CyclicAliasError): |
| 2169 |
self._target.aliases[self.path] = self |
| 2170 |
|
| 2171 |
@property |
| 2172 |
def resolved(self) -> bool: |
| 2173 |
"""Whether this alias' target is resolved.""" |
| 2174 |
return self._target is not None |
| 2175 |
|
| 2176 |
@property |
| 2177 |
def wildcard(self) -> str | None: |
| 2178 |
"""The module on which the wildcard import is performed (if any). |
| 2179 |
|
| 2180 |
See also: [`GriffeLoader.expand_wildcards`][griffe.GriffeLoader.expand_wildcards]. |
| 2181 |
""" |
| 2182 |
if self.name.endswith("/*"): |
| 2183 |
return self.target_path |
| 2184 |
return None |
| 2185 |
|
| 2186 |
def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]: |
| 2187 |
"""Return this alias' data as a dictionary. |
| 2188 |
|
| 2189 |
See also: [`as_json`][griffe.Alias.as_json]. |
| 2190 |
|
| 2191 |
Parameters: |
| 2192 |
full: Whether to return full info, or just base info. |
| 2193 |
**kwargs: Additional serialization options. |
| 2194 |
|
| 2195 |
Returns: |
| 2196 |
A dictionary. |
| 2197 |
""" |
| 2198 |
base: dict[str, Any] = { |
| 2199 |
"kind": Kind.ALIAS, |
| 2200 |
"name": self.name, |
| 2201 |
"target_path": self.target_path, |
| 2202 |
"runtime": self.runtime, |
| 2203 |
"inherited": self.inherited, |
| 2204 |
} |
| 2205 |
|
| 2206 |
if self.public is not None: |
| 2207 |
base["public"] = self.public |
| 2208 |
if self.deprecated is not None: |
| 2209 |
base["deprecated"] = self.deprecated |
| 2210 |
if self.alias_lineno: |
| 2211 |
base["lineno"] = self.alias_lineno |
| 2212 |
if self.alias_endlineno: |
| 2213 |
base["endlineno"] = self.alias_endlineno |
| 2214 |
if self.analysis: |
| 2215 |
base["analysis"] = self.analysis |
| 2216 |
|
| 2217 |
if full: |
| 2218 |
base.update( |
| 2219 |
{ |
| 2220 |
"path": self.path, |
| 2221 |
"is_public": self.is_public, |
| 2222 |
"is_deprecated": self.is_deprecated, |
| 2223 |
"is_private": self.is_private, |
| 2224 |
"is_class_private": self.is_class_private, |
| 2225 |
"is_special": self.is_special, |
| 2226 |
"is_imported": self.is_imported, |
| 2227 |
"is_exported": self.is_exported, |
| 2228 |
"is_wildcard_exposed": self.is_wildcard_exposed, |
| 2229 |
}, |
| 2230 |
) |
| 2231 |
|
| 2232 |
return base |
| 2233 |
|
| 2234 |
|
| 2235 |
class Module(Object): |
| 2236 |
"""The class representing a Python module.""" |
| 2237 |
|
| 2238 |
kind = Kind.MODULE |
| 2239 |
|
| 2240 |
def __init__(self, *args: Any, filepath: Path | list[Path] | None = None, **kwargs: Any) -> None: |
| 2241 |
"""Initialize the module. |
| 2242 |
|
| 2243 |
Parameters: |
| 2244 |
*args: See [`griffe.Object`][]. |
| 2245 |
filepath: The module file path (directory for namespace [sub]packages, none for builtin modules). |
| 2246 |
**kwargs: See [`griffe.Object`][]. |
| 2247 |
""" |
| 2248 |
super().__init__(*args, **kwargs) |
| 2249 |
self._filepath: Path | list[Path] | None = filepath |
| 2250 |
self.overloads: dict[str, list[Function]] = defaultdict(list) |
| 2251 |
"""The overloaded signatures declared in this module.""" |
| 2252 |
|
| 2253 |
def __repr__(self) -> str: |
| 2254 |
try: |
| 2255 |
return f"Module({self.filepath!r})" |
| 2256 |
except BuiltinModuleError: |
| 2257 |
return f"Module({self.name!r})" |
| 2258 |
|
| 2259 |
@property |
| 2260 |
def filepath(self) -> Path | list[Path]: |
| 2261 |
"""The file path of this module. |
| 2262 |
|
| 2263 |
Raises: |
| 2264 |
BuiltinModuleError: When the instance filepath is None. |
| 2265 |
""" |
| 2266 |
if self._filepath is None: |
| 2267 |
raise BuiltinModuleError(self.name) |
| 2268 |
return self._filepath |
| 2269 |
|
| 2270 |
@property |
| 2271 |
def imports_future_annotations(self) -> bool: |
| 2272 |
"""Whether this module import future annotations.""" |
| 2273 |
return ( |
| 2274 |
"annotations" in self.members |
| 2275 |
and self.members["annotations"].is_alias |
| 2276 |
and self.members["annotations"].target_path == "__future__.annotations" |
| 2277 |
) |
| 2278 |
|
| 2279 |
@property |
| 2280 |
def is_init_module(self) -> bool: |
| 2281 |
"""Whether this module is an `__init__.py` module. |
| 2282 |
|
| 2283 |
See also: [`is_module`][griffe.Module.is_module]. |
| 2284 |
""" |
| 2285 |
if isinstance(self.filepath, list): |
| 2286 |
return False |
| 2287 |
try: |
| 2288 |
return self.filepath.name.split(".", 1)[0] == "__init__" |
| 2289 |
except BuiltinModuleError: |
| 2290 |
return False |
| 2291 |
|
| 2292 |
@property |
| 2293 |
def is_package(self) -> bool: |
| 2294 |
"""Whether this module is a package (top module). |
| 2295 |
|
| 2296 |
See also: [`is_subpackage`][griffe.Module.is_subpackage]. |
| 2297 |
""" |
| 2298 |
return not bool(self.parent) and self.is_init_module |
| 2299 |
|
| 2300 |
@property |
| 2301 |
def is_subpackage(self) -> bool: |
| 2302 |
"""Whether this module is a subpackage. |
| 2303 |
|
| 2304 |
See also: [`is_package`][griffe.Module.is_package]. |
| 2305 |
""" |
| 2306 |
return bool(self.parent) and self.is_init_module |
| 2307 |
|
| 2308 |
@property |
| 2309 |
def is_namespace_package(self) -> bool: |
| 2310 |
"""Whether this module is a namespace package (top folder, no `__init__.py`). |
| 2311 |
|
| 2312 |
See also: [`is_namespace_subpackage`][griffe.Module.is_namespace_subpackage]. |
| 2313 |
""" |
| 2314 |
try: |
| 2315 |
return self.parent is None and isinstance(self.filepath, list) |
| 2316 |
except BuiltinModuleError: |
| 2317 |
return False |
| 2318 |
|
| 2319 |
@property |
| 2320 |
def is_namespace_subpackage(self) -> bool: |
| 2321 |
"""Whether this module is a namespace subpackage. |
| 2322 |
|
| 2323 |
See also: [`is_namespace_package`][griffe.Module.is_namespace_package]. |
| 2324 |
""" |
| 2325 |
try: |
| 2326 |
return ( |
| 2327 |
self.parent is not None |
| 2328 |
and isinstance(self.filepath, list) |
| 2329 |
and ( |
| 2330 |
cast("Module", self.parent).is_namespace_package |
| 2331 |
or cast("Module", self.parent).is_namespace_subpackage |
| 2332 |
) |
| 2333 |
) |
| 2334 |
except BuiltinModuleError: |
| 2335 |
return False |
| 2336 |
|
| 2337 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 2338 |
"""Return this module's data as a dictionary. |
| 2339 |
|
| 2340 |
See also: [`as_json`][griffe.Module.as_json]. |
| 2341 |
|
| 2342 |
Parameters: |
| 2343 |
**kwargs: Additional serialization options. |
| 2344 |
|
| 2345 |
Returns: |
| 2346 |
A dictionary. |
| 2347 |
""" |
| 2348 |
base = super().as_dict(**kwargs) |
| 2349 |
if isinstance(self._filepath, list): |
| 2350 |
base["filepath"] = [str(path) for path in self._filepath] |
| 2351 |
elif self._filepath: |
| 2352 |
base["filepath"] = str(self._filepath) |
| 2353 |
else: |
| 2354 |
base["filepath"] = None |
| 2355 |
return base |
| 2356 |
|
| 2357 |
|
| 2358 |
class Class(Object): |
| 2359 |
"""The class representing a Python class.""" |
| 2360 |
|
| 2361 |
kind = Kind.CLASS |
| 2362 |
|
| 2363 |
def __init__( |
| 2364 |
self, |
| 2365 |
*args: Any, |
| 2366 |
bases: Sequence[Expr | str] | None = None, |
| 2367 |
decorators: list[Decorator] | None = None, |
| 2368 |
keywords: dict[str, Any] | None = None, |
| 2369 |
**kwargs: Any, |
| 2370 |
) -> None: |
| 2371 |
"""Initialize the class. |
| 2372 |
|
| 2373 |
Parameters: |
| 2374 |
*args: See [`griffe.Object`][]. |
| 2375 |
bases: The list of base classes, if any. |
| 2376 |
decorators: The class decorators, if any. |
| 2377 |
keywords: The class keywords arguments, if any. |
| 2378 |
**kwargs: See [`griffe.Object`][]. |
| 2379 |
""" |
| 2380 |
super().__init__(*args, **kwargs) |
| 2381 |
|
| 2382 |
self.bases: list[Expr | str] = list(bases) if bases else [] |
| 2383 |
"""The class bases. |
| 2384 |
|
| 2385 |
See also: [`resolved_bases`][griffe.Class.resolved_bases], |
| 2386 |
[`mro`][griffe.Class.mro]. |
| 2387 |
""" |
| 2388 |
|
| 2389 |
self.decorators: list[Decorator] = decorators or [] |
| 2390 |
"""The class decorators.""" |
| 2391 |
|
| 2392 |
self.keywords: dict[str, Any] = keywords or {} |
| 2393 |
"""The class keywords arguments.""" |
| 2394 |
|
| 2395 |
self.overloads: dict[str, list[Function]] = defaultdict(list) |
| 2396 |
"""The overloaded signatures declared in this class.""" |
| 2397 |
|
| 2398 |
@property |
| 2399 |
def parameters(self) -> Parameters: |
| 2400 |
"""The parameters of this class' `__init__` method, if any. |
| 2401 |
|
| 2402 |
This property fetches inherited members, |
| 2403 |
and therefore is part of the consumer API: |
| 2404 |
do not use when producing Griffe trees! |
| 2405 |
""" |
| 2406 |
try: |
| 2407 |
return self.all_members["__init__"].parameters |
| 2408 |
except KeyError: |
| 2409 |
return Parameters() |
| 2410 |
|
| 2411 |
def signature(self, *, return_type: bool = False, name: str | None = None) -> str: |
| 2412 |
"""Construct the class signature. |
| 2413 |
|
| 2414 |
Parameters: |
| 2415 |
return_type: Whether to include the return type in the signature. |
| 2416 |
name: The name of the class to use in the signature. |
| 2417 |
|
| 2418 |
Returns: |
| 2419 |
A string representation of the class signature. |
| 2420 |
""" |
| 2421 |
all_members = self.all_members |
| 2422 |
if "__init__" in all_members: |
| 2423 |
init = all_members["__init__"] |
| 2424 |
if isinstance(init, Function): |
| 2425 |
return init.signature(return_type=return_type, name=name or self.name) |
| 2426 |
return "" |
| 2427 |
|
| 2428 |
@property |
| 2429 |
def resolved_bases(self) -> list[Object]: |
| 2430 |
"""Resolved class bases. |
| 2431 |
|
| 2432 |
This method is part of the consumer API: |
| 2433 |
do not use when producing Griffe trees! |
| 2434 |
|
| 2435 |
See also: [`bases`][griffe.Class.bases], |
| 2436 |
[`mro`][griffe.Class.mro]. |
| 2437 |
""" |
| 2438 |
resolved_bases = [] |
| 2439 |
for base in self.bases: |
| 2440 |
base_path = base if isinstance(base, str) else base.canonical_path |
| 2441 |
try: |
| 2442 |
resolved_base = self.modules_collection.get_member(base_path) |
| 2443 |
if resolved_base.is_alias: |
| 2444 |
resolved_base = resolved_base.final_target |
| 2445 |
except (AliasResolutionError, CyclicAliasError, KeyError): |
| 2446 |
logger.debug("Base class %s is not loaded, or not static, it cannot be resolved", base_path) |
| 2447 |
else: |
| 2448 |
resolved_bases.append(resolved_base) |
| 2449 |
return resolved_bases |
| 2450 |
|
| 2451 |
def _mro(self, seen: tuple[str, ...] = ()) -> list[Class]: |
| 2452 |
seen = (*seen, self.path) |
| 2453 |
bases: list[Class] = [base for base in self.resolved_bases if base.is_class] |
| 2454 |
if not bases: |
| 2455 |
return [self] |
| 2456 |
for base in bases: |
| 2457 |
if base.path in seen: |
| 2458 |
cycle = " -> ".join(seen) + f" -> {base.path}" |
| 2459 |
raise ValueError(f"Cannot compute C3 linearization, inheritance cycle detected: {cycle}") |
| 2460 |
return [self, *c3linear_merge(*[base._mro(seen) for base in bases], bases)] |
| 2461 |
|
| 2462 |
def mro(self) -> list[Class]: |
| 2463 |
"""Return a list of classes in order corresponding to Python's MRO. |
| 2464 |
|
| 2465 |
See also: [`bases`][griffe.Class.bases], |
| 2466 |
[`resolved_bases`][griffe.Class.resolved_bases]. |
| 2467 |
""" |
| 2468 |
return self._mro()[1:] |
| 2469 |
|
| 2470 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 2471 |
"""Return this class' data as a dictionary. |
| 2472 |
|
| 2473 |
See also: [`as_json`][griffe.Class.as_json]. |
| 2474 |
|
| 2475 |
Parameters: |
| 2476 |
**kwargs: Additional serialization options. |
| 2477 |
|
| 2478 |
Returns: |
| 2479 |
A dictionary. |
| 2480 |
""" |
| 2481 |
base = super().as_dict(**kwargs) |
| 2482 |
base["bases"] = self.bases |
| 2483 |
base["decorators"] = [dec.as_dict(**kwargs) for dec in self.decorators] |
| 2484 |
return base |
| 2485 |
|
| 2486 |
|
| 2487 |
class Function(Object): |
| 2488 |
"""The class representing a Python function.""" |
| 2489 |
|
| 2490 |
kind = Kind.FUNCTION |
| 2491 |
|
| 2492 |
def __init__( |
| 2493 |
self, |
| 2494 |
*args: Any, |
| 2495 |
parameters: Parameters | None = None, |
| 2496 |
returns: str | Expr | None = None, |
| 2497 |
decorators: list[Decorator] | None = None, |
| 2498 |
**kwargs: Any, |
| 2499 |
) -> None: |
| 2500 |
"""Initialize the function. |
| 2501 |
|
| 2502 |
Parameters: |
| 2503 |
*args: See [`griffe.Object`][]. |
| 2504 |
parameters: The function parameters. |
| 2505 |
returns: The function return annotation. |
| 2506 |
decorators: The function decorators, if any. |
| 2507 |
**kwargs: See [`griffe.Object`][]. |
| 2508 |
""" |
| 2509 |
super().__init__(*args, **kwargs) |
| 2510 |
self.parameters: Parameters = parameters or Parameters() |
| 2511 |
"""The function parameters.""" |
| 2512 |
self.returns: str | Expr | None = returns |
| 2513 |
"""The function return type annotation.""" |
| 2514 |
self.decorators: list[Decorator] = decorators or [] |
| 2515 |
"""The function decorators.""" |
| 2516 |
self.overloads: list[Function] | None = None |
| 2517 |
"""The overloaded signatures of this function.""" |
| 2518 |
|
| 2519 |
for parameter in self.parameters: |
| 2520 |
parameter.function = self |
| 2521 |
|
| 2522 |
@property |
| 2523 |
def annotation(self) -> str | Expr | None: |
| 2524 |
"""The type annotation of the returned value.""" |
| 2525 |
return self.returns |
| 2526 |
|
| 2527 |
def resolve(self, name: str) -> str: |
| 2528 |
"""Resolve a name within this object's and parents' scope. |
| 2529 |
|
| 2530 |
Parameters: |
| 2531 |
name: The name to resolve. |
| 2532 |
|
| 2533 |
Raises: |
| 2534 |
NameResolutionError: When the name could not be resolved. |
| 2535 |
|
| 2536 |
Returns: |
| 2537 |
The resolved name. |
| 2538 |
""" |
| 2539 |
|
| 2540 |
if self.parent and self.name == "__init__": |
| 2541 |
|
| 2542 |
if name in self.parameters: |
| 2543 |
return f"{self.parent.path}({name})" |
| 2544 |
|
| 2545 |
|
| 2546 |
|
| 2547 |
resolved = super().resolve(name) |
| 2548 |
try: |
| 2549 |
obj = self.modules_collection.get_member(resolved) |
| 2550 |
except KeyError: |
| 2551 |
return resolved |
| 2552 |
try: |
| 2553 |
if obj.is_attribute and "instance-attribute" in obj.labels: |
| 2554 |
raise NameResolutionError(name) |
| 2555 |
except AliasResolutionError: |
| 2556 |
pass |
| 2557 |
return resolved |
| 2558 |
return super().resolve(name) |
| 2559 |
|
| 2560 |
@property |
| 2561 |
def is_init_method(self) -> bool: |
| 2562 |
"""Whether this function is an `__init__` method.""" |
| 2563 |
return bool(self.parent and self.parent.is_class and self.name == "__init__") |
| 2564 |
|
| 2565 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 2566 |
"""Return this function's data as a dictionary. |
| 2567 |
|
| 2568 |
See also: [`as_json`][griffe.Function.as_json]. |
| 2569 |
|
| 2570 |
Parameters: |
| 2571 |
**kwargs: Additional serialization options. |
| 2572 |
|
| 2573 |
Returns: |
| 2574 |
A dictionary. |
| 2575 |
""" |
| 2576 |
base = super().as_dict(**kwargs) |
| 2577 |
base["decorators"] = [dec.as_dict(**kwargs) for dec in self.decorators] |
| 2578 |
base["parameters"] = [param.as_dict(**kwargs) for param in self.parameters] |
| 2579 |
base["returns"] = self.returns |
| 2580 |
return base |
| 2581 |
|
| 2582 |
def signature(self, *, return_type: bool = True, name: str | None = None) -> str: |
| 2583 |
"""Construct the function signature. |
| 2584 |
|
| 2585 |
Parameters: |
| 2586 |
return_type: Whether to include the return type in the signature. |
| 2587 |
name: The name of the function to use in the signature. |
| 2588 |
|
| 2589 |
Returns: |
| 2590 |
A string representation of the function signature. |
| 2591 |
""" |
| 2592 |
signature = f"{name or self.name}(" |
| 2593 |
|
| 2594 |
has_pos_only = any(p.kind == ParameterKind.positional_only for p in self.parameters) |
| 2595 |
render_pos_only_separator = True |
| 2596 |
render_kw_only_separator = True |
| 2597 |
|
| 2598 |
param_strs = [] |
| 2599 |
|
| 2600 |
for index, param in enumerate(self.parameters): |
| 2601 |
|
| 2602 |
if index == 0 and param.name in ("self", "cls") and self.parent and self.parent.is_class: |
| 2603 |
continue |
| 2604 |
|
| 2605 |
param_str = "" |
| 2606 |
|
| 2607 |
|
| 2608 |
if param.kind != ParameterKind.positional_only: |
| 2609 |
if has_pos_only and render_pos_only_separator: |
| 2610 |
render_pos_only_separator = False |
| 2611 |
param_strs.append("/") |
| 2612 |
|
| 2613 |
if param.kind == ParameterKind.keyword_only and render_kw_only_separator: |
| 2614 |
render_kw_only_separator = False |
| 2615 |
param_strs.append("*") |
| 2616 |
|
| 2617 |
|
| 2618 |
if param.kind == ParameterKind.var_positional: |
| 2619 |
param_str = "*" |
| 2620 |
render_kw_only_separator = False |
| 2621 |
elif param.kind == ParameterKind.var_keyword: |
| 2622 |
param_str = "**" |
| 2623 |
|
| 2624 |
|
| 2625 |
param_str += param.name |
| 2626 |
|
| 2627 |
|
| 2628 |
if param.annotation is not None: |
| 2629 |
param_str += f": {param.annotation}" |
| 2630 |
equal = " = " |
| 2631 |
else: |
| 2632 |
equal = "=" |
| 2633 |
|
| 2634 |
|
| 2635 |
if param.default is not None and param.kind not in { |
| 2636 |
ParameterKind.var_positional, |
| 2637 |
ParameterKind.var_keyword, |
| 2638 |
}: |
| 2639 |
param_str += f"{equal}{param.default}" |
| 2640 |
|
| 2641 |
param_strs.append(param_str) |
| 2642 |
|
| 2643 |
|
| 2644 |
if has_pos_only and render_pos_only_separator: |
| 2645 |
param_strs.append("/") |
| 2646 |
|
| 2647 |
signature += ", ".join(param_strs) |
| 2648 |
signature += ")" |
| 2649 |
|
| 2650 |
|
| 2651 |
if return_type and self.annotation: |
| 2652 |
signature += f" -> {self.annotation}" |
| 2653 |
|
| 2654 |
return signature |
| 2655 |
|
| 2656 |
|
| 2657 |
class Attribute(Object): |
| 2658 |
"""The class representing a Python module/class/instance attribute.""" |
| 2659 |
|
| 2660 |
kind = Kind.ATTRIBUTE |
| 2661 |
|
| 2662 |
def __init__( |
| 2663 |
self, |
| 2664 |
*args: Any, |
| 2665 |
value: str | Expr | None = None, |
| 2666 |
annotation: str | Expr | None = None, |
| 2667 |
**kwargs: Any, |
| 2668 |
) -> None: |
| 2669 |
"""Initialize the function. |
| 2670 |
|
| 2671 |
Parameters: |
| 2672 |
*args: See [`griffe.Object`][]. |
| 2673 |
value: The attribute value, if any. |
| 2674 |
annotation: The attribute annotation, if any. |
| 2675 |
**kwargs: See [`griffe.Object`][]. |
| 2676 |
""" |
| 2677 |
super().__init__(*args, **kwargs) |
| 2678 |
self.value: str | Expr | None = value |
| 2679 |
"""The attribute value.""" |
| 2680 |
self.annotation: str | Expr | None = annotation |
| 2681 |
"""The attribute type annotation.""" |
| 2682 |
self.setter: Function | None = None |
| 2683 |
"""The setter linked to this property.""" |
| 2684 |
self.deleter: Function | None = None |
| 2685 |
"""The deleter linked to this property.""" |
| 2686 |
|
| 2687 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 2688 |
"""Return this attribute's data as a dictionary. |
| 2689 |
|
| 2690 |
See also: [`as_json`][griffe.Attribute.as_json]. |
| 2691 |
|
| 2692 |
Parameters: |
| 2693 |
**kwargs: Additional serialization options. |
| 2694 |
|
| 2695 |
Returns: |
| 2696 |
A dictionary. |
| 2697 |
""" |
| 2698 |
base = super().as_dict(**kwargs) |
| 2699 |
if self.value is not None: |
| 2700 |
base["value"] = self.value |
| 2701 |
if self.annotation is not None: |
| 2702 |
base["annotation"] = self.annotation |
| 2703 |
return base |
| 2704 |
|
| 2705 |
|
| 2706 |
class TypeAlias(Object): |
| 2707 |
"""The class representing a Python type alias.""" |
| 2708 |
|
| 2709 |
kind = Kind.TYPE_ALIAS |
| 2710 |
|
| 2711 |
def __init__( |
| 2712 |
self, |
| 2713 |
*args: Any, |
| 2714 |
value: str | Expr | None = None, |
| 2715 |
**kwargs: Any, |
| 2716 |
) -> None: |
| 2717 |
"""Initialize the function. |
| 2718 |
|
| 2719 |
Parameters: |
| 2720 |
*args: See [`griffe.Object`][]. |
| 2721 |
value: The type alias value. |
| 2722 |
**kwargs: See [`griffe.Object`][]. |
| 2723 |
""" |
| 2724 |
super().__init__(*args, **kwargs) |
| 2725 |
self.value: str | Expr | None = value |
| 2726 |
"""The type alias value.""" |
| 2727 |
|
| 2728 |
def as_dict(self, **kwargs: Any) -> dict[str, Any]: |
| 2729 |
"""Return this type alias's data as a dictionary. |
| 2730 |
|
| 2731 |
Parameters: |
| 2732 |
**kwargs: Additional serialization options. |
| 2733 |
|
| 2734 |
Returns: |
| 2735 |
A dictionary. |
| 2736 |
""" |
| 2737 |
base = super().as_dict(**kwargs) |
| 2738 |
base["value"] = self.value |
| 2739 |
return base |