Function - Griffe

Bases: Object


              flowchart TD
              griffe.Function[Function]
              griffe._internal.models.Object[Object]
              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.models.Object --> griffe.Function
                                griffe._internal.mixins.ObjectAliasMixin --> griffe._internal.models.Object
                                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.Function href "" "griffe.Function"
              click griffe._internal.models.Object href "" "griffe._internal.models.Object"
              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"
            

The class representing a Python function.

Parameters:

  • *args ¤

    (Any, default: () ) –
  • parameters ¤

    (Parameters | None, default: None ) –

    The function parameters.

  • returns ¤

    (str | Expr | None, default: None ) –

    The function return annotation.

  • decorators ¤

    (list[Decorator] | None, default: None ) –

    The function decorators, if any.

  • **kwargs ¤

    (Any, default: {} ) –

Referenced by:

Returned by:

Used by:

Methods:

  • __bool__

    An object is always true-ish.

  • __delitem__

    Delete a member with its name or path.

  • __getitem__

    Get a member with its name or path.

  • __len__

    The number of members in this object, recursively.

  • __setitem__

    Set a member with its name or path.

  • as_dict

    Return this function's data as a dictionary.

  • as_json

    Return this object'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.

  • resolve

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

  • set_member

    Set a member with its name or path.

  • signature

    Construct the function signature.

Attributes:

Source code in packages/griffelib/src/griffe/_internal/models.py
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
def __init__(
    self,
    *args: Any,
    parameters: Parameters | None = None,
    returns: str | Expr | None = None,
    decorators: list[Decorator] | None = None,
    **kwargs: Any,
) -> None:
    """Initialize the function.

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

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

all_members property ¤

All members (declared and inherited).

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

analysis instance-attribute ¤

The type of analysis used to load this object.

None means the object was created manually.

annotation property ¤

The type annotation of the returned value.

attributes property ¤

The attribute members.

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

canonical_path property ¤

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 ¤

The class members.

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

decorators instance-attribute ¤

deprecated instance-attribute ¤

deprecated: bool | str | None = None

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

docstring instance-attribute ¤

endlineno instance-attribute ¤

exports instance-attribute ¤

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.

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

filepath property ¤

functions property ¤

The function members.

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

git_info property writable ¤

Git information for this object, if available.

has_docstring property ¤

has_docstrings property ¤

Whether this object or any of its members has a docstring (empty or not).

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

See also: docstring, has_docstring.

imports instance-attribute ¤

The other objects imported by this object.

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

inherited class-attribute instance-attribute ¤

Always false for objects.

Only aliases can be marked as inherited.

inherited_members property ¤

Members that are inherited from base classes.

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

See also: members.

is_alias class-attribute instance-attribute ¤

is_attribute property ¤

is_class property ¤

is_class_private property ¤

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 objects.

is_deprecated property ¤

Whether this object is deprecated.

is_exported property ¤

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

is_function property ¤

is_generic property ¤

Whether this object is generic.

is_imported property ¤

Whether this object/alias was imported from another module.

is_init_method property ¤

Whether this function is an __init__ method.

is_init_module property ¤

is_module property ¤

is_namespace_package property ¤

is_namespace_package: bool

is_namespace_subpackage property ¤

is_namespace_subpackage: bool

is_package property ¤

is_private property ¤

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

is_public property ¤

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 ¤

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

is_subpackage property ¤

is_type_alias property ¤

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.

kind class-attribute instance-attribute ¤

The object kind.

labels instance-attribute ¤

lineno instance-attribute ¤

lines property ¤

lines_collection property ¤

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 instance-attribute ¤

modules property ¤

The module members.

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

modules_collection property ¤

The modules collection attached to this object or its parents.

Raises:

  • ValueError

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

name instance-attribute ¤

The object name.

overloads instance-attribute ¤

overloads: list[Function] | None = None

The overloaded signatures of this function.

parameters instance-attribute ¤

parameters: Parameters = parameters or Parameters()

parent instance-attribute ¤

The parent of the object (none if top module).

path property ¤

The dotted path of this object.

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

See also: canonical_path.

Examples:

>>> import griffe
>>> markdown = griffe.load("markdown")
>>> markdown["core.Markdown.references"].path
'markdown.core.Markdown.references'

public instance-attribute ¤

public: bool | None = None

Whether this object is public.

relative_filepath property ¤

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

returns instance-attribute ¤

The function return type annotation.

runtime instance-attribute ¤

Whether this object is available at runtime.

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

source property ¤

Source link for this object, if available.

type_aliases property ¤

The type alias members.

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

type_parameters instance-attribute ¤

__bool__ ¤

An object is always true-ish.

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

__delitem__ ¤

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
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
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__ ¤

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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__ ¤

The number of members in this object, recursively.

Source code in packages/griffelib/src/griffe/_internal/models.py
def __len__(self) -> int:
    """The number of members in this object, recursively."""
    return len(self.members) + sum(len(member) for member in self.members.values())

__setitem__ ¤

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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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 ¤

Return this function's data as a dictionary.

See also: as_json.

Parameters:

  • **kwargs ¤

    (Any, default: {} ) –

    Additional serialization options.

Returns:

Source code in packages/griffelib/src/griffe/_internal/models.py
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
def as_dict(self, **kwargs: Any) -> dict[str, Any]:
    """Return this function's data as a dictionary.

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

    Parameters:
        **kwargs: Additional serialization options.

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

as_json ¤

Return this object's data as a JSON string.

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/mixins.py
215
216
217
218
219
220
221
222
223
224
225
226
227
def as_json(self, *, full: bool = False, **kwargs: Any) -> str:
    """Return this object's data as a JSON string.

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

    Returns:
        A JSON string.
    """
    from griffe._internal.encoders import JSONEncoder  # Avoid circular import.  # noqa: PLC0415

    return json.dumps(self, cls=JSONEncoder, full=full, **kwargs)

del_member ¤

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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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 and return members based on predicates.

See also: members.

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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
def filter_members(self, *predicates: Callable[[Object | Alias], bool]) -> dict[str, Object | Alias]:
    """Filter and return members based on predicates.

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

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

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

from_json classmethod ¤

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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
@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 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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]

is_kind ¤

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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def is_kind(self, kind: str | Kind | set[str | Kind]) -> bool:
    """Tell if this object is of the given kind.

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

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

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

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

resolve ¤

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
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
def resolve(self, name: str) -> str:
    """Resolve a name within this object's and parents' scope.

    Parameters:
        name: The name to resolve.

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

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

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

set_member ¤

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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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:
                            with suppress(ValueError):
                                value = merge_stubs(member, value)  # 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 ¤

Construct the function signature.

Parameters:

  • return_type ¤

    (bool, default: True ) –

    Whether to include the return type in the signature.

  • name ¤

    (str | None, default: None ) –

    The name of the function to use in the signature.

Returns:

  • str

    A string representation of the function signature.

Source code in packages/griffelib/src/griffe/_internal/models.py
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
def signature(self, *, return_type: bool = True, name: str | None = None) -> str:
    """Construct the function signature.

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

    Returns:
        A string representation of the function signature.
    """
    signature = f"{name or self.name}("

    has_pos_only = any(p.kind == ParameterKind.positional_only for p in self.parameters)
    render_pos_only_separator = True
    render_kw_only_separator = True

    param_strs = []

    for index, param in enumerate(self.parameters):
        # Skip 'self' or 'cls' for class methods if it's the first parameter.
        if index == 0 and param.name in ("self", "cls") and self.parent and self.parent.is_class:
            continue

        param_str = ""

        # Handle parameter kind and separators.
        if param.kind != ParameterKind.positional_only:
            if has_pos_only and render_pos_only_separator:
                render_pos_only_separator = False
                param_strs.append("/")

            if param.kind == ParameterKind.keyword_only and render_kw_only_separator:
                render_kw_only_separator = False
                param_strs.append("*")

        # Handle variadic parameters.
        if param.kind == ParameterKind.var_positional:
            param_str = "*"
            render_kw_only_separator = False
        elif param.kind == ParameterKind.var_keyword:
            param_str = "**"

        # Add parameter name.
        param_str += param.name

        # Handle type annotation
        if param.annotation is not None:
            param_str += f": {param.annotation}"
            equal = " = "  # Space around equal when annotation is present.
        else:
            equal = "="  # No space when no annotation.

        # Handle default value.
        if param.default is not None and param.kind not in {
            ParameterKind.var_positional,
            ParameterKind.var_keyword,
        }:
            param_str += f"{equal}{param.default}"

        param_strs.append(param_str)

    # If we have positional-only parameters but no '/' was added yet
    if has_pos_only and render_pos_only_separator:
        param_strs.append("/")

    signature += ", ".join(param_strs)
    signature += ")"

    # Add return type if present.
    if return_type and self.annotation:
        signature += f" -> {self.annotation}"

    return signature