0
# Documentation Objects
1
2
Individual documentation objects that represent different Python code elements. These objects provide detailed information about modules, classes, functions, variables, and external references with support for inheritance analysis, signature extraction, and cross-referencing.
3
4
## Capabilities
5
6
### Base Documentation Object
7
8
The foundational class for all documentation objects with common properties and URL generation.
9
10
```python { .api }
11
class Doc:
12
def __init__(self, name: str, module, obj, docstring: str = ''):
13
"""
14
Base class for all documentation objects.
15
16
Parameters:
17
- name: Public identifier name
18
- module: Module documentation object where this object is defined
19
- obj: Raw Python object
20
- docstring: Documentation string (auto-detected if empty)
21
"""
22
23
def url(self, relative_to=None, link_prefix='', top_ancestor=False) -> str:
24
"""
25
Canonical relative URL for this documentation object.
26
27
Parameters:
28
- relative_to: Module to compute relative URL from
29
- link_prefix: URL prefix for absolute links
30
- top_ancestor: If True, link to top ancestor in inheritance chain
31
32
Returns:
33
str: URL with page fragment
34
"""
35
36
# Properties
37
name: str # Public identifier name
38
module: 'Module' # Containing module
39
obj: Any # Raw Python object
40
docstring: str # Cleaned docstring with includes resolved
41
inherits: Optional[Union['Class', 'Function', 'Variable']] # Inherited object
42
refname: str # Fully qualified reference name
43
qualname: str # Module-relative qualified name
44
source: str # Cleaned source code
45
```
46
47
### Class Documentation
48
49
Comprehensive class documentation with inheritance analysis, member organization, and constructor parameter extraction.
50
51
```python { .api }
52
class Class(Doc):
53
def __init__(self, name: str, module: 'Module', obj, docstring=None):
54
"""
55
Class documentation object.
56
57
Parameters:
58
- name: Class name
59
- module: Containing module
60
- obj: Class object
61
- docstring: Override docstring (combines class + __init__ docs if None)
62
"""
63
64
def mro(self, only_documented=False) -> List['Class']:
65
"""
66
Method resolution order for this class.
67
68
Parameters:
69
- only_documented: If True, only include documented classes
70
71
Returns:
72
List[Class]: Ancestor classes in MRO order
73
"""
74
75
def subclasses(self) -> List['Class']:
76
"""
77
Direct subclasses visible to the Python interpreter.
78
79
Returns:
80
List[Class]: Subclasses sorted by name
81
"""
82
83
def params(self, annotate=False, link=None) -> List[str]:
84
"""
85
Formatted parameters for class constructor (__init__).
86
87
Parameters:
88
- annotate: If True, include type annotations
89
- link: Optional function to generate cross-reference links
90
91
Returns:
92
List[str]: Formatted parameter strings
93
"""
94
95
def class_variables(self, include_inherited=True, sort=True) -> List['Variable']:
96
"""
97
Class variables (not instance variables).
98
99
Parameters:
100
- include_inherited: If True, include inherited variables
101
- sort: If True, sort alphabetically
102
103
Returns:
104
List[Variable]: Class variables
105
"""
106
107
def instance_variables(self, include_inherited=True, sort=True) -> List['Variable']:
108
"""
109
Instance variables defined in __init__ as self.variable.
110
111
Parameters:
112
- include_inherited: If True, include inherited variables
113
- sort: If True, sort alphabetically
114
115
Returns:
116
List[Variable]: Instance variables
117
"""
118
119
def methods(self, include_inherited=True, sort=True) -> List['Function']:
120
"""
121
Class methods (bound methods, not static/class methods).
122
123
Parameters:
124
- include_inherited: If True, include inherited methods
125
- sort: If True, sort alphabetically
126
127
Returns:
128
List[Function]: Class methods
129
"""
130
131
def functions(self, include_inherited=True, sort=True) -> List['Function']:
132
"""
133
Static functions and class methods.
134
135
Parameters:
136
- include_inherited: If True, include inherited functions
137
- sort: If True, sort alphabetically
138
139
Returns:
140
List[Function]: Static functions and class methods
141
"""
142
143
def inherited_members(self) -> List[Tuple['Class', List[Doc]]]:
144
"""
145
All inherited members grouped by ancestor class.
146
147
Returns:
148
List[Tuple[Class, List[Doc]]]: (ancestor, members) pairs sorted by MRO
149
"""
150
151
# Properties
152
doc: Dict[str, Union['Function', 'Variable']] # Class members
153
```
154
155
### Function Documentation
156
157
Function and method documentation with signature analysis, parameter extraction, and return type annotation.
158
159
```python { .api }
160
class Function(Doc):
161
def __init__(self, name: str, module: 'Module', obj, cls=None):
162
"""
163
Function or method documentation object.
164
165
Parameters:
166
- name: Function name
167
- module: Containing module
168
- obj: Function object (must be callable)
169
- cls: Containing Class if this is a method
170
"""
171
172
def funcdef(self) -> str:
173
"""
174
Function definition keywords.
175
176
Returns:
177
str: 'def' or 'async def'
178
"""
179
180
def return_annotation(self, link=None) -> str:
181
"""
182
Formatted function return type annotation.
183
184
Parameters:
185
- link: Optional function to generate cross-reference links
186
187
Returns:
188
str: Formatted return type or empty string if none
189
"""
190
191
def params(self, annotate=False, link=None) -> List[str]:
192
"""
193
Formatted parameter list for this function.
194
195
Parameters:
196
- annotate: If True, include PEP 484 type annotations
197
- link: Optional function to generate cross-reference links
198
199
Returns:
200
List[str]: Formatted parameter strings
201
"""
202
203
# Properties
204
cls: Optional['Class'] # Containing class if method
205
is_method: bool # True if bound method (not static/classmethod)
206
```
207
208
### Variable Documentation
209
210
Documentation for module, class, and instance variables with type annotation support.
211
212
```python { .api }
213
class Variable(Doc):
214
def __init__(self, name: str, module: 'Module', docstring, obj=None,
215
cls=None, instance_var=False, kind='var'):
216
"""
217
Variable documentation object.
218
219
Parameters:
220
- name: Variable name
221
- module: Containing module
222
- docstring: Variable docstring
223
- obj: Variable object
224
- cls: Containing Class if class/instance variable
225
- instance_var: True if instance variable (vs class variable)
226
- kind: 'prop' for properties, 'var' for regular variables
227
"""
228
229
def type_annotation(self, link=None) -> str:
230
"""
231
Formatted variable type annotation.
232
233
Parameters:
234
- link: Optional function to generate cross-reference links
235
236
Returns:
237
str: Formatted type annotation or empty string if none
238
"""
239
240
# Properties
241
cls: Optional['Class'] # Containing class
242
instance_var: bool # True for instance variables
243
kind: str # 'prop' for properties, 'var' for variables
244
```
245
246
### External References
247
248
Representation of external or undocumented identifiers for cross-referencing.
249
250
```python { .api }
251
class External(Doc):
252
def __init__(self, name: str):
253
"""
254
External identifier documentation object.
255
256
Parameters:
257
- name: Fully qualified identifier name
258
"""
259
260
def url(self, *args, **kwargs) -> str:
261
"""
262
External objects return absolute URLs.
263
264
Returns:
265
str: Absolute URL in format '/{name}.ext'
266
"""
267
268
# Properties
269
docstring: str = '' # Always empty
270
module: None = None # Always None
271
name: str # Same as refname
272
```
273
274
## Usage Examples
275
276
### Working with Class Objects
277
278
```python
279
import pdoc
280
281
# Create module and find a class
282
module = pdoc.Module('mypackage')
283
cls_doc = module.find_ident('MyClass')
284
285
if isinstance(cls_doc, pdoc.Class):
286
# Get class information
287
print(f"Class: {cls_doc.name}")
288
print(f"MRO: {[c.name for c in cls_doc.mro()]}")
289
290
# Get class members
291
methods = cls_doc.methods(include_inherited=False)
292
class_vars = cls_doc.class_variables()
293
instance_vars = cls_doc.instance_variables()
294
295
# Get constructor parameters
296
params = cls_doc.params(annotate=True)
297
print(f"Constructor: {cls_doc.name}({', '.join(params)})")
298
```
299
300
### Analyzing Function Signatures
301
302
```python
303
import pdoc
304
305
module = pdoc.Module('mymodule')
306
307
for name, obj in module.doc.items():
308
if isinstance(obj, pdoc.Function):
309
# Get function signature
310
params = obj.params(annotate=True)
311
return_type = obj.return_annotation()
312
313
print(f"{obj.funcdef()} {obj.name}({', '.join(params)})")
314
if return_type:
315
print(f" -> {return_type}")
316
317
if obj.cls:
318
print(f" Method of: {obj.cls.name}")
319
if obj.is_method:
320
print(" Type: bound method")
321
```
322
323
### Variable Type Analysis
324
325
```python
326
import pdoc
327
328
module = pdoc.Module('mypackage')
329
330
# Find all variables with type annotations
331
for name, obj in module.doc.items():
332
if isinstance(obj, pdoc.Variable):
333
type_annotation = obj.type_annotation()
334
if type_annotation:
335
var_type = "instance" if obj.instance_var else "class"
336
if obj.cls:
337
print(f"{obj.cls.name}.{obj.name}: {type_annotation} ({var_type} variable)")
338
else:
339
print(f"{obj.name}: {type_annotation} (module variable)")
340
```
341
342
### Inheritance Analysis
343
344
```python
345
import pdoc
346
347
module = pdoc.Module('mypackage')
348
pdoc.link_inheritance() # Required for inheritance analysis
349
350
for name, obj in module.doc.items():
351
if isinstance(obj, pdoc.Class):
352
# Show inheritance chain
353
print(f"Class {obj.name}:")
354
for ancestor in obj.mro():
355
print(f" <- {ancestor.name}")
356
357
# Show inherited members
358
for ancestor, members in obj.inherited_members():
359
print(f" From {ancestor.name}:")
360
for member in members:
361
print(f" {member.name} ({type(member).__name__})")
362
```