### Async Function Example
Source: https://pdoc.dev/docs/demo_long.html
This is an example of an async function. It is documented with a docstring that includes list items.
```python
async def i_am_async(self) -> int:
"""
This is an example of an async function.
- Knock, knock
- An async function
- Who's there?
"""
raise NotImplementedError
```
--------------------------------
### Dataclass Example
Source: https://pdoc.dev/docs/demo_long.html
This is an example of a dataclass. Individual properties can be documented with docstrings.
```python
@dataclass
class DataDemo:
"""
This is an example for a dataclass.
As usual, you can link to individual properties: `DataDemo.a`.
"""
a: int
"""Again, we can document individual properties with docstrings."""
a2: Sequence[str]
# This property has a type annotation but is not documented.
a3 = "a3"
# This property has a default value but is not documented.
a4: str = "a4"
# This property has a type annotation and a default value but is not documented.
b: bool = field(repr=False, default=True)
"""This property is assigned to `dataclasses.field()`, which works just as well."""
```
--------------------------------
### Print Hello World
Source: https://pdoc.dev/docs/demo_long.html
A basic example of printing a string to the console. This is a simple demonstration of code execution within the documentation.
```python
print("hello world")
```
--------------------------------
### Enum Example
Source: https://pdoc.dev/docs/demo_long.html
This is an example of an Enum. Individual members can be documented with docstrings.
```python
class EnumDemo(enum.Enum):
"""
This is an example of an Enum.
As usual, you can link to individual properties: `GREEN`.
"""
RED = 1
"""I am the red."""
GREEN = 2
"""I am green."""
BLUE = enum.auto()
```
--------------------------------
### i_am_async
Source: https://pdoc.dev/docs/demo_long.html
This is an example of an async function. It is documented with a docstring that includes markdown formatting.
```APIDOC
## async def i_am_async()
### Description
This is an example of an async function.
- Knock, knock
- An async function
- Who's there?
### Method
ASYNC FUNCTION
### Endpoint
N/A
### Parameters
None
### Request Example
None
### Response
#### Success Response (Not Specified)
None
#### Response Example
None
```
--------------------------------
### Bar.Baz.fib
Source: https://pdoc.dev/docs/demo_long.html
A decorated function example within the Baz class, demonstrating how decorators are included in documentation.
```APIDOC
## Bar.Baz.fib
### Description
A decorated function example within the Baz class, demonstrating how decorators are included in documentation. This is often useful when documenting web APIs, for example.
### Method
`fib(n)`
### Parameters
- **n**: An integer input for the Fibonacci calculation.
### Response
- **int**: The nth Fibonacci number.
```
--------------------------------
### fib
Source: https://pdoc.dev/docs/demo_long.html
This is an example of a decorated function. Decorators are included in the documentation as well. This is often useful when documenting web APIs, for example.
```APIDOC
## @cache
def fib(n)
### Description
This is an example of decorated function. Decorators are included in the documentation as well.
This is often useful when documenting web APIs, for example.
### Method
FUNCTION
### Endpoint
N/A
### Parameters
* **n** (any) - Description: None
### Request Example
None
### Response
#### Success Response (Not Specified)
None
#### Response Example
None
```
--------------------------------
### get
Source: https://pdoc.dev/docs/pdoc/doc.html
Returns the documentation object for a particular identifier, or `None` if the identifier cannot be found.
```APIDOC
## get
### Description
Returns the documentation object for a particular identifier, or `None` if the identifier cannot be found.
### Method
`@cache def get(self, identifier: str) -> Doc | None:`
### Parameters
- **identifier** (str) - Required - The identifier string for the documentation object to retrieve.
### Returns
`Doc | None` - The documentation object if found, otherwise `None`.
```
--------------------------------
### Python ClassMethod Property Example
Source: https://pdoc.dev/docs/demo_long.html
Illustrates the syntax for a class method decorated as a property. This is a less common pattern.
```python
"""This is what a @classmethod @property looks like."""
return 24
```
--------------------------------
### Admonitions Example
Source: https://pdoc.dev/docs/demo_long.html
This docstring demonstrates the use of reStructuredText admonitions and GitHub-style Markdown alerts.
```python
def admonitions():
"""
pdoc also supports basic reStructuredText admonitions or GitHub's Markdown alerts:
```
> [!NOTE/WARNING/DANGER]
> Useful information that users should know, even when skimming content.
.. note/warning/danger:: Optional title
Body text
```
> [!NOTE]
> Hi there!
.. warning:: Be Careful!
This warning has both a title *and* content.
.. danger::
Danger ahead.
"""
```
--------------------------------
### Get Base Classes
Source: https://pdoc.dev/docs/pdoc/doc.html
Returns a list of all immediate parent classes. Each parent is a tuple containing its module name, qualified name, and display text.
```python
bases = []
for x in _safe_getattr(self.obj, "__orig_bases__", self.obj.__bases__):
if x is object:
continue
o = get_origin(x)
if o:
bases.append((o.__module__, o.__qualname__, str(x)))
elif x.__module__ == self.modulename:
bases.append((x.__module__, x.__qualname__, x.__qualname__))
else:
bases.append(
(x.__module__, x.__qualname__, f"{x.__module__}.{x.__qualname__}")
)
return bases
```
--------------------------------
### Basic Class Definition
Source: https://pdoc.dev/docs/demo_long.html
Defines a simple class `Foo` with a docstring. It includes examples of referencing other elements within the docstring.
```python
class Foo:
"""
`Foo` is a basic class without any parent classes (except for the implicit `object` class).
You will see in the definition of `Bar` that docstrings are inherited by default.
Functions in the current scope can be referenced without prefix: `a_regular_function()`.
"""
an_attribute: str | list["int"]
"""A regular attribute with type annotations"""
a_class_attribute: ClassVar[str] = "lots of foo!"
"""An attribute with a ClassVar annotation."""
def __init__(self) -> None:
"""
The constructor is currently always listed first as this feels most natural."""
self.a_constructor_only_attribute: int = 42
"""This attribute is defined in the constructor only, but still picked up by pdoc's AST traversal."""
self.undocumented_constructor_attribute = 42
a_complex_function("a", "Foo", keyword_only_argument=1)
def a_regular_function(self) -> "Foo":
"""This is a regular method, returning the object itself."""
return self
@property
def a_property(self) -> str:
"""This is a `@property` attribute. pdoc will display it as a variable."""
return "true foo"
@cached_property
def a_cached_property(self) -> str:
"""This is a `@functools.cached_property` attribute. pdoc will display it as a variable as well."""
return "true foo"
@cache
def a_cached_function(self) -> str:
"""This is method with `@cache` decoration."""
return "true foo"
@classmethod
def a_class_method(cls) -> int:
"""This is what a `@classmethod` looks like."""
return 24
@classmethod # type: ignore
@property
def a_class_property(cls) -> int:
"""This is what a `@classmethod @property` looks like."""
return 24
@staticmethod
def a_static_method():
"""This is what a `@staticmethod` looks like."""
print("Hello World")
```
--------------------------------
### Python Static Method Example
Source: https://pdoc.dev/docs/demo_long.html
Shows the definition of a static method within a Python class. Static methods do not receive implicit first arguments.
```python
@staticmethod
def a_static_method():
"""This is what a @staticmethod looks like."""
print("Hello World")
```
--------------------------------
### Docstring inheritance example
Source: https://pdoc.dev/docs/pdoc.html
Demonstrates how pdoc automatically attaches docstrings from parent classes to child classes if the child class's docstring is empty. This avoids redundant documentation.
```python
class Dog:
def bark(self, loud: bool) -> None:
"""
Make the dog bark. If `loud` is True,
use full volume. Not supported by all breeds.
"""
class GoldenRetriever(Dog):
def bark(self, loud: bool) -> None:
print("Woof Woof")
```
--------------------------------
### Docstring Inheritance Example
Source: https://pdoc.dev/docs/pdoc.html
Demonstrates how pdoc can automatically attach a docstring from a parent class method to a child class method if the child method's docstring is empty. This avoids redundant documentation.
```python
class Dog:
def bark(self, loud: bool) -> None:
"""
Make the dog bark. If `loud` is True,
use full volume. Not supported by all breeds.
"""
class GoldenRetriever(Dog):
def bark(self, loud: bool) -> None:
print("Woof Woof")
```
--------------------------------
### View pdoc Help and Options
Source: https://pdoc.dev/docs/pdoc.html
Run `pdoc --help` to display a list of all available command-line flags and options for customizing pdoc's behavior and output.
```bash
pdoc --help
```
--------------------------------
### Get Class Decorators
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves a list of all decorators applied to a class. Each decorator is represented as a string starting with '@'.
```python
decorators = []
for t in doc_ast.parse(self.obj).decorator_list:
decorators.append(f"@{doc_ast.unparse(t)}")
return decorators
```
--------------------------------
### Get Source Lines of Python Object
Source: https://pdoc.dev/docs/pdoc/doc.html
Returns a tuple of `(start, end)` line numbers for a Python object within its source file. Returns `None` if the source file cannot be found.
```python
lines, start = inspect.getsourcelines(self.obj) # type: ignore
return start, start + len(lines) - 1
```
--------------------------------
### Initialize Module Documentation
Source: https://pdoc.dev/docs/pdoc/doc.html
Creates a documentation object for a Python module using its name.
```python
def __init__(
self,
module: types.ModuleType,
):
"""
Creates a documentation object given the actual
Python module object.
"""
super().__init__(module.__name__, "", module, (module.__name__, ""))
```
--------------------------------
### Get Submodules with Filtering
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves a list of direct submodules. It respects the `__all__` attribute for explicit inclusion or filters out modules starting with an underscore if `__all__` is not present. Handles potential import errors gracefully.
```python
@cached_property
def submodules(self) -> list[Module]:
"""A list of all (direct) submodules."""
include: Callable[[str], bool]
mod_all = _safe_getattr(self.obj, "__all__", False)
if mod_all is not False:
mod_all_pos = {name: i for i, name in enumerate(mod_all)}
include = mod_all_pos.__contains__
else:
def include(name: str) -> bool:
# optimization: we don't even try to load modules starting with an underscore as they would not be
# visible by default. The downside of this is that someone who overrides `is_public` will miss those
# entries, the upsides are 1) better performance and 2) less warnings because of import failures
# (think of OS-specific modules, e.g. _linux.py failing to import on Windows).
return not name.startswith("_")
submodules: list[Module] = []
for mod_name, mod in extract.iter_modules2(self.obj).items():
if not include(mod_name):
continue
try:
module = Module.from_name(mod.name)
except RuntimeError:
warnings.warn(f"Couldn't import {mod.name}:\n{traceback.format_exc()}")
continue
submodules.append(module)
if mod_all:
submodules = sorted(submodules, key=lambda m: mod_all_pos[m.name])
return submodules
```
--------------------------------
### Dog Constructor
Source: https://pdoc.dev/docs/demo-standalone.html
Initializes a new Dog instance.
```APIDOC
## `__init__` Dog(name: str)
### Description
Make a Dog without any friends (yet).
### Parameters
- **name** (str) - Required - The name of our dog.
```
--------------------------------
### Dog Constructor
Source: https://pdoc.dev/docs/dark-mode
Initializes a new Dog instance.
```APIDOC
## `__init__` - Dog Constructor
### Description
Make a Dog without any friends (yet).
### Parameters
- **name** (str) - Required - The name of our dog.
```
--------------------------------
### Module.__init__
Source: https://pdoc.dev/docs/pdoc/doc.html
Creates a documentation object given the actual Python module object.
```APIDOC
## Module.__init__
### Description
Creates a documentation object given the actual Python module object.
### Method
__init__
### Parameters
- **module** (types.ModuleType) - The Python module object to document.
```
--------------------------------
### Initialize DocServer
Source: https://pdoc.dev/docs/pdoc/web.html
Initializes the DocServer, which is pdoc's live-reloading web server. It takes an address, a list of module specifications, and optional keyword arguments.
```python
class DocServer(http.server.HTTPServer):
"""pdoc's live-reloading web server"""
all_modules: AllModules
def __init__(self, addr: tuple[str, int], specs: list[str], **kwargs):
super().__init__(addr, DocHandler, **kwargs) # type: ignore
module_names = extract.walk_specs(specs)
self.all_modules = AllModules(module_names)
```
--------------------------------
### Display pdoc Help Information
Source: https://pdoc.dev/docs/pdoc.html
Command to display all available command-line options and rendering configurations for pdoc.
```shell
pdoc --help
```
--------------------------------
### Handle GET Request in pdoc.web
Source: https://pdoc.dev/docs/pdoc/web.html
Handles HTTP GET requests by writing the encoded response to the client. Includes basic error handling for connection issues.
```python
def do_GET(self):
try:
self.wfile.write(self.handle_request().encode())
except ConnectionError: # pragma: no cover
pass
```
--------------------------------
### Render Module Documentation
Source: https://pdoc.dev/docs/pdoc.html
Renders documentation for a list of modules. If `output_directory` is None, it returns the HTML for the first module. Otherwise, it writes HTML files for all modules and submodules to the specified directory, including an index and search index.
```python
def render_all(modules: list[str], output_directory: Path | None = None):
"""Render the documentation for a list of modules.
Args:
modules: A list of module names to render.
output_directory: The directory to write the rendered documentation to. If None, the HTML for the first module is returned.
Returns:
The rendered HTML for the first module if output_directory is None, otherwise None.
"""
all_modules: dict[str, doc.Module] = {}
for module_name in extract.walk_specs(modules):
all_modules[module_name] = doc.Module.from_name(module_name)
for module in all_modules.values():
out = render.html_module(module, all_modules)
if not output_directory:
return out
else:
outfile = output_directory / f"{module.fullname.replace('.', '/')}.html"
outfile.parent.mkdir(parents=True, exist_ok=True)
outfile.write_bytes(out.encode())
assert output_directory
index = render.html_index(all_modules)
if index:
(output_directory / "index.html").write_bytes(index.encode())
search = render.search_index(all_modules)
if search:
(output_directory / "search.js").write_bytes(search.encode())
return None
```
--------------------------------
### Get Module Functions
Source: https://pdoc.dev/docs/pdoc/doc.html
Returns a list of all module-level functions that are documented.
```python
@cached_property
def functions(self) -> list[Function]:
"""
A list of all documented module level functions.
"""
return [x for x in self.members.values() if isinstance(x, Function)]
```
--------------------------------
### pdoc Live-Reloading Web Server Initialization
Source: https://pdoc.dev/docs/pdoc/web.html
Initializes and runs the web server for pdoc. It takes an address, a list of module specifications, and optional keyword arguments. The server is configured with the custom DocHandler to process incoming requests and loads all specified modules into an AllModules instance.
```python
class DocServer(http.server.HTTPServer):
"""pdoc's live-reloading web server"""
all_modules: AllModules
def __init__(self, addr: tuple[str, int], specs: list[str], **kwargs):
super().__init__(addr, DocHandler, **kwargs) # type: ignore
module_names = extract.walk_specs(specs)
self.all_modules = AllModules(module_names)
@cache
def render_search_index(self) -> str:
"""Render the search index. For performance reasons this is always cached."""
```
--------------------------------
### Get Module Classes
Source: https://pdoc.dev/docs/pdoc/doc.html
Returns a list of all module-level classes that are documented.
```python
@cached_property
def classes(self) -> list[Class]:
"""
A list of all documented module level classes.
"""
return [x for x in self.members.values() if isinstance(x, Class)]
```
--------------------------------
### Render Module Documentation with pdoc
Source: https://pdoc.dev/docs/pdoc.html
Use this function to render documentation for specified modules. If `output_directory` is not provided, it returns the HTML for the first module. Otherwise, it writes HTML files for all modules and an index to the specified directory.
```python
from __future__ import annotations
__docformat__ = "markdown" # explicitly disable rST processing in the examples above.
__version__ = "16.0.0" # this is read from setup.py
from pathlib import Path
from typing import overload
from pdoc import doc
from pdoc import extract
from pdoc import render
@overload
def pdoc(
*modules: Path | str,
output_directory: None = None,
) -> str:
pass
@overload
def pdoc(
*modules: Path | str,
output_directory: Path,
) -> None:
pass
def pdoc(
*modules: Path | str,
output_directory: Path | None = None,
) -> str | None:
"""
Render the documentation for a list of modules.
- If `output_directory` is `None`, returns the rendered documentation
for the first module in the list.
- If `output_directory` is set, recursively writes the rendered output
for all specified modules and their submodules to the target destination.
Rendering options can be configured by calling `pdoc.render.configure` in advance.
"""
all_modules: dict[str, doc.Module] = {}
for module_name in extract.walk_specs(modules):
all_modules[module_name] = doc.Module.from_name(module_name)
for module in all_modules.values():
out = render.html_module(module, all_modules)
if not output_directory:
return out
else:
outfile = output_directory / f"{module.fullname.replace('.', '/')}.html"
outfile.parent.mkdir(parents=True, exist_ok=True)
outfile.write_bytes(out.encode())
assert output_directory
index = render.html_index(all_modules)
if index:
(output_directory / "index.html").write_bytes(index.encode())
search = render.search_index(all_modules)
if search:
(output_directory / "search.js").write_bytes(search.encode())
return None
```
--------------------------------
### Get Module Variables
Source: https://pdoc.dev/docs/pdoc/doc.html
Returns a list of all module-level variables that are documented.
```python
@cached_property
def variables(self) -> list[Variable]:
"""
A list of all documented module level variables.
"""
return [x for x in self.members.values() if isinstance(x, Variable)]
```
--------------------------------
### a_simple_function
Source: https://pdoc.dev/docs/demo_long.html
This is a basic module-level function. For a more complex example, take a look at `a_complex_function`!
```APIDOC
## def a_simple_function(a: str) -> str
### Description
This is a basic module-level function.
For a more complex example, take a look at `a_complex_function`!
### Method
FUNCTION
### Endpoint
N/A
### Parameters
* **a** (str) - Description: None
### Request Example
None
### Response
#### Success Response (Not Specified)
None
#### Response Example
None
```
--------------------------------
### Initialize Pet Object
Source: https://pdoc.dev/docs/mermaid
Constructor for the Pet class, initializing the pet with a name and an empty list of friends.
```python
def __init__(self, name: str):
"""Make a Pet without any friends (yet)."""
self.name = name
self.friends = []
```
--------------------------------
### Initialize Dog Object in Python
Source: https://pdoc.dev/docs/dark-mode/demo.html
Shows the constructor for the 'Dog' class, initializing a new dog instance with a name and an empty list of friends. This is used to create new dog objects.
```python
13 def __init__(self, name: str):
14 """Make a Dog without any friends (yet)."""
15 self.name = name
16 self.friends = []
```
--------------------------------
### Define Class with Multiple Inheritance
Source: https://pdoc.dev/docs/demo_long.html
An example of a class that inherits from multiple parent classes.
```python
class DoubleInherit(Foo, Bar.Baz, abc.ABC):
"""This is an example of a class that inherits from multiple parent classes."""
```
--------------------------------
### Dog Constructor (__init__)
Source: https://pdoc.dev/docs/demo-standalone.html
This snippet shows the constructor for the Dog class, which initializes a new Dog instance with a name and an empty list of friends. It's used to create Dog objects.
```python
def __init__(self, name: str):
"""Make a Dog without any friends (yet)."""
self.name = name
self.friends = []
```
--------------------------------
### DocServer
Source: https://pdoc.dev/docs/pdoc/web.html
pdoc's live-reloading web server. It serves documentation and handles module loading.
```APIDOC
## Class: DocServer
### Description
pdoc's live-reloading web server.
### Methods
#### `__init__(self, addr: tuple[str, int], specs: list[str], **kwargs)`
Constructor for the DocServer. Initializes the server with address, module specifications, and other keyword arguments.
#### `@cache
def render_search_index(self) -> str`
Render the search index. For performance reasons this is always cached. It handles potential import errors for modules.
```
--------------------------------
### Extended Dataclass Example
Source: https://pdoc.dev/docs/demo_long.html
This dataclass extends another dataclass and adds a new attribute with a docstring.
```python
@dataclass
class DataDemoExtended(DataDemo):
c: str = "42"
"""A new attribute."""
```
--------------------------------
### Get Class Methods
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves all documented methods decorated with `@classmethod`. These methods operate on the class itself.
```python
return [
x
for x in self.members.values()
if isinstance(x, Function) and x.is_classmethod
]
```
--------------------------------
### Dog Constructor
Source: https://pdoc.dev/docs/demo.html
The `__init__` method for the `Dog` class. It initializes a new Dog instance with a name and an empty list of friends.
```python
13 def __init__(self, name: str):
14 """Make a Dog without any friends (yet)."""
15 self.name = name
16 self.friends = []
```
--------------------------------
### Initialize Function Documentation Object
Source: https://pdoc.dev/docs/pdoc/doc.html
Initializes a documentation object for a function, handling various callable types like `classmethod`, `staticmethod`, and `singledispatchmethod` by unwrapping them to their base function.
```python
unwrapped: types.FunctionType
if isinstance(func, (classmethod, staticmethod)):
unwrapped = func.__func__ # type: ignore
elif isinstance(func, singledispatchmethod):
unwrapped = func.func # type: ignore
elif hasattr(func, "__wrapped__"):
unwrapped = func.__wrapped__
else:
unwrapped = func
super().__init__(modulename, qualname, unwrapped, taken_from)
self.wrapped = func # type: ignore
```
--------------------------------
### Define Async Method i_am_async
Source: https://pdoc.dev/docs/demo_long.html
An example of an asynchronous function. It is type-hinted to return an integer and raises a NotImplementedError.
```python
async def i_am_async(self) -> int:
"""
This is an example of an async function.
- Knock, knock
- An async function
- Who's there?
"""
raise NotImplementedError
```
--------------------------------
### Generate Documentation with pdoc CLI
Source: https://pdoc.dev/docs/pdoc.html
Invoke pdoc from the command line to generate documentation for a Python module or directory. The generated documentation will open in your default web browser.
```bash
pdoc ./demo.py # or: pdoc my_module_name
```
--------------------------------
### Get Static Methods
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves all documented methods decorated with `@staticmethod`. These methods do not operate on the class or instance.
```python
return [
x
for x in self.members.values()
if isinstance(x, Function) and x.is_staticmethod
]
```
--------------------------------
### Export Documentation to HTML File
Source: https://pdoc.dev/docs/pdoc.html
Command to export the generated API documentation to a standalone HTML file. The output directory and file name can be specified.
```shell
pdoc ./demo.py -o ./docs
```
--------------------------------
### Get Module Level Functions
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves a list of all documented module-level functions from the members of the current object.
```python
@cached_property
def functions(self) -> list[Function]:
"""
A list of all documented module level functions.
"""
return [x for x in self.members.values() if isinstance(x, Function)]
```
--------------------------------
### AllModules
Source: https://pdoc.dev/docs/pdoc/web.html
A lazy-loading implementation of all_modules. Modules are imported on demand.
```APIDOC
## Class: AllModules
### Description
A lazy-loading implementation of all_modules. This behaves like a regular dict, but modules are only imported on demand for performance reasons.
### Methods
#### `__init__(self, allowed_modules: Iterable[str])`
Initializes AllModules with a collection of allowed module names.
```
--------------------------------
### Get Module Level Classes
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves a list of all documented module-level classes from the members of the current object.
```python
@cached_property
def classes(self) -> list[Class]:
"""
A list of all documented module level classes.
"""
return [x for x in self.members.values() if isinstance(x, Class)]
```
--------------------------------
### Get Module Level Variables
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves a list of all documented module-level variables from the members of the current object.
```python
@cached_property
def variables(self) -> list[Variable]:
"""
A list of all documented module level variables.
"""
return [x for x in self.members.values() if isinstance(x, Variable)]
```
--------------------------------
### Foo Class Constructor
Source: https://pdoc.dev/docs/demo_long.html
The constructor for the Foo class, initializing instance attributes.
```python
def __init__(self) -> None:
"""
The constructor is currently always listed first as this feels most natural."""
self.a_constructor_only_attribute: int = 42
"""This attribute is defined in the constructor only, but still picked up by pdoc's AST traversal."""
self.undocumented_constructor_attribute = 42
a_complex_function("a", "Foo", keyword_only_argument=1)
```
--------------------------------
### Define Decorated Function fib
Source: https://pdoc.dev/docs/demo_long.html
An example of a decorated function using the `@cache` decorator. Decorators are included in the documentation.
```python
@cache
def fib(n):
"""
This is an example of decorated function. Decorators are included in the documentation as well.
This is often useful when documenting web APIs, for example.
"""
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
```
--------------------------------
### Generate Documentation from Python File
Source: https://pdoc.dev/docs/pdoc.html
Command-line interface to generate API documentation for a Python file or module. pdoc automatically opens a browser with the rendered documentation.
```shell
pdoc ./demo.py # or: pdoc my_module_name
```
--------------------------------
### Configure pdoc Rendering Options
Source: https://pdoc.dev/docs/pdoc/render.html
Use the `configure` function to set global rendering options such as docstring format, inclusion of undocumented members, URL mapping for editing source code, and enabling features like math rendering, mermaid diagrams, and search.
```python
from typing import Literal
from typing import Mapping
def configure(
*,
docformat: Literal[
"markdown", "google", "numpy", "restructuredtext" # noqa: F821
] = "restructuredtext",
include_undocumented: bool = True,
edit_url_map: Mapping[str, str] | None = None,
favicon: str | None = None,
footer_text: str = "",
logo: str | None = None,
logo_link: str | None = None,
math: bool = False,
mermaid: bool = False,
search: bool = True,
show_source: bool = True,
template_directory: Path | None = None,
):
"""
Configure the rendering output.
- `docformat` is the docstring flavor in use.
pdoc prefers plain Markdown (the default), but also supports other formats.
- `include_undocumented` controls whether members without a docstring are included in the output.
- `edit_url_map` is a mapping from module names to URL prefixes. For example,
```json
{"pdoc": "https://github.com/mitmproxy/pdoc/blob/main/pdoc/"}
```
renders the "Edit on GitHub" button on this page. The URL prefix can be modified to pin a particular version.
- `favicon` is an optional path/URL for a favicon image
- `footer_text` is additional text that should appear in the navigation footer.
- `logo` is an optional URL to the project's logo image
- `logo_link` is an optional URL the logo should point to
- `math` enables math rendering by including MathJax into the rendered documentation.
- `mermaid` enables diagram rendering by including Mermaid.js into the rendered documentation.
- `search` controls whether search functionality is enabled and a search index is built.
- `show_source` controls whether a "View Source" button should be included in the output.
- `template_directory` can be used to set an additional (preferred) directory
for templates. You can find an example in the main documentation of `pdoc`
or in `examples/custom-template`.
"""
searchpath = _default_searchpath
if template_directory:
searchpath = [template_directory] + searchpath
env.loader = FileSystemLoader(searchpath)
env.globals["docformat"] = docformat
env.globals["include_undocumented"] = include_undocumented
env.globals["edit_url_map"] = edit_url_map or {}
env.globals["math"] = math
env.globals["mermaid"] = mermaid
env.globals["show_source"] = show_source
env.globals["favicon"] = favicon
env.globals["logo"] = logo
env.globals["logo_link"] = logo_link
env.globals["footer_text"] = footer_text
env.globals["search"] = search
```
--------------------------------
### Get Instance Variables
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves all documented instance variables within a class. These are variables not explicitly annotated as `typing.ClassVar`.
```python
return [
x
for x in self.members.values()
if isinstance(x, Variable) and not x.is_classvar
]
```
--------------------------------
### Documenting Instance Variables in Python Classes
Source: https://pdoc.dev/docs/pdoc.html
Illustrates pdoc's detection of instance variables using type annotations or definitions within `__init__`, when followed by a docstring.
```python
class GoldenRetriever(Dog):
name: str
"""Full Name"""
def __init__(self):
self.weight: int = 10
"""Weight in kilograms"""
```
--------------------------------
### Doc Class Initialization
Source: https://pdoc.dev/docs/pdoc/doc.html
Initializes a `Doc` object with module name, qualified name, the underlying object, and its origin.
```python
class Doc(Generic[T]):
"""
A base class for all documentation objects.
"""
modulename: str
"""
The module that this object is in, for example `pdoc.doc`.
"""
qualname: str
"""
The qualified identifier name for this object. For example, if we have the following code:
```python
class Foo:
def bar(self):
pass
```
The qualname of `Foo`'s `bar` method is `Foo.bar`. The qualname of the `Foo` class is just `Foo`.
See for details.
"""
obj: T
"""
The underlying Python object.
"""
taken_from: tuple[str, str]
"""
`(modulename, qualname)` of this doc object's original location.
In the context of a module, this points to the location it was imported from,
in the context of classes, this points to the class an attribute is inherited from.
"""
kind: ClassVar[str]
"""
The type of the doc object, either `"module"`, `"class"`, `"function"`, or `"variable"`.
"""
@property
def type(self) -> str: # pragma: no cover
warnings.warn(
"pdoc.doc.Doc.type is deprecated. Use pdoc.doc.Doc.kind instead.",
DeprecationWarning,
)
return self.kind
def __init__(
self,
modulename: str,
qualname: str,
obj: T,
taken_from: tuple[str, str],
):
"""
Initializes a documentation object, where
`modulename` is the name this module is defined in,
`qualname` contains a dotted path leading to the object from the module top-level, and
`obj` is the object to document.
"""
self.modulename = modulename
self.qualname = qualname
self.obj = obj
self.taken_from = taken_from
```
--------------------------------
### Get Own Members of a Module
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves a list of all members directly defined within the module, excluding inherited members.
```python
@cached_property
def own_members(self) -> list[Doc]:
return list(self.members.values())
```
--------------------------------
### Embedded Image Example
Source: https://pdoc.dev/docs/demo_long.html
This docstring includes embedded images using Markdown image syntax and HTML `
` tags.
```python
def embed_image():
"""
This docstring includes an embedded image:
```

```

```
```
"""
```
--------------------------------
### Doc Class Initialization
Source: https://pdoc.dev/docs/pdoc/doc.html
Initializes a documentation object with module, qualified name, the object itself, and its origin.
```APIDOC
## __init__ Doc(modulename: str, qualname: str, obj: ~T, taken_from: tuple[str, str])
### Description
Initializes a documentation object, where `modulename` is the name this module is defined in, `qualname` contains a dotted path leading to the object from the module top-level, and `obj` is the object to document.
### Parameters
#### Path Parameters
- **modulename** (str) - Required - The module that this object is in, for example `pdoc.doc`.
- **qualname** (str) - Required - The qualified identifier name for this object. For example, if we have the following code:
```
class Foo:
def bar(self):
pass
```
The qualname of `Foo`'s `bar` method is `Foo.bar`. The qualname of the `Foo` class is just `Foo`.
See https://www.python.org/dev/peps/pep-3155/ for details.
- **obj** (~T) - Required - The underlying Python object.
- **taken_from** (tuple[str, str]) - Required - `(modulename, qualname)` of this doc object's original location. In the context of a module, this points to the location it was imported from, in the context of classes, this points to the class an attribute is inherited from.
```
--------------------------------
### Decorated Function Example
Source: https://pdoc.dev/docs/demo_long.html
This function is decorated with `@cache`. Decorators are included in the documentation. This is often useful when documenting web APIs.
```python
@cache
def fib(n):
"""
This is an example of decorated function. Decorators are included in the documentation as well.
This is often useful when documenting web APIs, for example.
"""
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
```
--------------------------------
### Initialize AllModules
Source: https://pdoc.dev/docs/pdoc/web.html
Initializes the AllModules class, which provides a lazy-loading implementation for modules. It stores allowed modules in a dictionary to preserve order.
```python
class AllModules(Mapping[str, doc.Module]):
"""A lazy-loading implementation of all_modules.
This behaves like a regular dict, but modules are only imported on demand for performance reasons.
This has the somewhat annoying side effect that __getitem__ may raise a RuntimeError.
We can ignore that when rendering HTML as the default templates do not access all_modules values,
but we need to perform additional steps for the search index.
"""
def __init__(self, allowed_modules: Iterable[str]):
# use a dict to preserve order
self.allowed_modules: dict[str, None] = dict.fromkeys(allowed_modules)
```
--------------------------------
### Get Cleaned Docstring
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves the cleaned docstring for an object. Returns an empty string if the docstring is identical to object.__init__.__doc__ or cannot be found.
```python
if doc == object.__init__.__doc__:
# inspect.getdoc(Foo.__init__) returns the docstring, for object.__init__ if left undefined...
return ""
else:
return doc
```
--------------------------------
### Get Regular Methods
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves all documented methods that are neither static nor class methods. These typically operate on class instances.
```python
return [
x
for x in self.members.values()
if isinstance(x, Function)
and not x.is_staticmethod
and not x.is_classmethod
]
```
--------------------------------
### open_browser
Source: https://pdoc.dev/docs/pdoc/web.html
Open a URL in a browser window, with a limited list of suitable browsers.
```APIDOC
## Function: open_browser
### Description
Open a URL in a browser window. In contrast to `webbrowser.open`, this function limits the list of suitable browsers and gracefully degrades to a no-op on headless servers.
### Parameters
- **url** (str) - The URL to open in the browser.
### Returns
- `True`, if a browser has been opened.
- `False`, if no suitable browser has been found.
```
--------------------------------
### Get Class Variables
Source: https://pdoc.dev/docs/pdoc/doc.html
Retrieves all documented class variables, which are explicitly annotated with `typing.ClassVar`. Other variables are treated as instance variables.
```python
return [
x
for x in self.members.values()
if isinstance(x, Variable) and x.is_classvar
]
```