Skip to content

rendering ¤

This module implements rendering utilities.

Classes:

  • Order

    Enumeration for the possible members ordering.

Functions:

Order ¤

Bases: Enum

Enumeration for the possible members ordering.

Attributes:

alphabetical class-attribute instance-attribute ¤

alphabetical = 'alphabetical'

Alphabetical order.

source class-attribute instance-attribute ¤

source = 'source'

Source code order.

do_any ¤

do_any(seq: Sequence, attribute: str | None = None) -> bool

Check if at least one of the item in the sequence evaluates to true.

The any builtin as a filter for Jinja templates.

Parameters:

  • seq (Sequence) –

    An iterable object.

  • attribute (str | None, default: None ) –

    The attribute name to use on each object of the iterable.

Returns:

  • bool

    A boolean telling if any object of the iterable evaluated to True.

Source code in src/griffe2md/rendering.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def do_any(seq: Sequence, attribute: str | None = None) -> bool:
    """Check if at least one of the item in the sequence evaluates to true.

    The `any` builtin as a filter for Jinja templates.

    Arguments:
        seq: An iterable object.
        attribute: The attribute name to use on each object of the iterable.

    Returns:
        A boolean telling if any object of the iterable evaluated to True.
    """
    if attribute is None:
        return any(seq)
    return any(_[attribute] for _ in seq)

do_as_attributes_section ¤

do_as_attributes_section(
    attributes: Sequence[Attribute],
    *,
    check_public: bool = True
) -> DocstringSectionAttributes

Build an attributes section from a list of attributes.

Parameters:

  • attributes (Sequence[Attribute]) –

    The attributes to build the section from.

  • check_public (bool, default: True ) –

    Whether to check if the attribute is public.

Returns:

  • DocstringSectionAttributes

    An attributes docstring section.

Source code in src/griffe2md/rendering.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def do_as_attributes_section(
    attributes: Sequence[Attribute],
    *,
    check_public: bool = True,
) -> DocstringSectionAttributes:
    """Build an attributes section from a list of attributes.

    Parameters:
        attributes: The attributes to build the section from.
        check_public: Whether to check if the attribute is public.

    Returns:
        An attributes docstring section.
    """
    return DocstringSectionAttributes(
        [
            DocstringAttribute(
                name=attribute.name,
                description=attribute.docstring.value.split("\n", 1)[0] if attribute.docstring else "",
                annotation=attribute.annotation,
                value=attribute.value,
            )
            for attribute in attributes
            if not check_public or attribute.is_public or from_private_package(attribute)
        ],
    )

do_as_classes_section ¤

do_as_classes_section(
    classes: Sequence[Class], *, check_public: bool = True
) -> DocstringSectionClasses

Build a classes section from a list of classes.

Parameters:

  • classes (Sequence[Class]) –

    The classes to build the section from.

  • check_public (bool, default: True ) –

    Whether to check if the class is public.

Returns:

  • DocstringSectionClasses

    A classes docstring section.

Source code in src/griffe2md/rendering.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def do_as_classes_section(classes: Sequence[Class], *, check_public: bool = True) -> DocstringSectionClasses:
    """Build a classes section from a list of classes.

    Parameters:
        classes: The classes to build the section from.
        check_public: Whether to check if the class is public.

    Returns:
        A classes docstring section.
    """
    return DocstringSectionClasses(
        [
            DocstringClass(
                name=cls.name,
                description=cls.docstring.value.split("\n", 1)[0] if cls.docstring else "",
            )
            for cls in classes
            if not check_public or cls.is_public or from_private_package(cls)
        ],
    )

do_as_functions_section ¤

do_as_functions_section(
    functions: Sequence[Function],
    *,
    check_public: bool = True
) -> DocstringSectionFunctions

Build a functions section from a list of functions.

Parameters:

  • functions (Sequence[Function]) –

    The functions to build the section from.

  • check_public (bool, default: True ) –

    Whether to check if the function is public.

Returns:

  • DocstringSectionFunctions

    A functions docstring section.

Source code in src/griffe2md/rendering.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
def do_as_functions_section(functions: Sequence[Function], *, check_public: bool = True) -> DocstringSectionFunctions:
    """Build a functions section from a list of functions.

    Parameters:
        functions: The functions to build the section from.
        check_public: Whether to check if the function is public.

    Returns:
        A functions docstring section.
    """
    return DocstringSectionFunctions(
        [
            DocstringFunction(
                name=function.name,
                description=function.docstring.value.split("\n", 1)[0] if function.docstring else "",
            )
            for function in functions
            if not check_public or function.is_public or from_private_package(function)
        ],
    )

do_as_modules_section ¤

do_as_modules_section(
    modules: Sequence[Module], *, check_public: bool = True
) -> DocstringSectionModules

Build a modules section from a list of modules.

Parameters:

  • modules (Sequence[Module]) –

    The modules to build the section from.

  • check_public (bool, default: True ) –

    Whether to check if the module is public.

Returns:

  • DocstringSectionModules

    A modules docstring section.

Source code in src/griffe2md/rendering.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def do_as_modules_section(modules: Sequence[Module], *, check_public: bool = True) -> DocstringSectionModules:
    """Build a modules section from a list of modules.

    Parameters:
        modules: The modules to build the section from.
        check_public: Whether to check if the module is public.

    Returns:
        A modules docstring section.
    """
    return DocstringSectionModules(
        [
            DocstringModule(
                name=module.name,
                description=module.docstring.value.split("\n", 1)[0] if module.docstring else "",
            )
            for module in modules
            if not check_public or module.is_public or from_private_package(module)
        ],
    )

do_filter_objects ¤

do_filter_objects(
    objects_dictionary: dict[str, Object | Alias],
    *,
    filters: Sequence[tuple[Pattern, bool]] | None = None,
    members_list: bool | list[str] | None = None,
    inherited_members: bool | list[str] = False,
    keep_no_docstrings: bool = True
) -> list[Object | Alias]

Filter a dictionary of objects based on their docstrings.

Parameters:

  • objects_dictionary (dict[str, Object | Alias]) –

    The dictionary of objects.

  • filters (Sequence[tuple[Pattern, bool]] | None, default: None ) –

    Filters to apply, based on members' names. Each element is a tuple: a pattern, and a boolean indicating whether to reject the object if the pattern matches.

  • members_list (bool | list[str] | None, default: None ) –

    An optional, explicit list of members to keep. When given and empty, return an empty list. When given and not empty, ignore filters and docstrings presence/absence.

  • inherited_members (bool | list[str], default: False ) –

    Whether to keep inherited members or exclude them.

  • keep_no_docstrings (bool, default: True ) –

    Whether to keep objects with no/empty docstrings (recursive check).

Returns:

  • list[Object | Alias]

    A list of objects.

Source code in src/griffe2md/rendering.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def do_filter_objects(
    objects_dictionary: dict[str, Object | Alias],
    *,
    filters: Sequence[tuple[Pattern, bool]] | None = None,
    members_list: bool | list[str] | None = None,
    inherited_members: bool | list[str] = False,
    keep_no_docstrings: bool = True,
) -> list[Object | Alias]:
    """Filter a dictionary of objects based on their docstrings.

    Parameters:
        objects_dictionary: The dictionary of objects.
        filters: Filters to apply, based on members' names.
            Each element is a tuple: a pattern, and a boolean indicating whether
            to reject the object if the pattern matches.
        members_list: An optional, explicit list of members to keep.
            When given and empty, return an empty list.
            When given and not empty, ignore filters and docstrings presence/absence.
        inherited_members: Whether to keep inherited members or exclude them.
        keep_no_docstrings: Whether to keep objects with no/empty docstrings (recursive check).

    Returns:
        A list of objects.
    """
    inherited_members_specified = False
    if inherited_members is True:
        # Include all inherited members.
        objects = list(objects_dictionary.values())
    elif inherited_members is False:
        # Include no inherited members.
        objects = [obj for obj in objects_dictionary.values() if not obj.inherited]
    else:
        # Include specific inherited members.
        inherited_members_specified = True
        objects = [
            obj for obj in objects_dictionary.values() if not obj.inherited or obj.name in set(inherited_members)
        ]

    if members_list is True:
        # Return all pre-selected members.
        return objects

    if members_list is False or members_list == []:
        # Return selected inherited members, if any.
        return [obj for obj in objects if obj.inherited]

    if members_list is not None:
        # Return selected members (keeping any pre-selected inherited members).
        return [
            obj for obj in objects if obj.name in set(members_list) or (inherited_members_specified and obj.inherited)
        ]

    # Use filters and docstrings.
    if filters:
        objects = [
            obj for obj in objects if _keep_object(obj.name, filters) or (inherited_members_specified and obj.inherited)
        ]
    if keep_no_docstrings:
        return objects

    return [obj for obj in objects if obj.has_docstrings or (inherited_members_specified and obj.inherited)]

do_format_attribute ¤

do_format_attribute(
    context: Context,
    attribute_path: Markup,
    attribute: Attribute,
    line_length: int,
    *,
    crossrefs: bool = False
) -> str

Format an attribute using Black.

Parameters:

  • context (Context) –

    Jinja context, passed automatically.

  • attribute_path (Markup) –

    The path of the callable we render the signature of.

  • attribute (Attribute) –

    The attribute we render the signature of.

  • line_length (int) –

    The line length to give to Black.

  • crossrefs (bool, default: False ) –

    Whether to cross-reference types in the signature.

Returns:

  • str

    The same code, formatted.

Source code in src/griffe2md/rendering.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
@pass_context
def do_format_attribute(
    context: Context,
    attribute_path: Markup,
    attribute: Attribute,
    line_length: int,
    *,
    crossrefs: bool = False,
) -> str:
    """Format an attribute using Black.

    Parameters:
        context: Jinja context, passed automatically.
        attribute_path: The path of the callable we render the signature of.
        attribute: The attribute we render the signature of.
        line_length: The line length to give to Black.
        crossrefs: Whether to cross-reference types in the signature.

    Returns:
        The same code, formatted.
    """
    env = context.environment
    template = env.get_template("expression.md.jinja")
    annotations = context.parent["config"]["show_signature_annotations"]
    separate_signature = context.parent["config"]["separate_signature"]
    old_stash_ref_filter = env.filters["stash_crossref"]

    stash: dict[str, str] = {}
    if separate_signature and crossrefs:
        env.filters["stash_crossref"] = partial(_stash_crossref, stash)

    try:
        signature = str(attribute_path).strip()
        if annotations and attribute.annotation:
            annotation = template.render(context.parent, expression=attribute.annotation, signature=True)
            signature += f": {annotation}"
        if attribute.value:
            value = template.render(context.parent, expression=attribute.value, signature=True)
            signature += f" = {value}"
    finally:
        env.filters["stash_crossref"] = old_stash_ref_filter

    signature = do_format_code(signature, line_length)

    if stash:
        for key, value in stash.items():
            signature = re.sub(rf"\b{key}\b", value, signature)

    return signature

do_format_code ¤

do_format_code(code: str, line_length: int) -> str

Format code using Black.

Parameters:

  • code (str) –

    The code to format.

  • line_length (int) –

    The line length to give to Black.

Returns:

  • str

    The same code, formatted.

Source code in src/griffe2md/rendering.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def do_format_code(code: str, line_length: int) -> str:
    """Format code using Black.

    Parameters:
        code: The code to format.
        line_length: The line length to give to Black.

    Returns:
        The same code, formatted.
    """
    code = code.strip()
    if len(code) < line_length:
        return code
    formatter = _get_black_formatter()
    return formatter(code, line_length)

do_format_signature ¤

do_format_signature(
    context: Context,
    callable_path: Markup,
    function: Function,
    line_length: int,
    *,
    annotations: bool | None = None,
    crossrefs: bool = False
) -> str

Format a signature using Black.

Parameters:

  • context (Context) –

    Jinja context, passed automatically.

  • callable_path (Markup) –

    The path of the callable we render the signature of.

  • function (Function) –

    The function we render the signature of.

  • line_length (int) –

    The line length to give to Black.

  • annotations (bool | None, default: None ) –

    Whether to show type annotations.

  • crossrefs (bool, default: False ) –

    Whether to cross-reference types in the signature.

Returns:

  • str

    The same code, formatted.

Source code in src/griffe2md/rendering.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@pass_context
def do_format_signature(
    context: Context,
    callable_path: Markup,
    function: Function,
    line_length: int,
    *,
    annotations: bool | None = None,
    crossrefs: bool = False,
) -> str:
    """Format a signature using Black.

    Parameters:
        context: Jinja context, passed automatically.
        callable_path: The path of the callable we render the signature of.
        function: The function we render the signature of.
        line_length: The line length to give to Black.
        annotations: Whether to show type annotations.
        crossrefs: Whether to cross-reference types in the signature.

    Returns:
        The same code, formatted.
    """
    env = context.environment
    template = env.get_template("signature.md.jinja")
    config_annotations = context.parent["config"]["show_signature_annotations"]
    old_stash_ref_filter = env.filters["stash_crossref"]

    stash: dict[str, str] = {}
    if (annotations or config_annotations) and crossrefs:
        env.filters["stash_crossref"] = partial(_stash_crossref, stash)

    if annotations is None:
        new_context = context.parent
    else:
        new_context = dict(context.parent)
        new_context["config"] = dict(new_context["config"])
        new_context["config"]["show_signature_annotations"] = annotations
    try:
        signature = template.render(new_context, function=function, signature=True)
    finally:
        env.filters["stash_crossref"] = old_stash_ref_filter

    signature = _format_signature(callable_path, signature, line_length)

    if stash:
        for key, value in stash.items():
            signature = re.sub(rf"\b{key}\b", value, signature)

    return signature

do_heading ¤

do_heading(content: str, heading_level: int) -> str

Render a Markdown heading.

Source code in src/griffe2md/rendering.py
309
310
311
def do_heading(content: str, heading_level: int) -> str:
    """Render a Markdown heading."""
    return f"\n{'#' * heading_level} {content}\n\n"

do_order_members ¤

do_order_members(
    members: Sequence[Object | Alias],
    order: Order,
    members_list: bool | list[str] | None,
) -> Sequence[Object | Alias]

Order members given an ordering method.

Parameters:

  • members (Sequence[Object | Alias]) –

    The members to order.

  • order (Order) –

    The ordering method.

  • members_list (bool | list[str] | None) –

    An optional member list (manual ordering).

Returns:

  • Sequence[Object | Alias]

    The same members, ordered.

Source code in src/griffe2md/rendering.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def do_order_members(
    members: Sequence[Object | Alias],
    order: Order,
    members_list: bool | list[str] | None,
) -> Sequence[Object | Alias]:
    """Order members given an ordering method.

    Parameters:
        members: The members to order.
        order: The ordering method.
        members_list: An optional member list (manual ordering).

    Returns:
        The same members, ordered.
    """
    if isinstance(members_list, list) and members_list:
        sorted_members = []
        members_dict = {member.name: member for member in members}
        for name in members_list:
            if name in members_dict:
                sorted_members.append(members_dict[name])
        return sorted_members
    return sorted(members, key=order_map[order])

do_split_path ¤

do_split_path(
    path: str, full_path: str
) -> list[tuple[str, str]]

Split object paths for building cross-references.

Parameters:

  • path (str) –

    The path to split.

Returns:

Source code in src/griffe2md/rendering.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def do_split_path(path: str, full_path: str) -> list[tuple[str, str]]:
    """Split object paths for building cross-references.

    Parameters:
        path: The path to split.

    Returns:
        A list of pairs (title, full path).
    """
    if "." not in path:
        return [(path, full_path)]
    pairs = []
    full_path = ""
    for part in path.split("."):
        if full_path:
            full_path += f".{part}"
        else:
            full_path = part
        pairs.append((part, full_path))
    return pairs

from_private_package ¤

from_private_package(obj: Object | Alias) -> bool

Tell if an alias points to an object coming from a corresponding private package.

For example, return true for an alias in package ast pointing at an object in package _ast.

Parameters:

  • obj (Object | Alias) –

    The object (alias) to check.

Returns:

  • bool

    True or false.

Source code in src/griffe2md/rendering.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def from_private_package(obj: Object | Alias) -> bool:
    """Tell if an alias points to an object coming from a corresponding private package.

    For example, return true for an alias in package `ast` pointing at an object in package `_ast`.

    Parameters:
        obj: The object (alias) to check.

    Returns:
        True or false.
    """
    if not obj.is_alias:
        return False
    try:
        return obj.target.package.name == f"_{obj.parent.package.name}"
    except (AliasResolutionError, CyclicAliasError):
        return False