Auto-generate API documentation for Python projects with support for multiple docstring formats, type annotations, and customizable templates.
—
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.
The foundational class for all documentation objects with common properties and URL generation.
class Doc:
def __init__(self, name: str, module, obj, docstring: str = ''):
"""
Base class for all documentation objects.
Parameters:
- name: Public identifier name
- module: Module documentation object where this object is defined
- obj: Raw Python object
- docstring: Documentation string (auto-detected if empty)
"""
def url(self, relative_to=None, link_prefix='', top_ancestor=False) -> str:
"""
Canonical relative URL for this documentation object.
Parameters:
- relative_to: Module to compute relative URL from
- link_prefix: URL prefix for absolute links
- top_ancestor: If True, link to top ancestor in inheritance chain
Returns:
str: URL with page fragment
"""
# Properties
name: str # Public identifier name
module: 'Module' # Containing module
obj: Any # Raw Python object
docstring: str # Cleaned docstring with includes resolved
inherits: Optional[Union['Class', 'Function', 'Variable']] # Inherited object
refname: str # Fully qualified reference name
qualname: str # Module-relative qualified name
source: str # Cleaned source codeComprehensive class documentation with inheritance analysis, member organization, and constructor parameter extraction.
class Class(Doc):
def __init__(self, name: str, module: 'Module', obj, docstring=None):
"""
Class documentation object.
Parameters:
- name: Class name
- module: Containing module
- obj: Class object
- docstring: Override docstring (combines class + __init__ docs if None)
"""
def mro(self, only_documented=False) -> List['Class']:
"""
Method resolution order for this class.
Parameters:
- only_documented: If True, only include documented classes
Returns:
List[Class]: Ancestor classes in MRO order
"""
def subclasses(self) -> List['Class']:
"""
Direct subclasses visible to the Python interpreter.
Returns:
List[Class]: Subclasses sorted by name
"""
def params(self, annotate=False, link=None) -> List[str]:
"""
Formatted parameters for class constructor (__init__).
Parameters:
- annotate: If True, include type annotations
- link: Optional function to generate cross-reference links
Returns:
List[str]: Formatted parameter strings
"""
def class_variables(self, include_inherited=True, sort=True) -> List['Variable']:
"""
Class variables (not instance variables).
Parameters:
- include_inherited: If True, include inherited variables
- sort: If True, sort alphabetically
Returns:
List[Variable]: Class variables
"""
def instance_variables(self, include_inherited=True, sort=True) -> List['Variable']:
"""
Instance variables defined in __init__ as self.variable.
Parameters:
- include_inherited: If True, include inherited variables
- sort: If True, sort alphabetically
Returns:
List[Variable]: Instance variables
"""
def methods(self, include_inherited=True, sort=True) -> List['Function']:
"""
Class methods (bound methods, not static/class methods).
Parameters:
- include_inherited: If True, include inherited methods
- sort: If True, sort alphabetically
Returns:
List[Function]: Class methods
"""
def functions(self, include_inherited=True, sort=True) -> List['Function']:
"""
Static functions and class methods.
Parameters:
- include_inherited: If True, include inherited functions
- sort: If True, sort alphabetically
Returns:
List[Function]: Static functions and class methods
"""
def inherited_members(self) -> List[Tuple['Class', List[Doc]]]:
"""
All inherited members grouped by ancestor class.
Returns:
List[Tuple[Class, List[Doc]]]: (ancestor, members) pairs sorted by MRO
"""
# Properties
doc: Dict[str, Union['Function', 'Variable']] # Class membersFunction and method documentation with signature analysis, parameter extraction, and return type annotation.
class Function(Doc):
def __init__(self, name: str, module: 'Module', obj, cls=None):
"""
Function or method documentation object.
Parameters:
- name: Function name
- module: Containing module
- obj: Function object (must be callable)
- cls: Containing Class if this is a method
"""
def funcdef(self) -> str:
"""
Function definition keywords.
Returns:
str: 'def' or 'async def'
"""
def return_annotation(self, link=None) -> str:
"""
Formatted function return type annotation.
Parameters:
- link: Optional function to generate cross-reference links
Returns:
str: Formatted return type or empty string if none
"""
def params(self, annotate=False, link=None) -> List[str]:
"""
Formatted parameter list for this function.
Parameters:
- annotate: If True, include PEP 484 type annotations
- link: Optional function to generate cross-reference links
Returns:
List[str]: Formatted parameter strings
"""
# Properties
cls: Optional['Class'] # Containing class if method
is_method: bool # True if bound method (not static/classmethod)Documentation for module, class, and instance variables with type annotation support.
class Variable(Doc):
def __init__(self, name: str, module: 'Module', docstring, obj=None,
cls=None, instance_var=False, kind='var'):
"""
Variable documentation object.
Parameters:
- name: Variable name
- module: Containing module
- docstring: Variable docstring
- obj: Variable object
- cls: Containing Class if class/instance variable
- instance_var: True if instance variable (vs class variable)
- kind: 'prop' for properties, 'var' for regular variables
"""
def type_annotation(self, link=None) -> str:
"""
Formatted variable type annotation.
Parameters:
- link: Optional function to generate cross-reference links
Returns:
str: Formatted type annotation or empty string if none
"""
# Properties
cls: Optional['Class'] # Containing class
instance_var: bool # True for instance variables
kind: str # 'prop' for properties, 'var' for variablesRepresentation of external or undocumented identifiers for cross-referencing.
class External(Doc):
def __init__(self, name: str):
"""
External identifier documentation object.
Parameters:
- name: Fully qualified identifier name
"""
def url(self, *args, **kwargs) -> str:
"""
External objects return absolute URLs.
Returns:
str: Absolute URL in format '/{name}.ext'
"""
# Properties
docstring: str = '' # Always empty
module: None = None # Always None
name: str # Same as refnameimport pdoc
# Create module and find a class
module = pdoc.Module('mypackage')
cls_doc = module.find_ident('MyClass')
if isinstance(cls_doc, pdoc.Class):
# Get class information
print(f"Class: {cls_doc.name}")
print(f"MRO: {[c.name for c in cls_doc.mro()]}")
# Get class members
methods = cls_doc.methods(include_inherited=False)
class_vars = cls_doc.class_variables()
instance_vars = cls_doc.instance_variables()
# Get constructor parameters
params = cls_doc.params(annotate=True)
print(f"Constructor: {cls_doc.name}({', '.join(params)})")import pdoc
module = pdoc.Module('mymodule')
for name, obj in module.doc.items():
if isinstance(obj, pdoc.Function):
# Get function signature
params = obj.params(annotate=True)
return_type = obj.return_annotation()
print(f"{obj.funcdef()} {obj.name}({', '.join(params)})")
if return_type:
print(f" -> {return_type}")
if obj.cls:
print(f" Method of: {obj.cls.name}")
if obj.is_method:
print(" Type: bound method")import pdoc
module = pdoc.Module('mypackage')
# Find all variables with type annotations
for name, obj in module.doc.items():
if isinstance(obj, pdoc.Variable):
type_annotation = obj.type_annotation()
if type_annotation:
var_type = "instance" if obj.instance_var else "class"
if obj.cls:
print(f"{obj.cls.name}.{obj.name}: {type_annotation} ({var_type} variable)")
else:
print(f"{obj.name}: {type_annotation} (module variable)")import pdoc
module = pdoc.Module('mypackage')
pdoc.link_inheritance() # Required for inheritance analysis
for name, obj in module.doc.items():
if isinstance(obj, pdoc.Class):
# Show inheritance chain
print(f"Class {obj.name}:")
for ancestor in obj.mro():
print(f" <- {ancestor.name}")
# Show inherited members
for ancestor, members in obj.inherited_members():
print(f" From {ancestor.name}:")
for member in members:
print(f" {member.name} ({type(member).__name__})")Install with Tessl CLI
npx tessl i tessl/pypi-pdoc3