### Setup project dependencies with direnv Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Installs project dependencies and sets up the virtual environment using make and direnv. Run 'direnv allow' first. ```bash make setup ``` -------------------------------- ### Setup project dependencies without direnv Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Installs project dependencies and sets up the virtual environment by directly running the setup script. ```bash ./scripts/make setup ``` -------------------------------- ### Install Griffelib with uv Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use uv to install Griffe as a library only. ```bash uv add griffelib ``` -------------------------------- ### Install Griffe with uv Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use uv to install Griffe as a tool and library. ```bash uv add griffe ``` -------------------------------- ### Install Griffe Source: https://github.com/mkdocstrings/griffe/blob/main/README.md Install Griffe using pip. For uv users, use `uv tool install griffe`. ```bash pip install griffe ``` ```bash uv tool install griffe ``` -------------------------------- ### Install Griffelib with poetry Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use poetry to install Griffe as a library only. ```bash poetry add griffelib ``` -------------------------------- ### Install Griffelib with pdm Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use pdm to install Griffe as a library only. ```bash pdm add griffelib ``` -------------------------------- ### Install Griffe with poetry Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use poetry to install Griffe as a tool and library. ```bash poetry add griffe ``` -------------------------------- ### Install Griffe as a tool only with uv Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use uv to install Griffe as a tool only. ```bash uv tool install griffe ``` -------------------------------- ### Install Griffe with pdm Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use pdm to install Griffe as a tool and library. ```bash pdm add griffe ``` -------------------------------- ### Install Griffelib with pip Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use pip to install Griffe as a library only. ```bash pip install griffelib ``` -------------------------------- ### Start Live Reloading Server for Docs Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md Use this command to start the live reloading server for documentation updates. Disable mkdocstrings for faster reloading if needed. ```bash make docs MKDOCSTRINGS_ENABLED=false make docs ``` -------------------------------- ### Install Griffelib with rye Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use rye to install Griffe as a library only. ```bash rye add griffelib ``` -------------------------------- ### Install Griffe with pip Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use pip to install Griffe as a tool and library. ```bash pip install griffe ``` -------------------------------- ### Install Griffe with rye Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use rye to install Griffe as a tool and library. ```bash rye add griffe ``` -------------------------------- ### Class and Method Docstring Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Document a Python class, its purpose, methods, and properties. Includes an example of how to instantiate the class and document method usage. ```python class Ghost: """Ghosts that wander the earth. Ghosts are meant to... we're actually unsure. All we know is that, as a user, you might find it amusing to instantiate a few of them and put them together to see what they do. Methods: wander: Wander the earth. spook: Spook living organisms. pass_through: Pass through anything. Examples: Create a new ghost with a cool nickname: >>> ghost = Ghost(nickname="Rattlesnake") """ def wander(self) -> None: """Wander the earth. That's it, really. Examples: >>> ghost.wander() """ ... @property def weight(self) -> int: """The ghost's weight (spoiler: it's close to 0).""" ... ``` -------------------------------- ### Install Griffe with PyPI Extra Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/checking.md Installs Griffe with the 'pypi' extra, which is required to check packages directly from PyPI.org. ```console $ pip install griffe[pypi] ``` -------------------------------- ### Replicating File Tree and Running Python Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Commands to set up the file structure and start a Python interpreter for testing name shadowing. ```bash # Replicate the file tree from above. mkdir -p package/subpackage echo 'thing = "thing from init module"' > package/subpackage/__init__.py echo 'other_thing = "other thing from thing submodule"' > package/subpackage/thing.py # Run a Python interpreter. python ``` -------------------------------- ### Install Griffe as a tool only with rye Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use rye to install Griffe as a tool only. ```bash rye install griffe ``` -------------------------------- ### Install uv with curl Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Installs the uv package manager using a curl script. This is one of the official installation methods. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install uv with pip Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Installs the uv package manager using pip. Ensure pip is available in your environment. ```bash pip install --user uv ``` -------------------------------- ### Install Griffe as a tool only with pip Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use pip with the --user flag to install Griffe as a tool only. ```bash pip install --user griffe ``` -------------------------------- ### Adding Examples with NumpyDoc Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Examples sections allow adding Python code examples directly within docstrings, mixing prose with interactive console snippets. Blank lines separate prose from console blocks. ```python """My module. Examples -------- Some explanation of what is possible. >>> print("hello!") hello! Blank lines delimit prose vs. console blocks. >>> a = 0 >>> a += 1 >>> a 1 """ ``` -------------------------------- ### Package layout example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md This tree structure illustrates the file layout for package1 and package2. ```tree ./ package1/ __init__.py package2/ __init__.py ``` -------------------------------- ### Install and Load Package with Griffe Source: https://github.com/mkdocstrings/griffe/blob/main/docs/playground.md Use this snippet to install a Python package using micropip and then load it with Griffe for API exploration. This is useful for quickly inspecting the structure of external libraries within the browser playground. ```python import griffe, micropip # Install your favorite Python package... await micropip.install("cowsay") # And load it with Griffe! cowsay = griffe.load("cowsay") cowsay.as_json(indent=2)[:1000] ``` -------------------------------- ### Get Help for Commands Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/commands.md Type 'make help' to display detailed information about all available commands and their usage. ```console $ make help ``` -------------------------------- ### Install Griffe as a tool only with pipx Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Use pipx to install Griffe as a tool only, in an isolated environment. ```bash pipx install griffe ``` -------------------------------- ### Numpydoc Syntax Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Demonstrates the basic syntax for Numpydoc docstrings, including parameters with multi-line descriptions. ```python def foo(a, b): """Foo. Parameters ---------- a Here's a. Continuation line 1. Continuation line 2. b Here's b. """ ``` -------------------------------- ### Install uv with rye Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Installs the uv package manager using rye, a comprehensive Python project management tool. ```bash rye install uv ``` -------------------------------- ### Install uv with pipx Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Installs the uv package manager using pipx, which provides isolated environments for Python applications. ```bash pipx install uv ``` -------------------------------- ### Canonical Import Example (Good) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Importing 'thing' directly from 'package.module_a' is a canonical import and is recommended. ```python from package.module_a import thing # Canonical import, good. ``` -------------------------------- ### Class Docstring with Pycon Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Demonstrates using fenced code blocks within docstrings for examples, specifically using the 'pycon' language identifier for interactive Python console sessions. ```python """ Examples: Create a new ghost with a cool nickname: ```pycon >>> ghost = Ghost(nickname="Rattlesnake") ``` """ ``` -------------------------------- ### Google-style Docstring Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Demonstrates the Google-style docstring format for parameters and notes. This style is recommended for its markup-agnostic nature. ```python def greet(name: str, end: str = "!") -> None: """Greet someone. Parameters: name: The name to greet. end: The punctuation mark at the end. Note: Greetings are cool! """ print(f"Hey {name}{end}") ‎ ``` -------------------------------- ### Canonical Import Example (Good) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Importing 'thing' directly from 'package.module_b' is a canonical import and is recommended. ```python from package.module_b import thing # Canonical import, good. ``` -------------------------------- ### Interactive Examples in Docstrings Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md The 'Examples:' section allows for embedding interactive console snippets within docstrings. Use blank lines to separate prose from code blocks. ```python """My module. Examples: Some explanation of what is possible. >>> print("hello!") hello! Blank lines delimit prose vs. console blocks. >>> a = 0 >>> a += 1 >>> a 1 """ ``` -------------------------------- ### Canonical Import Example (Good) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Importing 'thing' directly from 'package.module_b' is a canonical import and is recommended. ```python from package.module_b import thing ``` -------------------------------- ### Module Docstring Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Document a Python package's purpose, exposed API, and contents. This example shows how to describe attributes, classes, and functions within a module. ```python """A generic package to demonstrate docstrings. This package does not really exist, and is only used as a demonstration purpose for docstrings. Anyway, this package contains the following API, exposed directly at the top-level, meaning you can import everything from `package` directly. Attributes: ghost: A ghost wandering in this desolated land. dummy: A dummy you can practice on. Not for ghosts. Classes: Ghost: Ah, so this is where our ghost comes from. Maybe create some additional ghosts so they can pass the time together? Functions: deploy(): Deploy something on the web (we're not sure what exactly). """ ``` -------------------------------- ### MkDocs Configuration for Griffe Extension Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/how-to/set-docstring-styles.md Example MkDocs configuration to enable a custom Griffe extension and provide explicit configuration for mapping object paths to docstring styles. ```yaml plugins: - mkdocstrings: handlers: python: options: extensions: - your_griffe_extension.py: config: path.to.obj1: google path.to.obj2: numpy path.to.obj3.*: sphinx path.to.obj4*: google ``` -------------------------------- ### Example Commit Message with Trailers Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md Demonstrates how to include trailers for issue and pull request references at the end of a commit message body. ```text This is the body of the commit message. Issue-10: https://github.com/namespace/project/issues/10 Related-to-PR-namespace/other-project#15: https://github.com/namespace/other-project/pull/15 ``` -------------------------------- ### Package Structure Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Illustrates a package structure where a submodule might shadow an attribute in its parent's __init__.py. This structure is discouraged. ```tree package/ __init__.py subpackage/ __init__.py thing.py ``` -------------------------------- ### Example Commit Subject Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md Illustrates the subject line format for commit messages, including the type and a concise description. ```text feat: Add CLI option to run in verbose mode ``` -------------------------------- ### Example Usage of a Custom Decorator Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/how-to/support-decorators.md Illustrates how a custom decorator is applied to a function definition. ```python from my_package.utils import enhance @enhance def my_function() -> ...: ... ``` -------------------------------- ### Use Case for Positional-Only Parameters Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/checking.md Shows an example of using positional-only parameters when parameter order does not matter and naming is not intuitive. ```python def multiply3(a, b, c, /): return a * b * c # all the following are equivalent multiply3(4, 2, 3) multiply3(4, 3, 2) multiply3(2, 3, 4) # etc. ``` -------------------------------- ### Numpydoc Attributes Section Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Shows how to document module and class attributes using the 'Attributes' section in Numpydoc format. ```python """My module. Attributes ---------- foo Description for `foo`. bar Description for `bar`. """ foo: int = 0 bar: bool = True class MyClass: """My class. Attributes ---------- foofoo Description for `foofoo`. barbar Description for `barbar`. """ foofoo: int = 0 def __init__(self): self.barbar: bool = True ``` -------------------------------- ### Define a Dataclass Source: https://github.com/mkdocstrings/griffe/blob/main/docs/extensions/built-in/dataclasses.md Example of defining a simple dataclass with type hints and default values. ```python from dataclasses import dataclass @dataclass class Room: uid: int name: str capacity: int = 10 available: bool = True ``` -------------------------------- ### Keyword-Only Arguments (Before) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/checking.md Demonstrates using keyword-only arguments to prevent issues caused by moving parameters. This setup ensures parameter order does not affect functionality. ```python def greet(*, prefix, name): print(prefix + " " + name) greet(prefix="hello", name="world") ``` -------------------------------- ### Load Package from File Path Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Load API data by passing absolute or relative file paths to the `griffe.load` function. This is useful for packages not installed in the current environment. ```python import griffe griffe.load("src/my_package") griffe.load("some_script.py") ``` -------------------------------- ### Dump JSON API with Griffe CLI Source: https://github.com/mkdocstrings/griffe/blob/main/README.md Use the `griffe dump` command to get JSON-serialized API information for specified packages. See the Serializing chapter for more examples. ```console $ griffe dump httpx fastapi { "httpx": { "name": "httpx", ... }, "fastapi": { "name": "fastapi", ... } } ``` -------------------------------- ### Exposing class in a single module location (good) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/public-apis.md This example demonstrates exposing a class in a single module, with no re-export in __init__.py. This is a recommended pattern for clarity and avoiding import conflicts. ```python __all__ ["Hello"] class Hello: ... ``` ```python # Nothing to see here. ``` -------------------------------- ### Documenting Modules with NumpyDoc Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Use Modules sections in module docstrings to document submodules. This example shows a tree structure and a corresponding __init__.py docstring. ```tree my_pkg/ __init__.py foo.py bar.py ``` ```python """My package. Modules ------- foo Description for `foo`. bar Description for `bar`. """ ``` -------------------------------- ### Documenting Returned Values from Functions Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Example of a function with a 'Returns' section to document its return value. Type annotations are fetched from the function's return annotation. ```python import random def foo() -> int: """Foo. Returns: A random integer. """ return random.randint(0, 100) ``` -------------------------------- ### Clone repository with GitHub CLI Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/setup.md Clones the griffe repository using the GitHub CLI tool. Requires gh to be installed and authenticated. ```bash gh repo clone griffe ``` -------------------------------- ### Documenting Functions and Methods Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Use docstrings to describe function parameters, return values, and any yielded or received values for generators. This example shows documentation for a regular function, a generator function, and an iterator function. ```python import datetime from typing import Generator, Iterator class GhostOlympicGames: ... class GOGTicket: ... def organize_gog(date: datetime.date) -> GhostOlympicGames: """Organize Olympic Games for Ghosts. The ghost world is much simpler than the living world, so it's super easy to organize big events like this. Parameters: date: The date of the games. Returns: The prepared games. """ ... def yield_athletes(quantity: int) -> Iterator[Ghost]: """Yield a certain quantity of athletes. Parameters: quantity: How many ghost athletes you want. Yields: Ghost athletes. They're just regular ghosts. """ ... def gog_tickets_factory() -> Generator[GOGTicket, int, None]: """Generate tickets for the GOG. We value fairness: tickets are priced randomly. Unless we send a specific price to the generator. Yields: Tickets for the games. Receives: Price for the next ticket, in ghost money (???). """ ... ``` -------------------------------- ### Exposing class in multiple locations (bad) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/public-apis.md This example shows a class exposed in both a module and the package's __init__.py, which can lead to ambiguity. Use this pattern to understand what to avoid. ```python __all__ ["Hello"] class Hello: ... ``` ```python from my_package.module import Hello __all__ = ["Hello"] ``` -------------------------------- ### Python Docstring Examples Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Demonstrates various types of docstrings in Python, including module, type alias, attribute, function, class, and method docstrings. ```python """This is the module docstring.""" type X = dict[str, int] """This is a type alias docstring.""" a = 0 """This is an attribute docstring.""" def b(): """This is a function docstring.""" pass class C: """This is a class docstring.""" def d(self): """This is a method docstring.""" pass ``` -------------------------------- ### Extension with Configuration Options Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/how-to/selectively-inspect.md Implement the `__init__` method to accept configuration, such as a list of object paths to inspect. This allows for flexible customization of the extension's behavior. ```python import griffe class InspectSpecificObjects(griffe.Extension): """An extension to inspect just a few specific objects.""" def __init__(self, objects: list[str]) -> None: self.objects = objects ``` -------------------------------- ### Create a New Release Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md Initiates the release process, which includes staging the changelog, committing, tagging, pushing, building distributions, uploading to PyPI, and deploying documentation. You can specify the version or be prompted. ```bash make release version=x.x.x ``` -------------------------------- ### Testing Griffe CLI Commands Programmatically Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/public-apis.md Examples of testing Griffe's CLI commands using pytest. These tests import the griffe.main function and pass command-line arguments as a list of strings, asserting exit codes and captured output. ```python import pytest import griffe def test_main() -> None: assert griffe.main(["dump", "griffe", "-s", "src", "-o/dev/null"]) == 0 ``` ```python import pytest import griffe def test_show_help(capsys: pytest.CaptureFixture) -> None: with pytest.raises(SystemExit): griffe.main(["-h"]) captured = capsys.readouterr() assert "griffe" in captured.out ``` ```python import pytest import griffe def test_show_version(capsys: pytest.CaptureFixture) -> None: with pytest.raises(SystemExit): griffe.main(["-V"]) captured = capsys.readouterr() assert griffe.get_version() in captured.out ``` -------------------------------- ### package1/__init__.py Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Defines a simple variable X in package1. ```python X = 0 ``` -------------------------------- ### Render Griffe CLI Help Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/cli.md This script generates and prints the help documentation for the griffe CLI parser. It's useful for understanding available commands and options. ```python import argparse import sys from griffe import get_parser parser = get_parser() def render_parser(parser: argparse.ArgumentParser, title: str, heading_level: int = 2) -> str: """Render the parser help documents as a string.""" result = [f"{'#' * heading_level} {title}\n"] if parser.description and title != "pdm": result.append("> " + parser.description + "\n") for group in sorted(parser._action_groups, key=lambda g: g.title.lower(), reverse=True): if not any( bool(action.option_strings or action.dest) or isinstance(action, argparse._SubParsersAction) for action in group._group_actions ): continue result.append(f"{group.title.title()}:\n") for action in group._group_actions: if isinstance(action, argparse._SubParsersAction): for name, subparser in action._name_parser_map.items(): result.append(render_parser(subparser, name, heading_level + 1)) continue opts = [f"`{opt}`" for opt in action.option_strings] if not opts: line = f"- `{action.dest}`" else: line = f"- {', '.join(opts)}" if action.metavar: line += f" `{action.metavar}`" line += f": {action.help}" if action.default and action.default != argparse.SUPPRESS: if action.default is sys.stdout: default = "sys.stdout" else: default = str(action.default) line += f" Default: `{default}`." result.append(line) result.append("") return "\n".join(result) print(render_parser(parser, "griffe")) ``` -------------------------------- ### Manually Deploy Documentation Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md If the release task fails, you can manually deploy the documentation using this command. ```bash make docs-deploy ``` -------------------------------- ### Display Available Commands Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/commands.md Use the 'make' script to view a list of available management commands. This is the primary entry point for project management. ```console $ alias make="$PWD/scripts/make"; cd # markdown-exec: hide $ make ``` -------------------------------- ### package2/__init__.py Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Imports X from package1, creating an alias. ```python from package1 import X ``` -------------------------------- ### Render CLI Entrypoint Documentation Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/architecture.md Renders documentation for the CLI entrypoint. This function is part of the internal documentation generation process. ```python render_entrypoint(heading_level=4) ``` -------------------------------- ### Forward-Compatibility with Keyword-Only Parameters Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/checking.md Demonstrates using keyword-only parameters for optional arguments to improve forward-compatibility. ```python def greet(name, *, punctuation=False, bold=False, italic=False): ... # simple cases are easy to write greet("tim") greet("tiff") # complex cases are never ambiguous greet("tim", italic=True, bold=True) greet(name="tiff", bold=True, punctuation=True) ``` -------------------------------- ### Imported Objects are Not Public Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/public-apis.md Illustrates that imported objects are not considered public by default, even if they do not start with an underscore. ```python from elsewhere import something ``` -------------------------------- ### Recommended Package Structure for Clarity Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Suggests prefixing submodule names with an underscore (e.g., _thing.py) to clearly distinguish them from attributes in the parent's __init__.py, avoiding ambiguity. ```tree package/ __init__.py subpackage/ __init__.py _thing.py ``` -------------------------------- ### Indirect Import Example (Bad) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Importing 'thing' from 'package.module_a' which itself imports 'thing' from 'package.module_b' is an indirect import and should be avoided. ```python from package.module_a import thing # Indirect import, bad. ``` -------------------------------- ### Define Griffe Extension Class Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/how-to/selectively-inspect.md Create a Python class that inherits from `griffe.Extension` to start building your custom extension. ```python import griffe class InspectSpecificObjects(griffe.Extension): """An extension to inspect just a few specific objects.""" ``` -------------------------------- ### Expose Extension in Package Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/extending.md Make your custom extension discoverable by importing it in the top-level `__init__.py` file of your package. ```python from dynamic_docstrings.extension import DynamicDocstrings __all__ = ["DynamicDocstrings"] ``` -------------------------------- ### Indirect Import Example (Bad) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Importing 'thing' from 'package' which imports it from 'package.module_a' is an indirect import passing through the parent and should be avoided. ```python from package import thing # Indirect import passing through parent, bad. ``` -------------------------------- ### Numpydoc-style Docstring Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Illustrates the Numpydoc-style docstring format, which also uses sections for parameters and notes. This style is favored for its readability. ```python def greet(name: str, end: str = "!") -> None: """Greet someone. Parameters ---------- name The name to greet. end The punctuation mark at the end. Note ---- Greetings are cool! """ print(f"Hey {name}{end}") ``` -------------------------------- ### Specify extensions via command-line (JSON list) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/extending.md Use the `-e` or `--extensions` option with a JSON list to specify extensions and their options. ```bash griffe check --search src griffe -e \ '[ {"pydantic": {"schema": true}}, { "scripts/exts.py:DynamicDocstrings": { "paths": ["mypkg.mymod.myobj"] } }, "griffe_attrs" ]' ``` -------------------------------- ### griffe.load_pypi Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/api/loaders.md Loads a module from PyPI. ```APIDOC ## griffe.load_pypi ### Description Loads a module from PyPI. ### Parameters (No parameters explicitly documented in the source) ### Returns (No return value explicitly documented in the source) ``` -------------------------------- ### Specify extensions via command-line (comma-separated) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/extending.md Use the `-e` or `--extensions` option with a comma-separated list of extension names or paths. ```bash griffe dump griffe -e pydantic,scripts/exts.py:DynamicDocstrings,griffe_attrs ``` -------------------------------- ### Manually Build Distributions Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md If the release task fails, you can manually build distributions using this command. ```bash make build ``` -------------------------------- ### Dynamic Docstrings Extension Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/extending.md An example extension that dynamically imports objects to retrieve and update their docstrings. It can be configured to target specific object paths. ```python import ast import inspect import griffe logger = griffe.get_logger(__name__) class DynamicDocstrings(griffe.Extension): def __init__(self, object_paths: list[str] | None = None) -> None: self.object_paths = object_paths def on_object( self, obj: griffe.Object, loader: griffe.GriffeLoader, **kwargs, ) -> None: if obj.analysis == "dynamic": return # Skip runtime objects, their docstrings are already right. if self.object_paths and obj.path not in self.object_paths: return # Skip objects that were not selected. # Import object to get its evaluated docstring. try: runtime_obj = griffe.dynamic_import(obj.path) docstring = runtime_obj.__doc__ except ImportError: logger.debug(f"Could not get dynamic docstring for {obj.path}") return except AttributeError: logger.debug(f"Object {obj.path} does not have a __doc__ attribute") return # Update the object instance with the evaluated docstring. docstring = inspect.cleandoc(docstring) if obj.docstring: obj.docstring.value = docstring else: obj.docstring = griffe.Docstring( docstring, parent=obj, docstring_parser=loader.docstring_parser, docstring_options=loader.docstring_options, ) ``` -------------------------------- ### Load Package Data with Griffe Python API Source: https://github.com/mkdocstrings/griffe/blob/main/README.md Load a package using `griffe.load()` for programmatic access. See the Loading chapter for more examples. ```python import griffe fastapi = griffe.load("fastapi") ``` -------------------------------- ### Implicitly Exposed to Wildcard Imports Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Objects not starting with an underscore are implicitly exposed to wildcard imports. This can lead to unintended imports if not carefully managed. ```python class SomeClass: ... class _SomeOtherClass: ... def some_function(): ... def _some_other_function(): ... some_attribute = 0 _some_other_attribute = 1 ``` -------------------------------- ### Specify Search Paths with `load` function Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Configure the directories Griffe searches for packages and modules using the `search_paths` parameter in the `griffe.load` function. ```python import griffe my_package = griffe.load("my_package", search_paths=["src"]) ``` -------------------------------- ### Enable `dataclasses` Extension via CLI Source: https://github.com/mkdocstrings/griffe/blob/main/docs/extensions/built-in/dataclasses.md How to enable the `dataclasses` extension when using the Griffe CLI for dumping package information. ```console $ griffe dump -e dataclasses,other my_package ``` -------------------------------- ### Public module importing from compiled module Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Example of a public Python module exposing objects from a private compiled module using wildcard import. ```python from package._module import * ``` -------------------------------- ### Main API: as_json() and from_json() Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/api/serializers.md Provides methods for converting Griffe objects to and from JSON format. ```APIDOC ## Main API See the [`as_json()`][griffe.Object.as_json] and [`from_json()`][griffe.Object.from_json] methods of objects. ``` -------------------------------- ### Mark Function for Removal in Future Version Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md Example of using Yore comments to mark a function for removal in a future major version (e.g., v5.0). ```python # YORE: Bump 5: Remove block. def deprecated_function(): ... ``` -------------------------------- ### Programmatic Access to Griffe Main Entrypoint Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/public-apis.md This script shows how to import and run the griffe.main function programmatically. It's useful for direct execution or integration into other Python scripts. ```python import re import sys from griffe import main if __name__ == "__main__": sys.argv[0] = re.sub(r"(-script\.pyw|\.exe)?$", "", sys.argv[0]) sys.exit(main()) ``` -------------------------------- ### Load a Package Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Use the `griffe.load` function to load API data for a given package name. ```python import griffe my_package = griffe.load("my_package") ``` -------------------------------- ### Valid Google-style Docstring with Initial Newline for Parameter Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Shows a valid Google-style docstring where a parameter's description starts with a newline for potentially improved readability. ```python def foo(a, b): """Foo. Parameters: a: Here's a. Continuation line 1. Continuation line 2. b: Here's b. """ ``` -------------------------------- ### Generic type with forward reference in base class (3.12+) Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Shows the syntax for generic types with forward references in base classes starting from Python 3.12. ```python class Foo[T]: ... class FooBar(Foo['Bar']): ... class Bar: ... ``` -------------------------------- ### Implementing `on_function_instance` Hook Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/how-to/support-decorators.md Shows how to implement the `on_function_instance` hook to process decorated functions. This hook receives `griffe.Function` objects. ```python import griffe class MyDecorator(griffe.Extension): """An extension to suport my decorator.""" def on_function_instance(self, *, func: griffe.Function, **kwargs) -> None: ... ``` -------------------------------- ### Rust PyO3 class with correct module attribute Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Example using PyO3 in Rust to define a Python class, ensuring the `module` attribute points to the canonical location. ```rust // Your module is compiled and added as `_module` into `package`, // but its objects are exposed in `package` or `package.module`. // Set `module = "package._module"`, not `module = "package"` or `module = "package.module"`! #[pyclass(name = "MyClass", module = "package._module")] struct MyClass { // ... } ``` -------------------------------- ### griffe.load Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/api/loaders.md Loads a module from a given filepath. ```APIDOC ## griffe.load ### Description Loads a module from a given filepath. ### Parameters (No parameters explicitly documented in the source) ### Returns (No return value explicitly documented in the source) ``` -------------------------------- ### Mark Code for Simplification After Python EOL Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/contributors/workflow.md Example of using Yore comments to mark code that can be simplified once a specific Python version (e.g., 3.15) reaches its End-of-Life. ```python # YORE: EOL 3.15: Replace block with line 4. try: import ... except ImportError: import ... ``` -------------------------------- ### Load extensions programmatically in Python Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/extending.md Instantiate `griffe.Extensions` using `griffe.load_extensions` with various extension specifications, then pass it to `griffe.load`. ```python import griffe from mypackage.extensions import ThisExtension, ThisOtherExtension extensions = griffe.load_extensions( {"pydantic": {"schema": true}}, {"scripts/exts.py:DynamicDocstrings": {"paths": ["mypkg.mymod.myobj"]}}, "griffe_attrs", ThisExtension(option="value"), ThisOtherExtension, ) data = griffe.load("mypackage", extensions=extensions) ``` -------------------------------- ### Class with Inherited Docstrings Source: https://github.com/mkdocstrings/griffe/blob/main/docs/extensions/official/inherited-docstrings.md This example demonstrates how docstrings are inherited. Without the extension, Derived.attr and Derived.hello would not have docstrings. With the extension enabled, they inherit from Base.attr and Base.hello respectively. ```python class Base: attr = "hello" """Hello.""" def hello(self): """Hello again.""" ... class Derived(Base): attr = "bye" def hello(self): ... ``` -------------------------------- ### PEP 727 Docstring Example Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/docstrings.md Shows how PEP 727 uses `typing.Annotated` and `Doc` for metadata, allowing docstrings to be plain Markdown. This approach avoids docstring parsing by Griffe. ```python from typing_extensions import Annotated, Doc def greet( name: Annotated[str, Doc("The name to greet.")], end: Annotated[str, Doc("The punctuation mark at the end.")] = "!", ) -> None: """Greet someone. > [!NOTE] > Greetings are cool! """ # (1)! print(f"Hey {name}{end}") ``` -------------------------------- ### Documenting Tuple Returns with Type Annotations Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Illustrates documenting a function that returns a tuple, with each tuple item documented separately. Type annotations are fetched accordingly. ```python def foo() -> tuple[bool, float]: """Foo. Returns: success: Whether it succeeded. precision: Final precision. ... """ ... ``` -------------------------------- ### Instantiate and Use GriffeLoader Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md For efficiency, instantiate `GriffeLoader` once and reuse its `load` method. This caches directory contents and reduces IO operations. ```python import griffe loader = GriffeLoader() my_package = loader.load("my_package") my_other_package = loader.load("my_other_package") ``` -------------------------------- ### TypedDict with Unpack Source: https://github.com/mkdocstrings/griffe/blob/main/docs/extensions/built-in/unpack-typeddict.md Defines a TypedDict for greeting parameters and a function that uses `Unpack` to accept these parameters via `**kwargs`. This example demonstrates the original code structure before the extension is applied. ```python from typing import TypedDict, Unpack class GreetKwargs(TypedDict): name: str """The name of a person to greet.""" shout: bool """Whether to shout.""" def greet(**kwargs: Unpack[GreetKwargs]) -> str: """Greet someone. Parameters: **kwargs: Greet parameters. Returns: A message. """ message = f"Hello {kwargs['name']}!" if kwargs["shout"]: return message.upper() + "!!" return message ``` -------------------------------- ### Control Relative Path Loading Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Instruct Griffe to ignore existing relative file paths by setting `try_relative_path=False`. This forces Griffe to use the installed version of a package instead of a local one. ```python import griffe my_installed_package = griffe.load("my_package", try_relative_path=False) ``` -------------------------------- ### Documenting Received Values in Generators Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Example of a generator function with a 'Receives' section to document values sent via the 'send' method. Type annotations are fetched from the function's return annotation. ```python from typing import Generator def foo() -> Generator[int, str, None]: """Foo. Receives: reverse: Reverse the generator if "reverse" is received. Yields: Integers from 0 to 9. Examples: >>> gen = foo() >>> next(gen) 0 >>> next(gen) 1 >>> next(gen) 2 >>> gen.send("reverse") 2 >>> next(gen) 1 >>> next(gen) 0 >>> next(gen) Traceback (most recent call last): File "", line 1, in StopIteration """ for i in range(10): received = yield i if received == "reverse": for j in range(i, -1, -1): yield j break ``` -------------------------------- ### Run Griffe command Source: https://github.com/mkdocstrings/griffe/blob/main/docs/installation.md Execute Griffe using the 'griffe' command-line interface. ```console $ griffe check mypackage ``` -------------------------------- ### Load external package to resolve aliases Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/loading.md Instruct Griffe loaders to automatically load external packages when resolving aliases. This example shows how `package1` is loaded implicitly when resolving aliases for `package2`. ```python import griffe package2 = griffe.load("package2", resolve_aliases=True, resolve_external=True) print(package2["X"].target.name) # X ``` -------------------------------- ### griffe.ExplanationStyle Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/api/checks.md Enum for explanation styles. ```APIDOC ## griffe.ExplanationStyle ### Description An enumeration representing different styles for explanations. ### Method (Not specified, likely an enum usage) ### Endpoint (Not applicable for an enum) ### Parameters (Parameters not explicitly detailed in the source) ### Request Example (Not applicable for an enum) ### Response (Response details not explicitly detailed in the source) ``` -------------------------------- ### Example of a Griffe JSON structure for a class Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/serializing.md This JSON structure represents a Griffe class object, including its name, line numbers, docstring, labels, members, bases, and decorators. It illustrates the detailed output format. ```json { "kind": "class", "name": "Expr", "lineno": 82, "endlineno": 171, "docstring": { "value": "Base class for expressions.", "lineno": 84, "endlineno": 84 }, "labels": [ "dataclass" ], "members": [ ... ], "bases": [], "decorators": [ { "value": { "name": "dataclass", "cls": "ExprName" }, "lineno": 82, "endlineno": 82 } ] } ``` -------------------------------- ### Main API Commands Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/api/cli.md These are the primary commands for interacting with the Griffe CLI. ```APIDOC ## Main API Commands This section details the primary commands available through the Griffe CLI. ### `griffecli.main` **Description:** Provides the main entry point for the Griffe CLI, orchestrating various subcommands. ### `griffecli.check` **Description:** Used to check the integrity and consistency of Griffe's data or configurations. ### `griffecli.dump` **Description:** Allows dumping Griffe's internal data structures or configurations to a specified format. ``` -------------------------------- ### Documenting Tuple Receives with Type Annotations Source: https://github.com/mkdocstrings/griffe/blob/main/docs/reference/docstrings.md Demonstrates documenting a generator that receives a tuple, with each tuple item documented separately. Type annotations are fetched accordingly. ```python def foo() -> Generator[int, tuple[str, bool], None]: """Foo. Receives: mode: Some mode. flag: Some flag. ... """ ... ``` -------------------------------- ### GitHub Actions Workflow for API Change Check Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/checking.md Integrate Griffe into a GitHub Actions workflow to automatically check for API breaking changes in pull/merge requests. This example compares the current changes against the latest Git tag. ```yaml jobs: check-api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 with: fetch-depth: 0 # We the need the full Git history. - uses: astral-sh/setup-uv@v6 # The following command will compare current changes to latest tag. - run: uvx griffe check --search src --format github your_package_name ``` -------------------------------- ### Azure Pipelines for API Change Check Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/checking.md Set up an Azure Pipeline to enforce API stability by checking for breaking changes with Griffe. This example utilizes Azure DevOps task logging commands for formatted output and compares against the latest tag. ```yaml jobs: - name: check-api pool: vmImage: 'ubuntu-latest' steps: - checkout: self fetchDepth: 0 # We the need the full Git history. - task: CmdLine@2 inputs: script: pip install --user griffe - task: CmdLine@2 inputs: # The following command will compare current changes to latest tag. script: | griffe check --search src --format azdo your_package_name ``` -------------------------------- ### Wildcard Import in __init__.py Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/python-code.md Demonstrates a wildcard import from a submodule into the package's `__init__.py`. This will import objects based on the submodule's export rules (`__all__` or implicit). ```python from package.module import * ``` -------------------------------- ### Set Logger Level for Specific Module Source: https://github.com/mkdocstrings/griffe/blob/main/docs/guide/users/recommendations/public-apis.md This example demonstrates how to set a specific logging level for a logger named after a particular module. This can be useful for controlling log verbosity from specific parts of a package, especially when avoiding the use of `__name__` for logger names in private modules. ```python # For example, the following would have zero effect if `_module` was renamed `_other_module`. package_module_logger = logging.getLogger("package._module") package_module_logger.setLevel(logging.ERROR) ```