Skip to content

Alias ¤

Alias(
    name: str,
    target: str | Object | Alias,
    *,
    lineno: int | None = None,
    endlineno: int | None = None,
    runtime: bool = True,
    parent: Module | Class | Alias | None = None,
    inherited: bool = False,
    wildcard_imported: bool = False,
    analysis: Literal["static", "dynamic"] | None = None,
)

Bases: ObjectAliasMixin


              flowchart TD
              griffe.Alias[Alias]
              griffe._internal.mixins.ObjectAliasMixin[ObjectAliasMixin]
              griffe._internal.mixins.GetMembersMixin[GetMembersMixin]
              griffe._internal.mixins.SetMembersMixin[SetMembersMixin]
              griffe._internal.mixins.DelMembersMixin[DelMembersMixin]
              griffe._internal.mixins.SerializationMixin[SerializationMixin]

                              griffe._internal.mixins.ObjectAliasMixin --> griffe.Alias
                                griffe._internal.mixins.GetMembersMixin --> griffe._internal.mixins.ObjectAliasMixin
                
                griffe._internal.mixins.SetMembersMixin --> griffe._internal.mixins.ObjectAliasMixin
                
                griffe._internal.mixins.DelMembersMixin --> griffe._internal.mixins.ObjectAliasMixin
                
                griffe._internal.mixins.SerializationMixin --> griffe._internal.mixins.ObjectAliasMixin
                



              click griffe.Alias href "" "griffe.Alias"
              click griffe._internal.mixins.ObjectAliasMixin href "" "griffe._internal.mixins.ObjectAliasMixin"
              click griffe._internal.mixins.GetMembersMixin href "" "griffe._internal.mixins.GetMembersMixin"
              click griffe._internal.mixins.SetMembersMixin href "" "griffe._internal.mixins.SetMembersMixin"
              click griffe._internal.mixins.DelMembersMixin href "" "griffe._internal.mixins.DelMembersMixin"
              click griffe._internal.mixins.SerializationMixin href "" "griffe._internal.mixins.SerializationMixin"
            

This class represents an alias, or indirection, to an object declared in another module.

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

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

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

Parameters:

  • name ¤

    (str) –

    The alias name.

  • target ¤

    (str | Object | Alias) –

    If it's a string, the target resolution is delayed until accessing the target property. If it's an object, or even another alias, the target is immediately set.

  • lineno ¤

    (int | None, default: None ) –

    The alias starting line number.

  • endlineno ¤

    (int | None, default: None ) –

    The alias ending line number.

  • runtime ¤

    (bool, default: True ) –

    Whether this alias is present at runtime or not.

  • parent ¤

    (Module | Class | Alias | None, default: None ) –

    The alias parent.

  • inherited ¤

    (bool, default: False ) –

    Whether this alias wraps an inherited member.

  • wildcard_imported ¤

    (bool, default: False ) –

    Whether this alias was created using a wildcard import.

  • analysis ¤

    (Literal['static', 'dynamic'] | None, default: None ) –

    The type of analysis used to load this alias. None means the alias was created manually.

Methods:

  • __bool__

    An alias is always true-ish.

  • __delitem__

    Delete a member with its name or path.

  • __getitem__

    Get a member with its name or path.

  • __len__

    The length of an alias is always 1.

  • __setitem__

    Set a member with its name or path.

  • as_dict

    Return this alias' data as a dictionary.

  • as_json

    Return this target's data as a JSON string.

  • del_member

    Delete a member with its name or path.

  • filter_members

    Filter and return members based on predicates.

  • from_json

    Create an instance of this class from a JSON string.

  • get_member

    Get a member with its name or path.

  • has_labels

    Tell if this object has all the given labels.

  • is_kind

    Tell if this object is of the given kind.

  • mro

    Return a list of classes in order corresponding to Python's MRO.

  • resolve

    Resolve a name within this object's and parents' scope.

  • resolve_target

    Resolve the target.

  • set_member

    Set a member with its name or path.

  • signature

    Construct the class/function signature.

Attributes:

Source code in packages/griffelib/src/griffe/_internal/models.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
def __init__(
    self,
    name: str,
    target: str | Object | Alias,
    *,
    lineno: int | None = None,
    endlineno: int | None = None,
    runtime: bool = True,
    parent: Module | Class | Alias | None = None,
    inherited: bool = False,
    wildcard_imported: bool = False,
    analysis: Literal["static", "dynamic"] | None = None,
) -> None:
    """Initialize the alias.

    Parameters:
        name: The alias name.
        target: If it's a string, the target resolution is delayed until accessing the target property.
            If it's an object, or even another alias, the target is immediately set.
        lineno: The alias starting line number.
        endlineno: The alias ending line number.
        runtime: Whether this alias is present at runtime or not.
        parent: The alias parent.
        inherited: Whether this alias wraps an inherited member.
        wildcard_imported: Whether this alias was created using a wildcard import.
        analysis: The type of analysis used to load this alias.
            None means the alias was created manually.
    """
    self.name: str = name
    """The alias name."""

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

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

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

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

    self.wildcard_imported: bool = wildcard_imported
    """Whether this alias was created using a wildcard import."""

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

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

    self.analysis: Literal["static", "dynamic"] | None = analysis
    """The type of analysis used to load this alias.

    None means the alias was created manually.
    """

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

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

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

alias_endlineno instance-attribute ¤

alias_endlineno: int | None = endlineno

The ending line number of the alias.

alias_lineno instance-attribute ¤

alias_lineno: int | None = lineno

The starting line number of the alias.

aliases property ¤

aliases: dict[str, Alias]

The aliases pointing to this object.

all_members property ¤

all_members: dict[str, Object | Alias]

All members (declared and inherited).

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

analysis instance-attribute ¤

analysis: Literal['static', 'dynamic'] | None = analysis

The type of analysis used to load this alias.

None means the alias was created manually.

annotation property writable ¤

annotation: str | Expr | None

The attribute type annotation.

attributes property ¤

attributes: dict[str, Attribute]

The attribute members.

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

bases property ¤

bases: list[Expr | str]

The class bases.

See also: Class, resolved_bases, mro.

canonical_path property ¤

canonical_path: str

The full dotted path of this object.

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

See also: path.

classes property ¤

classes: dict[str, Class]

The class members.

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

decorators property ¤

decorators: list[Decorator]

The class/function decorators.

See also: Function, Class.

deleter property ¤

deleter: Function | None

The deleter linked to this function (property).

deprecated instance-attribute ¤

deprecated: str | bool | None = None

Whether this alias is deprecated (boolean or deprecation message).

docstring property writable ¤

docstring: Docstring | None

endlineno property writable ¤

endlineno: int | None

The ending line number of the target object.

See also: lineno.

exports property ¤

exports: list[str | ExprName] | None

The names of the objects exported by this (module) object through the __all__ variable.

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

from .submodule import __all__ as submodule_all

__all__ = ["hello", *submodule_all]

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

See also: GriffeLoader.expand_exports.

extra property ¤

extra: dict

Namespaced dictionaries storing extra metadata for this object, used by extensions.

filepath property ¤

filepath: Path | list[Path]

The file path (or directory list for namespace packages) where this object was defined.

See also: relative_filepath, relative_package_filepath.

final_target property ¤

final_target: Object

The final, resolved target, if possible.

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

See also: target, resolve_target, resolved.

functions property ¤

functions: dict[str, Function]

The function members.

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

git_info property writable ¤

git_info: GitInfo | None

Get the Git information for this object, if available.

has_docstring property ¤

has_docstring: bool

Whether this alias' target has a non-empty docstring.

See also: has_docstrings, docstring.

has_docstrings property ¤

has_docstrings: bool

Whether this alias' target or any of its members has a non-empty docstring.

See also: has_docstring, docstring.

imports property ¤

imports: dict[str, str]

The other objects imported by this alias' target.

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

See also: is_imported.

imports_future_annotations property ¤

imports_future_annotations: bool

Whether this module import future annotations.

inherited instance-attribute ¤

inherited: bool = inherited

Whether this alias represents an inherited member.

inherited_members property ¤

inherited_members: dict[str, Alias]

Members that are inherited from base classes.

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

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

See also: members.

is_alias class-attribute instance-attribute ¤

is_alias: bool = True

is_attribute property ¤

is_attribute: bool

is_class property ¤

is_class: bool

is_class_private property ¤

is_class_private: bool

Whether this object/alias is class-private (starts with __ and is a class member).

is_collection class-attribute instance-attribute ¤

is_collection: bool = False

Always false for aliases.

See also: ModulesCollection.

is_deprecated property ¤

is_deprecated: bool

Whether this object is deprecated.

is_exported property ¤

is_exported: bool

Whether this object/alias is exported (listed in __all__).

is_function property ¤

is_function: bool

is_generic property ¤

is_generic: bool

Whether this object is generic.

is_imported property ¤

is_imported: bool

Whether this object/alias was imported from another module.

is_init_method property ¤

is_init_method: bool

Whether this method is an __init__ method.

is_init_module property ¤

is_init_module: bool

Whether this module is an __init__.py module.

See also: is_module.

is_namespace_package property ¤

is_namespace_package: bool

Whether this module is a namespace package (top folder, no __init__.py).

See also: is_namespace_subpackage.

is_namespace_subpackage property ¤

is_namespace_subpackage: bool

Whether this module is a namespace subpackage.

See also: is_namespace_package.

is_package property ¤

is_package: bool

Whether this module is a package (top module).

See also: is_subpackage.

is_private property ¤

is_private: bool

Whether this object/alias is private (starts with _) but not special.

is_public property ¤

is_public: bool

Whether this object is considered public.

In modules, developers can mark objects as public thanks to the __all__ variable. In classes however, there is no convention or standard to do so.

Therefore, to decide whether an object is public, we follow this algorithm:

  • If the object's public attribute is set (boolean), return its value.
  • If the object is listed in its parent's (a module) __all__ attribute, it is public.
  • If the parent (module) defines __all__ and the object is not listed in, it is private.
  • If the object has a private name, it is private.
  • If the object was imported from another module, it is private.
  • Otherwise, the object is public.

is_special property ¤

is_special: bool

Whether this object/alias is special ("dunder" attribute/method, starts and end with __).

is_subpackage property ¤

is_subpackage: bool

Whether this module is a subpackage.

See also: is_package.

is_type_alias property ¤

is_type_alias: bool

is_wildcard_exposed property ¤

is_wildcard_exposed: bool

Whether this object/alias is exposed to wildcard imports.

To be exposed to wildcard imports, an object/alias must:

  • be available at runtime
  • have a module as parent
  • be listed in __all__ if __all__ is defined
  • or not be private (having a name starting with an underscore)

Special case for Griffe trees: a submodule is only exposed if its parent imports it.

Returns:

  • bool

    True or False.

keywords property ¤

keywords: dict[str, Expr | str]

The class keywords.

kind property ¤

kind: Kind

The target's kind, or Kind.ALIAS if the target cannot be resolved.

See also: is_kind.

labels property ¤

labels: set[str]

The target labels (property, dataclass, etc.).

See also: has_labels.

lineno property writable ¤

lineno: int | None

The starting line number of the target object.

See also: endlineno.

lines property ¤

lines: list[str]

The lines containing the source of this object.

See also: source, lines_collection.

lines_collection property ¤

lines_collection: LinesCollection

The lines collection attached to this object or its parents.

See also: lines, source.

Raises:

  • ValueError

    When no modules collection can be found in the object or its parents.

members property ¤

members: dict[str, Object | Alias]

The target's members (modules, classes, functions, attributes, type aliases).

See also: inherited_members, get_member, set_member, filter_members.

module property ¤

module: Module

The parent module of this object.

See also: package.

Raises:

  • ValueError

    When the object is not a module and does not have a parent.

modules property ¤

modules: dict[str, Module]

The module members.

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

modules_collection property ¤

modules_collection: ModulesCollection

The modules collection attached to the alias parents.

name instance-attribute ¤

name: str = name

The alias name.

overloads property writable ¤

overloads: dict[str, list[Function]] | list[Function] | None

The overloaded signatures declared in this class/module or for this function.

package property ¤

package: Module

The absolute top module (the package) of this object.

See also: module.

parameters property ¤

parameters: Parameters

The parameters of the current function or __init__ method for classes.

This property can fetch inherited members, and therefore is part of the consumer API: do not use when producing Griffe trees!

parent property writable ¤

parent: Module | Class | Alias | None

The parent of this alias.

path property ¤

path: str

The dotted path / import path of this object.

See also: canonical_path.

public instance-attribute ¤

public: bool | None = None

Whether this alias is public.

relative_filepath property ¤

relative_filepath: Path

The file path where this object was defined, relative to the current working directory.

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

See also: filepath, relative_package_filepath.

Raises:

  • ValueError

    When the relative path could not be computed.

relative_package_filepath property ¤

relative_package_filepath: Path

The file path where this object was defined, relative to the top module path.

See also: filepath, relative_filepath.

Raises:

  • ValueError

    When the relative path could not be computed.

resolved property ¤

resolved: bool

Whether this alias' target is resolved.

resolved_bases property ¤

resolved_bases: list[Object]

Resolved class bases.

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

returns property writable ¤

returns: str | Expr | None

The function return type annotation.

runtime instance-attribute ¤

runtime: bool = runtime

Whether this alias is available at runtime.

setter property ¤

setter: Function | None

The setter linked to this function (property).

source property ¤

source: str

The source code of this object.

See also: lines, lines_collection.

source_link: str | None

Get the source link for this object, if available.

target property writable ¤

target: Object | Alias

The resolved target (actual object), if possible.

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

See also: final_target, resolve_target, resolved.

target_path instance-attribute ¤

target_path: str

The path of this alias' target.

type_aliases property ¤

type_aliases: dict[str, TypeAlias]

The type alias members.

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

type_parameters property writable ¤

type_parameters: TypeParameters

The target type parameters.

value property writable ¤

value: str | Expr | None

The attribute or type alias value.

wildcard property ¤

wildcard: str | None

The module on which the wildcard import is performed (if any).

See also: GriffeLoader.expand_wildcards.

wildcard_imported instance-attribute ¤

wildcard_imported: bool = wildcard_imported

Whether this alias was created using a wildcard import.

__bool__ ¤

__bool__() -> bool

An alias is always true-ish.

Source code in packages/griffelib/src/griffe/_internal/models.py
1506
1507
1508
def __bool__(self) -> bool:
    """An alias is always true-ish."""
    return True

__delitem__ ¤

__delitem__(key: str | Sequence[str]) -> None

Delete a member with its name or path.

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

Members will be looked up in both declared members and inherited ones, triggering computation of the latter.

Parameters:

Examples:

>>> del griffe_object["foo"]
>>> del griffe_object["path.to.bar"]
>>> del griffe_object[("path", "to", "qux")]
Source code in packages/griffelib/src/griffe/_internal/mixins.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def __delitem__(self, key: str | Sequence[str]) -> None:
    """Delete a member with its name or path.

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

    Members will be looked up in both declared members and inherited ones,
    triggering computation of the latter.

    Parameters:
        key: The name or path of the member.

    Examples:
        >>> del griffe_object["foo"]
        >>> del griffe_object["path.to.bar"]
        >>> del griffe_object[("path", "to", "qux")]
    """
    parts = _get_parts(key)
    if len(parts) == 1:
        name = parts[0]
        try:
            del self.members[name]  # ty:ignore[unresolved-attribute]
        except KeyError:
            del self.inherited_members[name]  # ty:ignore[unresolved-attribute]
    else:
        del self.all_members[parts[0]][parts[1:]]  # ty:ignore[unresolved-attribute]

__getitem__ ¤

__getitem__(key: str | Sequence[str]) -> Any

Get a member with its name or path.

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

Members will be looked up in both declared members and inherited ones, triggering computation of the latter.

Parameters:

Examples:

>>> foo = griffe_object["foo"]
>>> bar = griffe_object["path.to.bar"]
>>> qux = griffe_object[("path", "to", "qux")]
Source code in packages/griffelib/src/griffe/_internal/mixins.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __getitem__(self, key: str | Sequence[str]) -> Any:
    """Get a member with its name or path.

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

    Members will be looked up in both declared members and inherited ones,
    triggering computation of the latter.

    Parameters:
        key: The name or path of the member.

    Examples:
        >>> foo = griffe_object["foo"]
        >>> bar = griffe_object["path.to.bar"]
        >>> qux = griffe_object[("path", "to", "qux")]
    """
    parts = _get_parts(key)
    if len(parts) == 1:
        return self.all_members[parts[0]]  # ty:ignore[unresolved-attribute]
    return self.all_members[parts[0]][parts[1:]]  # ty:ignore[unresolved-attribute]

__len__ ¤

__len__() -> int

The length of an alias is always 1.

Source code in packages/griffelib/src/griffe/_internal/models.py
1510
1511
1512
def __len__(self) -> int:
    """The length of an alias is always 1."""
    return 1

__setitem__ ¤

__setitem__(
    key: str | Sequence[str], value: Object | Alias
) -> None

Set a member with its name or path.

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

Parameters:

Examples:

>>> griffe_object["foo"] = foo
>>> griffe_object["path.to.bar"] = bar
>>> griffe_object[("path", "to", "qux")] = qux
Source code in packages/griffelib/src/griffe/_internal/mixins.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def __setitem__(self, key: str | Sequence[str], value: Object | Alias) -> None:
    """Set a member with its name or path.

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

    Parameters:
        key: The name or path of the member.
        value: The member.

    Examples:
        >>> griffe_object["foo"] = foo
        >>> griffe_object["path.to.bar"] = bar
        >>> griffe_object[("path", "to", "qux")] = qux
    """
    parts = _get_parts(key)
    if len(parts) == 1:
        name = parts[0]
        self.members[name] = value  # ty:ignore[unresolved-attribute]
        if self.is_collection:  # ty:ignore[unresolved-attribute]
            value._modules_collection = self  # ty:ignore[invalid-assignment]
        else:
            value.parent = self  # ty:ignore[invalid-assignment]
    else:
        self.members[parts[0]][parts[1:]] = value  # ty:ignore[unresolved-attribute]

as_dict ¤

as_dict(
    *, full: bool = False, **kwargs: Any
) -> dict[str, Any]

Return this alias' data as a dictionary.

See also: as_json.

Parameters:

  • full ¤

    (bool, default: False ) –

    Whether to return full info, or just base info.

  • **kwargs ¤

    (Any, default: {} ) –

    Additional serialization options.

Returns:

Source code in packages/griffelib/src/griffe/_internal/models.py
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
def as_dict(self, *, full: bool = False, **kwargs: Any) -> dict[str, Any]:  # noqa: ARG002
    """Return this alias' data as a dictionary.

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

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

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

    if self.public is not None:
        base["public"] = self.public
    if self.deprecated is not None:
        base["deprecated"] = self.deprecated
    if self.alias_lineno:
        base["lineno"] = self.alias_lineno
    if self.alias_endlineno:
        base["endlineno"] = self.alias_endlineno
    if self.analysis:
        base["analysis"] = self.analysis

    if full:
        base.update(
            {
                "path": self.path,
                "is_public": self.is_public,
                "is_deprecated": self.is_deprecated,
                "is_private": self.is_private,
                "is_class_private": self.is_class_private,
                "is_special": self.is_special,
                "is_imported": self.is_imported,
                "is_exported": self.is_exported,
                "is_wildcard_exposed": self.is_wildcard_exposed,
            },
        )

    return base

as_json ¤

as_json(*, full: bool = False, **kwargs: Any) -> str

Return this target's data as a JSON string.

See also: as_dict.

Parameters:

  • full ¤

    (bool, default: False ) –

    Whether to return full info, or just base info.

  • **kwargs ¤

    (Any, default: {} ) –

    Additional serialization options passed to encoder.

Returns:

  • str

    A JSON string.

Source code in packages/griffelib/src/griffe/_internal/models.py
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
def as_json(self, *, full: bool = False, **kwargs: Any) -> str:
    """Return this target's data as a JSON string.

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

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

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

del_member ¤

del_member(key: str | Sequence[str]) -> None

Delete a member with its name or path.

This method is part of the producer API: you can use it safely while building Griffe trees (for example in Griffe extensions).

Members will be looked up in declared members only, not inherited ones.

Parameters:

Examples:

>>> griffe_object.del_member("foo")
>>> griffe_object.del_member("path.to.bar")
>>> griffe_object.del_member(("path", "to", "qux"))
Source code in packages/griffelib/src/griffe/_internal/mixins.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def del_member(self, key: str | Sequence[str]) -> None:
    """Delete a member with its name or path.

    This method is part of the producer API:
    you can use it safely while building Griffe trees
    (for example in Griffe extensions).

    Members will be looked up in declared members only, not inherited ones.

    Parameters:
        key: The name or path of the member.

    Examples:
        >>> griffe_object.del_member("foo")
        >>> griffe_object.del_member("path.to.bar")
        >>> griffe_object.del_member(("path", "to", "qux"))
    """
    parts = _get_parts(key)
    if len(parts) == 1:
        name = parts[0]
        del self.members[name]  # ty:ignore[unresolved-attribute]
    else:
        self.members[parts[0]].del_member(parts[1:])  # ty:ignore[unresolved-attribute]

filter_members ¤

filter_members(
    *predicates: Callable[[Object | Alias], bool],
) -> dict[str, Object | Alias]

Filter and return members based on predicates.

See also: members, get_member, set_member.

Parameters:

  • *predicates ¤

    (Callable[[Object | Alias], bool], default: () ) –

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

Returns:

Source code in packages/griffelib/src/griffe/_internal/models.py
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]:
    """Filter and return members based on predicates.

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

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

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

from_json classmethod ¤

from_json(json_string: str, **kwargs: Any) -> _ObjType

Create an instance of this class from a JSON string.

Parameters:

  • json_string ¤

    (str) –

    JSON to decode into Object.

  • **kwargs ¤

    (Any, default: {} ) –

    Additional options passed to decoder.

Returns:

  • _ObjType

    An Object instance.

Raises:

  • TypeError

    When the json_string does not represent and object of the class from which this classmethod has been called.

Source code in packages/griffelib/src/griffe/_internal/mixins.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
@classmethod
def from_json(cls: type[_ObjType], json_string: str, **kwargs: Any) -> _ObjType:  # noqa: PYI019
    """Create an instance of this class from a JSON string.

    Parameters:
        json_string: JSON to decode into Object.
        **kwargs: Additional options passed to decoder.

    Returns:
        An Object instance.

    Raises:
        TypeError: When the json_string does not represent and object
            of the class from which this classmethod has been called.
    """
    from griffe._internal.encoders import json_decoder  # Avoid circular import.  # noqa: PLC0415

    kwargs.setdefault("object_hook", json_decoder)
    obj = json.loads(json_string, **kwargs)
    if not isinstance(obj, cls):
        raise TypeError(f"provided JSON object is not of type {cls}")
    return obj

get_member ¤

get_member(key: str | Sequence[str]) -> Any

Get a member with its name or path.

This method is part of the producer API: you can use it safely while building Griffe trees (for example in Griffe extensions).

Members will be looked up in declared members only, not inherited ones.

Parameters:

Examples:

>>> foo = griffe_object["foo"]
>>> bar = griffe_object["path.to.bar"]
>>> bar = griffe_object[("path", "to", "bar")]
Source code in packages/griffelib/src/griffe/_internal/mixins.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def get_member(self, key: str | Sequence[str]) -> Any:
    """Get a member with its name or path.

    This method is part of the producer API:
    you can use it safely while building Griffe trees
    (for example in Griffe extensions).

    Members will be looked up in declared members only, not inherited ones.

    Parameters:
        key: The name or path of the member.

    Examples:
        >>> foo = griffe_object["foo"]
        >>> bar = griffe_object["path.to.bar"]
        >>> bar = griffe_object[("path", "to", "bar")]
    """
    parts = _get_parts(key)
    if len(parts) == 1:
        return self.members[parts[0]]  # ty:ignore[unresolved-attribute]
    return self.members[parts[0]].get_member(parts[1:])  # ty:ignore[unresolved-attribute]

has_labels ¤

has_labels(*labels: str) -> bool

Tell if this object has all the given labels.

See also: labels.

Parameters:

  • *labels ¤

    (str, default: () ) –

    Labels that must be present.

Returns:

  • bool

    True or False.

Source code in packages/griffelib/src/griffe/_internal/models.py
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
def has_labels(self, *labels: str) -> bool:
    """Tell if this object has all the given labels.

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

    Parameters:
        *labels: Labels that must be present.

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

is_kind ¤

is_kind(kind: str | Kind | set[str | Kind]) -> bool

Tell if this object is of the given kind.

See also: is_module, is_class, is_function, is_attribute, is_type_alias, is_alias.

Parameters:

  • kind ¤

    (str | Kind | set[str | Kind]) –

    An instance or set of kinds (strings or enumerations).

Raises:

  • ValueError

    When an empty set is given as argument.

Returns:

  • bool

    True or False.

Source code in packages/griffelib/src/griffe/_internal/models.py
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool:
    """Tell if this object is of the given kind.

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

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

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

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

mro ¤

mro() -> list[Class]

Return a list of classes in order corresponding to Python's MRO.

Source code in packages/griffelib/src/griffe/_internal/models.py
2128
2129
2130
def mro(self) -> list[Class]:
    """Return a list of classes in order corresponding to Python's MRO."""
    return cast("Class", self.final_target).mro()

resolve ¤

resolve(name: str) -> str

Resolve a name within this object's and parents' scope.

Parameters:

  • name ¤

    (str) –

    The name to resolve.

Raises:

Returns:

  • str

    The resolved name.

Source code in packages/griffelib/src/griffe/_internal/models.py
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
def resolve(self, name: str) -> str:
    """Resolve a name within this object's and parents' scope.

    Parameters:
        name: The name to resolve.

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

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

resolve_target ¤

resolve_target() -> None

Resolve the target.

See also: target, final_target, resolved.

Raises:

  • AliasResolutionError

    When the target cannot be resolved. It happens when the target does not exist, or could not be loaded (unhandled dynamic object?), or when the target is from a module that was not loaded and added to the collection.

  • CyclicAliasError

    When the resolved target is the alias itself.

Source code in packages/griffelib/src/griffe/_internal/models.py
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
def resolve_target(self) -> None:
    """Resolve the target.

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

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

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

set_member ¤

set_member(
    key: str | Sequence[str], value: Object | Alias
) -> None

Set a member with its name or path.

This method is part of the producer API: you can use it safely while building Griffe trees (for example in Griffe extensions).

Parameters:

Examples:

>>> griffe_object.set_member("foo", foo)
>>> griffe_object.set_member("path.to.bar", bar)
>>> griffe_object.set_member(("path", "to", "qux"), qux)
Source code in packages/griffelib/src/griffe/_internal/mixins.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def set_member(self, key: str | Sequence[str], value: Object | Alias) -> None:
    """Set a member with its name or path.

    This method is part of the producer API:
    you can use it safely while building Griffe trees
    (for example in Griffe extensions).

    Parameters:
        key: The name or path of the member.
        value: The member.

    Examples:
        >>> griffe_object.set_member("foo", foo)
        >>> griffe_object.set_member("path.to.bar", bar)
        >>> griffe_object.set_member(("path", "to", "qux"), qux)
    """
    parts = _get_parts(key)
    if len(parts) == 1:
        name = parts[0]
        if name in self.members:  # ty:ignore[unresolved-attribute]
            member = self.members[name]  # ty:ignore[unresolved-attribute]
            if not member.is_alias:
                # When reassigning a module to an existing one,
                # try to merge them as one regular and one stubs module
                # (implicit support for .pyi modules).
                if member.is_module and not (member.is_namespace_package or member.is_namespace_subpackage):
                    # Accessing attributes of the value or member can trigger alias errors.
                    # Accessing file paths can trigger a builtin module error.
                    with suppress(AliasResolutionError, CyclicAliasError, BuiltinModuleError):
                        if value.is_module and value.filepath != member.filepath:
                            psd = self._psd if self.is_collection else self.modules_collection._psd  # ty:ignore[unresolved-attribute]
                            with suppress(ValueError):
                                value = merge_stubs(member, value, prefer_stubs_docs=psd)  # ty:ignore[invalid-argument-type]
                for alias in member.aliases.values():
                    with suppress(CyclicAliasError):
                        alias.target = value
        self.members[name] = value  # ty:ignore[unresolved-attribute]
        if self.is_collection:  # ty:ignore[unresolved-attribute]
            value._modules_collection = self  # ty:ignore[invalid-assignment]
        else:
            value.parent = self  # ty:ignore[invalid-assignment]
    else:
        self.members[parts[0]].set_member(parts[1:], value)  # ty:ignore[unresolved-attribute]

signature ¤

signature(
    *, return_type: bool = False, name: str | None = None
) -> str

Construct the class/function signature.

Parameters:

  • return_type ¤

    (bool, default: False ) –

    Whether to include the return type in the signature.

  • name ¤

    (str | None, default: None ) –

    The name of the class/function to use in the signature.

Returns:

  • str

    A string representation of the class/function signature.

Source code in packages/griffelib/src/griffe/_internal/models.py
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
def signature(self, *, return_type: bool = False, name: str | None = None) -> str:
    """Construct the class/function signature.

    Parameters:
        return_type: Whether to include the return type in the signature.
        name: The name of the class/function to use in the signature.

    Returns:
        A string representation of the class/function signature.
    """
    return cast("Class | Function", self.final_target).signature(return_type=return_type, name=name)