CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-griffe

Extract Python API signatures and detect breaking changes for documentation generation.

Pending
Overview
Eval results
Files

models.mddocs/

Models

The core object models that represent Python API elements. These classes form the foundation of Griffe's object hierarchy and provide the primary interface for working with analyzed Python code structures.

Capabilities

Base Object Class

Abstract base class for all Griffe objects providing common functionality.

class Object:
    """
    Abstract base class representing a Python object.
    
    Provides common functionality for all Griffe object types including
    serialization, path resolution, and member management.
    """
    
    def __init__(
        self,
        name: str,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
        runtime: bool = True,
        docstring: Docstring | None = None,
        parent: Module | Class | None = None,
    ) -> None:
        """
        Initialize the object.
        
        Args:
            name: The object's name
            lineno: Starting line number in source
            endlineno: Ending line number in source  
            runtime: Whether object was found at runtime
            docstring: Associated docstring
            parent: Parent object (module or class)
        """
    
    @property
    def name(self) -> str:
        """The object's name."""
    
    @property
    def path(self) -> str:
        """The object's full dotted path."""
    
    @property
    def filepath(self) -> Path | None:
        """Path to the file containing this object."""
    
    @property
    def lineno(self) -> int | None:
        """Starting line number in source file."""
    
    @property
    def endlineno(self) -> int | None:
        """Ending line number in source file."""
    
    @property
    def docstring(self) -> Docstring | None:
        """The object's docstring."""
    
    @property
    def parent(self) -> Module | Class | None:
        """The object's parent (module or class)."""
    
    @property
    def module(self) -> Module:
        """The module containing this object."""
    
    @property
    def package(self) -> Module:
        """The top-level package containing this object."""
    
    def serialize(self, **kwargs: Any) -> dict[str, Any]:
        """
        Serialize the object to a dictionary.
        
        Args:
            **kwargs: Serialization options
            
        Returns:
            dict: Serialized representation
        """
    
    def as_json(self, **kwargs: Any) -> str:
        """
        Serialize the object to JSON string.
        
        Args:
            **kwargs: JSON serialization options
            
        Returns:
            str: JSON representation
        """
    
    @classmethod
    def from_json(cls, json_str: str, **kwargs: Any) -> Object:
        """
        Deserialize an object from JSON.
        
        Args:
            json_str: JSON string to deserialize
            **kwargs: Deserialization options
            
        Returns:
            Object: Deserialized object
        """

Module Class

Represents a Python module containing other objects.

class Module(Object):
    """
    Class representing a Python module.
    
    Contains attributes, classes, functions, and other module-level objects.
    Serves as a container and namespace for Python code elements.
    """
    
    def __init__(
        self,
        name: str,
        *,
        filepath: str | Path | None = None,
        parent: Module | None = None,
        **kwargs: Any,
    ) -> None:
        """
        Initialize the module.
        
        Args:
            name: Module name
            filepath: Path to the module file
            parent: Parent module (for submodules)
            **kwargs: Additional Object parameters
        """
    
    @property
    def filepath(self) -> Path | None:
        """Path to the module file."""
    
    @property
    def modules(self) -> dict[str, Module]:
        """Submodules contained in this module."""
    
    @property  
    def classes(self) -> dict[str, Class]:
        """Classes defined in this module."""
    
    @property
    def functions(self) -> dict[str, Function]:
        """Functions defined in this module."""
    
    @property
    def attributes(self) -> dict[str, Attribute]:
        """Attributes defined in this module."""
    
    @property
    def aliases(self) -> dict[str, Alias]:
        """Aliases (imports) in this module."""
    
    @property
    def exports(self) -> set[str] | None:
        """Exported names (__all__ list)."""
    
    def __getitem__(self, key: str) -> Object:
        """
        Get a member by name.
        
        Args:
            key: Member name
            
        Returns:
            Object: The requested member
            
        Raises:
            KeyError: If member not found
        """
    
    def __contains__(self, key: str) -> bool:
        """Check if module contains a member."""

Class Class

Represents a Python class with methods, attributes, and inheritance.

class Class(Object):
    """
    Class representing a Python class.
    
    Includes methods, attributes, decorators, base classes, and docstrings.
    Supports inheritance relationships and method resolution order.
    """
    
    def __init__(
        self,
        name: str,
        *,
        bases: list[Expr] | None = None,
        decorators: list[Decorator] | None = None,
        **kwargs: Any,
    ) -> None:
        """
        Initialize the class.
        
        Args:
            name: Class name
            bases: Base class expressions
            decorators: Applied decorators
            **kwargs: Additional Object parameters
        """
    
    @property
    def bases(self) -> list[Expr]:
        """Base class expressions."""
    
    @property
    def decorators(self) -> list[Decorator]:
        """Decorators applied to this class."""
    
    @property
    def methods(self) -> dict[str, Function]:
        """Methods defined in this class."""
    
    @property
    def attributes(self) -> dict[str, Attribute]:
        """Attributes defined in this class."""
    
    @property
    def classes(self) -> dict[str, Class]:
        """Nested classes defined in this class."""
    
    @property
    def aliases(self) -> dict[str, Alias]:
        """Aliases defined in this class."""
    
    def mro(self) -> list[Class]:
        """
        Get the method resolution order.
        
        Returns:
            list[Class]: Classes in MRO order
        """
    
    def __getitem__(self, key: str) -> Object:
        """Get a member by name."""
    
    def __contains__(self, key: str) -> bool:
        """Check if class contains a member."""

Function Class

Represents a Python function or method with parameters and return information.

class Function(Object):
    """
    Class representing a Python function or method.
    
    Contains parameters, return annotations, decorators, and docstrings.
    Supports both regular functions and class methods.
    """
    
    def __init__(
        self,
        name: str,
        *,
        parameters: Parameters | None = None,
        returns: Expr | None = None,
        decorators: list[Decorator] | None = None,
        **kwargs: Any,
    ) -> None:
        """
        Initialize the function.
        
        Args:
            name: Function name
            parameters: Function parameters
            returns: Return annotation expression
            decorators: Applied decorators
            **kwargs: Additional Object parameters
        """
    
    @property
    def parameters(self) -> Parameters:
        """Function parameters."""
    
    @property
    def returns(self) -> Expr | None:
        """Return type annotation."""
    
    @property
    def decorators(self) -> list[Decorator]:
        """Decorators applied to this function."""
    
    @property
    def signature(self) -> str:
        """
        Get the function signature as a string.
        
        Returns:
            str: Function signature
        """
    
    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        """
        Call the function if it's available at runtime.
        
        Args:
            *args: Positional arguments
            **kwargs: Keyword arguments
            
        Returns:
            Any: Function return value
            
        Raises:
            RuntimeError: If function is not callable
        """

Attribute Class

Represents a module, class, or instance attribute.

class Attribute(Object):
    """
    Class representing a Python attribute.
    
    Stores attribute values, type annotations, and metadata for
    module-level variables, class attributes, and instance variables.
    """
    
    def __init__(
        self,
        name: str,
        *,
        annotation: Expr | None = None,
        value: Expr | None = None,
        **kwargs: Any,
    ) -> None:
        """
        Initialize the attribute.
        
        Args:
            name: Attribute name
            annotation: Type annotation expression
            value: Value expression
            **kwargs: Additional Object parameters
        """
    
    @property
    def annotation(self) -> Expr | None:
        """Type annotation expression."""
    
    @property
    def value(self) -> Expr | None:
        """Attribute value expression."""
    
    @property
    def has_type(self) -> bool:
        """Whether the attribute has a type annotation."""
    
    @property
    def has_value(self) -> bool:
        """Whether the attribute has a value."""

Alias Class

Represents an alias or import reference to an object in another module.

class Alias(Object):
    """
    Class representing an alias or indirection to an object.
    
    Handles imported objects and references, providing resolution
    to the actual target objects when needed.
    """
    
    def __init__(
        self,
        name: str,
        target_path: str,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
    ) -> None:
        """
        Initialize the alias.
        
        Args:
            name: Alias name (local name)
            target_path: Path to target object
            lineno: Starting line number
            endlineno: Ending line number
        """
    
    @property
    def target_path(self) -> str:
        """Path to the target object."""
    
    @property
    def target(self) -> Object | None:
        """The resolved target object."""
    
    def resolve(self, *, external: bool | None = None) -> Object | None:
        """
        Resolve the alias to its target object.
        
        Args:
            external: Whether to resolve external references
            
        Returns:
            Object | None: The target object if resolvable
            
        Raises:
            AliasResolutionError: If alias cannot be resolved
            CyclicAliasError: If circular reference detected
        """
    
    @property
    def resolved(self) -> bool:
        """Whether the alias has been resolved."""

Supporting Classes

Decorator Class

Represents a decorator applied to functions or classes.

class Decorator:
    """
    Class representing a decorator applied to a function, method, or class.
    
    Stores decorator expressions and metadata about decorator usage.
    """
    
    def __init__(
        self,
        decorator: Expr,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
    ) -> None:
        """
        Initialize the decorator.
        
        Args:
            decorator: Decorator expression
            lineno: Starting line number
            endlineno: Ending line number
        """
    
    @property
    def value(self) -> Expr:
        """The decorator expression."""
    
    @property
    def lineno(self) -> int | None:
        """Starting line number."""
    
    @property
    def endlineno(self) -> int | None:
        """Ending line number."""

Parameter and Parameters Classes

Represent function parameters and parameter collections.

class Parameter:
    """
    Class representing a function parameter.
    
    Includes name, annotation, default value, and parameter kind.
    """
    
    def __init__(
        self,
        name: str,
        *,
        annotation: Expr | None = None,
        default: Expr | None = None,
        kind: ParameterKind = ParameterKind.POSITIONAL_OR_KEYWORD,
    ) -> None:
        """
        Initialize the parameter.
        
        Args:
            name: Parameter name
            annotation: Type annotation
            default: Default value expression
            kind: Parameter kind (positional, keyword-only, etc.)
        """
    
    @property
    def name(self) -> str:
        """Parameter name."""
    
    @property
    def annotation(self) -> Expr | None:
        """Type annotation expression."""
    
    @property
    def default(self) -> Expr | None:
        """Default value expression."""
    
    @property
    def kind(self) -> ParameterKind:
        """Parameter kind."""
    
    @property
    def required(self) -> bool:
        """Whether parameter is required (no default)."""

class Parameters:
    """
    Container class for function parameters.
    
    Allows accessing parameters by position or name and provides
    iteration over parameter collections.
    """
    
    def __init__(self, *parameters: Parameter) -> None:
        """
        Initialize parameters collection.
        
        Args:
            *parameters: Parameter objects
        """
    
    def __iter__(self) -> Iterator[Parameter]:
        """Iterate over parameters."""
    
    def __getitem__(self, key: int | str) -> Parameter:
        """
        Get parameter by index or name.
        
        Args:
            key: Parameter index or name
            
        Returns:
            Parameter: The requested parameter
        """
    
    def __len__(self) -> int:
        """Number of parameters."""
    
    @property
    def signature(self) -> str:
        """
        Get parameters as signature string.
        
        Returns:
            str: Parameter signature
        """

Docstring Class

Represents and parses docstrings with structured content.

class Docstring:
    """
    Class representing docstrings.
    
    Provides parsing capabilities and access to structured
    docstring content including sections and elements.
    """
    
    def __init__(
        self,
        value: str,
        *,
        lineno: int | None = None,
        endlineno: int | None = None,
        parent: Object | None = None,
    ) -> None:
        """
        Initialize the docstring.
        
        Args:
            value: Raw docstring text
            lineno: Starting line number
            endlineno: Ending line number
            parent: Parent object containing this docstring
        """
    
    @property
    def value(self) -> str:
        """Raw docstring text."""
    
    @property
    def lineno(self) -> int | None:
        """Starting line number."""
    
    @property
    def endlineno(self) -> int | None:
        """Ending line number."""
    
    def parse(
        self,
        parser: Parser | str | None = None,
        **options: Any,
    ) -> list[DocstringSection]:
        """
        Parse the docstring into structured sections.
        
        Args:
            parser: Parser to use (auto, google, numpy, sphinx)
            **options: Parser-specific options
            
        Returns:
            list[DocstringSection]: Parsed sections
        """

Usage Examples

Working with Modules

import griffe

# Load a module
module = griffe.load("requests")

# Access module properties
print(f"Module: {module.name}")
print(f"Path: {module.path}")
print(f"File: {module.filepath}")

# Iterate through classes
for class_name, class_obj in module.classes.items():
    print(f"Class: {class_name}")
    print(f"  Methods: {list(class_obj.methods.keys())}")
    
# Access specific objects
session_class = module["Session"]  # Get Session class
get_function = module["get"]       # Get get function

Analyzing Functions

import griffe

# Load a specific function
func = griffe.load("requests.api.get")

print(f"Function: {func.name}")
print(f"Signature: {func.signature}")

# Examine parameters
for param in func.parameters:
    print(f"Parameter: {param.name}")
    print(f"  Type: {param.annotation}")
    print(f"  Default: {param.default}")
    print(f"  Required: {param.required}")

# Check return type
if func.returns:
    print(f"Returns: {func.returns}")

Working with Classes

import griffe

# Load a class
cls = griffe.load("requests.Session")

print(f"Class: {cls.name}")
print(f"Base classes: {[str(base) for base in cls.bases]}")

# Examine methods
for method_name, method in cls.methods.items():
    print(f"Method: {method_name}")
    print(f"  Signature: {method.signature}")
    
# Check for specific decorators
for method in cls.methods.values():
    for decorator in method.decorators:
        if "property" in str(decorator.value):
            print(f"Property method: {method.name}")

Resolving Aliases

import griffe

# Load module with imports
module = griffe.load("requests")

# Find aliases (imports)
for alias_name, alias in module.aliases.items():
    print(f"Alias: {alias_name} -> {alias.target_path}")
    
    # Resolve to actual object
    target = alias.resolve()
    if target:
        print(f"  Resolved to: {target.path}")
        print(f"  Type: {type(target).__name__}")

Types

from pathlib import Path
from typing import Any, Iterator
from enum import Enum

class ParameterKind(Enum):
    """Parameter kinds matching Python's inspect module."""
    POSITIONAL_ONLY = 0
    POSITIONAL_OR_KEYWORD = 1  
    VAR_POSITIONAL = 2
    KEYWORD_ONLY = 3
    VAR_KEYWORD = 4

class Kind(Enum):
    """Object kinds."""
    MODULE = "module"
    CLASS = "class"
    FUNCTION = "function" 
    ATTRIBUTE = "attribute"
    ALIAS = "alias"

# Expression type (defined in expressions module)
class Expr:
    """Base expression class."""

# Docstring section type (defined in docstrings module)  
class DocstringSection:
    """Base docstring section class."""

Install with Tessl CLI

npx tessl i tessl/pypi-griffe

docs

agents.md

breaking-changes.md

cli.md

docstrings.md

extensions.md

index.md

loaders.md

models.md

serialization.md

tile.json