Skip to content

serializer

This module defines function to serialize objects.

These functions simply take objects as parameters and return dictionaries that can be dumped by json.dumps.

RE_FORWARD_REF = re.compile("_?ForwardRef\\('([^']+)'\\)") module-attribute ¤

Regular expression to match forward-reference annotations of the form _ForwardRef('T').

RE_OPTIONAL = re.compile('Union\\[(.+), NoneType\\]') module-attribute ¤

Regular expression to match optional annotations of the form Union[T, NoneType].

annotation_to_string(annotation) ¤

Return an annotation as a string.

Parameters:

Name Type Description Default
annotation Any

The annotation to return as a string.

required

Returns:

Type Description
str

The annotation as a string.

Source code in src/pytkdocs/serializer.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def annotation_to_string(annotation: Any) -> str:
    """Return an annotation as a string.

    Arguments:
        annotation: The annotation to return as a string.

    Returns:
        The annotation as a string.
    """
    if annotation is inspect.Signature.empty:
        return ""

    if inspect.isclass(annotation) and not isinstance(annotation, GenericMeta):
        string = annotation.__name__
    else:
        string = str(annotation).replace("typing.", "")

    string = RE_FORWARD_REF.sub(lambda match: match.group(1), string)
    return RE_OPTIONAL.sub(rebuild_optional, string)

rebuild_optional(match) ¤

Rebuild Union[T, None] as Optional[T].

Parameters:

Name Type Description Default
match Match

The match object when matching against a regular expression (by the parent caller).

required

Returns:

Type Description
str

The rebuilt type string.

Source code in src/pytkdocs/serializer.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def rebuild_optional(match: Match) -> str:
    """Rebuild `Union[T, None]` as `Optional[T]`.

    Arguments:
        match: The match object when matching against a regular expression (by the parent caller).

    Returns:
        The rebuilt type string.
    """
    group = match.group(1)
    brackets_level = 0
    for char in group:
        if char == "," and brackets_level == 0:
            return f"Union[{group}]"
        if char == "[":
            brackets_level += 1
        elif char == "]":
            brackets_level -= 1
    return f"Optional[{group}]"

serialize_annotated_object(obj) ¤

Serialize an instance of AnnotatedObject.

Parameters:

Name Type Description Default
obj AnnotatedObject

The object to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
71
72
73
74
75
76
77
78
79
80
def serialize_annotated_object(obj: AnnotatedObject) -> dict:
    """Serialize an instance of [`AnnotatedObject`][pytkdocs.parsers.docstrings.base.AnnotatedObject].

    Arguments:
        obj: The object to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    return {"description": obj.description, "annotation": annotation_to_string(obj.annotation)}

serialize_attribute(attribute) ¤

Serialize an instance of Attribute.

Parameters:

Name Type Description Default
attribute Attribute

The attribute to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def serialize_attribute(attribute: Attribute) -> dict:
    """Serialize an instance of [`Attribute`][pytkdocs.parsers.docstrings.base.Attribute].

    Arguments:
        attribute: The attribute to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    return {
        "name": attribute.name,
        "description": attribute.description,
        "annotation": annotation_to_string(attribute.annotation),
    }

serialize_docstring_section(section) ¤

Serialize an instance of inspect.Signature.

Parameters:

Name Type Description Default
section Section

The section to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def serialize_docstring_section(section: Section) -> dict:
    """Serialize an instance of `inspect.Signature`.

    Arguments:
        section: The section to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    serialized = {"type": section.type}
    if section.type == section.Type.MARKDOWN:
        serialized.update({"value": section.value})
    elif section.type == section.Type.RETURN or section.type == section.Type.YIELD:  # noqa: PLR1714
        serialized.update({"value": serialize_annotated_object(section.value)})  # type: ignore[dict-item]
    elif section.type == section.Type.EXCEPTIONS:
        serialized.update({"value": [serialize_annotated_object(exc) for exc in section.value]})  # type: ignore[dict-item]
    elif section.type == section.Type.PARAMETERS or section.type == section.Type.KEYWORD_ARGS:  # noqa: PLR1714
        serialized.update({"value": [serialize_parameter(param) for param in section.value]})  # type: ignore[dict-item]
    elif section.type == section.Type.ATTRIBUTES:
        serialized.update({"value": [serialize_attribute(attr) for attr in section.value]})  # type: ignore[dict-item]
    elif section.type == section.Type.EXAMPLES:
        serialized.update({"value": section.value})
    return serialized

serialize_object(obj) ¤

Serialize an instance of a subclass of Object.

Parameters:

Name Type Description Default
obj Object

The object to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def serialize_object(obj: Object) -> dict:
    """Serialize an instance of a subclass of [`Object`][pytkdocs.objects.Object].

    Arguments:
        obj: The object to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    serialized = {
        "name": obj.name,
        "path": obj.path,
        "category": obj.category,
        "file_path": obj.file_path,
        "relative_file_path": obj.relative_file_path,
        "properties": sorted(set(obj.properties + obj.name_properties)),
        "parent_path": obj.parent_path,
        "has_contents": obj.has_contents(),
        "docstring": obj.docstring,
        "docstring_sections": [serialize_docstring_section(sec) for sec in obj.docstring_sections],
        "source": serialize_source(obj.source),
        "children": {child.path: serialize_object(child) for child in obj.children},
        "attributes": [attr.path for attr in obj.attributes],
        "methods": [meth.path for meth in obj.methods],
        "functions": [func.path for func in obj.functions],
        "modules": [mod.path for mod in obj.modules],
        "classes": [clas.path for clas in obj.classes],
    }
    if hasattr(obj, "type"):
        serialized["type"] = annotation_to_string(obj.type)
    if hasattr(obj, "signature"):
        serialized["signature"] = serialize_signature(obj.signature)
    if hasattr(obj, "bases"):
        serialized["bases"] = obj.bases
    return serialized

serialize_parameter(parameter) ¤

Serialize an instance of Parameter.

Parameters:

Name Type Description Default
parameter Parameter

The parameter to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def serialize_parameter(parameter: Parameter) -> dict:
    """Serialize an instance of [`Parameter`][pytkdocs.parsers.docstrings.base.Parameter].

    Arguments:
        parameter: The parameter to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    serialized = serialize_annotated_object(parameter)
    serialized.update(
        {
            "name": parameter.name,
            "kind": str(parameter.kind),
            "default": parameter.default_string,
            "is_optional": parameter.is_optional,
            "is_required": parameter.is_required,
            "is_args": parameter.is_args,
            "is_kwargs": parameter.is_kwargs,
        },
    )
    return serialized

serialize_signature(signature) ¤

Serialize an instance of inspect.Signature.

Parameters:

Name Type Description Default
signature Signature

The signature to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def serialize_signature(signature: inspect.Signature) -> dict:
    """Serialize an instance of `inspect.Signature`.

    Arguments:
        signature: The signature to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    if signature is None:
        return {}
    serialized: dict = {
        "parameters": [serialize_signature_parameter(value) for name, value in signature.parameters.items()],
    }
    if signature.return_annotation is not inspect.Signature.empty:
        serialized["return_annotation"] = annotation_to_string(signature.return_annotation)
    return serialized

serialize_signature_parameter(parameter) ¤

Serialize an instance of inspect.Parameter.

Parameters:

Name Type Description Default
parameter Parameter

The parameter to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def serialize_signature_parameter(parameter: inspect.Parameter) -> dict:
    """Serialize an instance of `inspect.Parameter`.

    Arguments:
        parameter: The parameter to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    serialized = {"kind": str(parameter.kind), "name": parameter.name}
    if parameter.annotation is not parameter.empty:
        serialized["annotation"] = annotation_to_string(parameter.annotation)
    if parameter.default is not parameter.empty:
        serialized["default"] = repr(parameter.default)
    return serialized

serialize_source(source) ¤

Serialize an instance of Source.

Parameters:

Name Type Description Default
source Optional[Source]

The source to serialize.

required

Returns:

Type Description
dict

A JSON-serializable dictionary.

Source code in src/pytkdocs/serializer.py
184
185
186
187
188
189
190
191
192
193
194
195
def serialize_source(source: Optional[Source]) -> dict:
    """Serialize an instance of [`Source`][pytkdocs.objects.Source].

    Arguments:
        source: The source to serialize.

    Returns:
        A JSON-serializable dictionary.
    """
    if source:
        return {"code": source.code, "line_start": source.line_start}
    return {}