Skip to content

inspect (13)

get_annotations

get_annotations(obj, *, globals=None, locals=None, eval_str=False, format=<Format.VALUE: 1>)

Compute the annotations dict for an object.

Example

Jinja call:

{{ filters.get_annotations | get_annotations }}
Result: {}

DocStrings
Source code in python3.14/annotationlib.py
def get_annotations(
    obj, *, globals=None, locals=None, eval_str=False, format=Format.VALUE
):
    """Compute the annotations dict for an object.

    obj may be a callable, class, module, or other object with
    __annotate__ or __annotations__ attributes.
    Passing any other object raises TypeError.

    The *format* parameter controls the format in which annotations are returned,
    and must be a member of the Format enum or its integer equivalent.
    For the VALUE format, the __annotations__ is tried first; if it
    does not exist, the __annotate__ function is called. The
    FORWARDREF format uses __annotations__ if it exists and can be
    evaluated, and otherwise falls back to calling the __annotate__ function.
    The STRING format tries __annotate__ first, and falls back to
    using __annotations__, stringified using annotations_to_string().

    This function handles several details for you:

      * If eval_str is true, values of type str will
        be un-stringized using eval().  This is intended
        for use with stringized annotations
        ("from __future__ import annotations").
      * If obj doesn't have an annotations dict, returns an
        empty dict.  (Functions and methods always have an
        annotations dict; classes, modules, and other types of
        callables may not.)
      * Ignores inherited annotations on classes.  If a class
        doesn't have its own annotations dict, returns an empty dict.
      * All accesses to object members and dict values are done
        using getattr() and dict.get() for safety.
      * Always, always, always returns a freshly-created dict.

    eval_str controls whether or not values of type str are replaced
    with the result of calling eval() on those values:

      * If eval_str is true, eval() is called on values of type str.
      * If eval_str is false (the default), values of type str are unchanged.

    globals and locals are passed in to eval(); see the documentation
    for eval() for more information.  If either globals or locals is
    None, this function may replace that value with a context-specific
    default, contingent on type(obj):

      * If obj is a module, globals defaults to obj.__dict__.
      * If obj is a class, globals defaults to
        sys.modules[obj.__module__].__dict__ and locals
        defaults to the obj class namespace.
      * If obj is a callable, globals defaults to obj.__globals__,
        although if obj is a wrapped function (using
        functools.update_wrapper()) it is first unwrapped.
    """
    if eval_str and format != Format.VALUE:
        raise ValueError("eval_str=True is only supported with format=Format.VALUE")

    match format:
        case Format.VALUE:
            # For VALUE, we first look at __annotations__
            ann = _get_dunder_annotations(obj)

            # If it's not there, try __annotate__ instead
            if ann is None:
                ann = _get_and_call_annotate(obj, format)
        case Format.FORWARDREF:
            # For FORWARDREF, we use __annotations__ if it exists
            try:
                ann = _get_dunder_annotations(obj)
            except Exception:
                pass
            else:
                if ann is not None:
                    return dict(ann)

            # But if __annotations__ threw a NameError, we try calling __annotate__
            ann = _get_and_call_annotate(obj, format)
            if ann is None:
                # If that didn't work either, we have a very weird object: evaluating
                # __annotations__ threw NameError and there is no __annotate__. In that case,
                # we fall back to trying __annotations__ again.
                ann = _get_dunder_annotations(obj)
        case Format.STRING:
            # For STRING, we try to call __annotate__
            ann = _get_and_call_annotate(obj, format)
            if ann is not None:
                return dict(ann)
            # But if we didn't get it, we use __annotations__ instead.
            ann = _get_dunder_annotations(obj)
            if ann is not None:
                return annotations_to_string(ann)
        case Format.VALUE_WITH_FAKE_GLOBALS:
            raise ValueError("The VALUE_WITH_FAKE_GLOBALS format is for internal use only")
        case _:
            raise ValueError(f"Unsupported format {format!r}")

    if ann is None:
        if isinstance(obj, type) or callable(obj):
            return {}
        raise TypeError(f"{obj!r} does not have annotations")

    if not ann:
        return {}

    if not eval_str:
        return dict(ann)

    if globals is None or locals is None:
        if isinstance(obj, type):
            # class
            obj_globals = None
            module_name = getattr(obj, "__module__", None)
            if module_name:
                module = sys.modules.get(module_name, None)
                if module:
                    obj_globals = getattr(module, "__dict__", None)
            obj_locals = dict(vars(obj))
            unwrap = obj
        elif isinstance(obj, types.ModuleType):
            # module
            obj_globals = getattr(obj, "__dict__")
            obj_locals = None
            unwrap = None
        elif callable(obj):
            # this includes types.Function, types.BuiltinFunctionType,
            # types.BuiltinMethodType, functools.partial, functools.singledispatch,
            # "class funclike" from Lib/test/test_inspect... on and on it goes.
            obj_globals = getattr(obj, "__globals__", None)
            obj_locals = None
            unwrap = obj
        else:
            obj_globals = obj_locals = unwrap = None

        if unwrap is not None:
            # Use an id-based visited set to detect cycles in the __wrapped__
            # and functools.partial.func chain (e.g. f.__wrapped__ = f).
            # On cycle detection we stop and use whatever __globals__ we have
            # found so far, mirroring the approach of inspect.unwrap().
            _seen_ids = {id(unwrap)}
            while True:
                if hasattr(unwrap, "__wrapped__"):
                    candidate = unwrap.__wrapped__
                    if id(candidate) in _seen_ids:
                        break
                    _seen_ids.add(id(candidate))
                    unwrap = candidate
                    continue
                if functools := sys.modules.get("functools"):
                    if isinstance(unwrap, functools.partial):
                        candidate = unwrap.func
                        if id(candidate) in _seen_ids:
                            break
                        _seen_ids.add(id(candidate))
                        unwrap = candidate
                        continue
                break
            if hasattr(unwrap, "__globals__"):
                obj_globals = unwrap.__globals__

        if globals is None:
            globals = obj_globals
        if locals is None:
            locals = obj_locals

    # "Inject" type parameters into the local namespace
    # (unless they are shadowed by assignments *in* the local namespace),
    # as a way of emulating annotation scopes when calling `eval()`
    if type_params := getattr(obj, "__type_params__", ()):
        if locals is None:
            locals = {}
        locals = {param.__name__: param for param in type_params} | locals

    return_value = {
        key: value if not isinstance(value, str)
        else eval(_rewrite_star_unpack(value), globals, locals)
        for key, value in ann.items()
    }
    return return_value

get_argspec

get_argspec(obj: Any, remove_self: bool = True) -> inspect.FullArgSpec

Return a cleaned-up FullArgSpec for given callable.

Example

Jinja call:

{{ filters.get_argspec | get_argspec }}
Result: FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'return': typing.Any, 'args': typing.Any, 'kwargs': typing.Any})

DocStrings

Parameters:

Name Type Description Default
obj Any

A callable python object

required
remove_self bool

Whether to remove "self" argument from method argspecs

True
Source code in src/jinjarope/inspectfilters.py
def get_argspec(obj: Any, remove_self: bool = True) -> inspect.FullArgSpec:
    """Return a cleaned-up FullArgSpec for given callable.

    ArgSpec is cleaned up by removing `self` from method callables.

    Args:
        obj: A callable python object
        remove_self: Whether to remove "self" argument from method argspecs
    """
    if inspect.isfunction(obj):
        argspec = inspect.getfullargspec(obj)
    elif inspect.ismethod(obj):
        argspec = inspect.getfullargspec(obj)
        if remove_self:
            del argspec.args[0]
    elif inspect.isclass(obj):
        if obj.__init__ is object.__init__:  # to avoid an error
            argspec = inspect.getfullargspec(lambda self: None)
        else:
            argspec = inspect.getfullargspec(obj.__init__)
        if remove_self:
            del argspec.args[0]
    elif callable(obj):
        argspec = inspect.getfullargspec(obj.__call__)
        if remove_self:
            del argspec.args[0]
    else:
        msg = f"{obj} is not callable"
        raise TypeError(msg)
    return argspec

get_deprecated_message

get_deprecated_message(obj: Any) -> str | None

Return deprecated message (created by deprecated decorator).

DocStrings

Parameters:

Name Type Description Default
obj Any

Object to check

required
Source code in src/jinjarope/inspectfilters.py
def get_deprecated_message(obj: Any) -> str | None:
    """Return deprecated message (created by deprecated decorator).

    Args:
        obj: Object to check
    """
    return obj.__deprecated__ if hasattr(obj, "__deprecated__") else None

get_doc

get_doc(obj: Any, *, escape: bool = False, fallback: str = '', from_base_classes: bool = False, only_summary: bool = False, only_description: bool = False) -> str

Get doc for given object.

Example

Jinja call:

{{ filters.get_doc | get_doc }}
Result: `get_doc filter: docstrings are data, the page's Jinja pass must not render them.`

DocStrings

Parameters:

Name Type Description Default
obj Any

Object to get docstrings from, or import path string (supports both "module.path:object" and "module.path.object")

required
escape bool

Whether docstrings should get escaped

False
fallback str

Fallback in case docstrings dont exist

''
from_base_classes bool

Use base class docstrings if docstrings dont exist

False
only_summary bool

Only return first line of docstrings

False
only_description bool

Only return block after first line

False
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def get_doc(
    obj: Any,
    *,
    escape: bool = False,
    fallback: str = "",
    from_base_classes: bool = False,
    only_summary: bool = False,
    only_description: bool = False,
) -> str:
    """Get __doc__ for given object.

    Args:
        obj: Object to get docstrings from, or import path string
            (supports both "module.path:object" and "module.path.object")
        escape: Whether docstrings should get escaped
        fallback: Fallback in case docstrings dont exist
        from_base_classes: Use base class docstrings if docstrings dont exist
        only_summary: Only return first line of docstrings
        only_description: Only return block after first line
    """
    from jinjarope import mdfilters

    # Handle string import paths
    if isinstance(obj, str):
        # Try colon notation first (module.path:object)
        if ":" in obj:
            module_path, obj_name = obj.rsplit(":", 1)
            try:
                module = importlib.import_module(module_path)
                obj = getattr(module, obj_name)
            except (ImportError, AttributeError) as e:
                logger.debug(f"Failed to import {obj}: {e}")  # noqa: G004
                return fallback
        else:
            # Try dot notation (module.path.object)
            parts = obj.rsplit(".", 1)
            if len(parts) == 2:  # noqa: PLR2004
                module_path, obj_name = parts
                try:
                    module = importlib.import_module(module_path)
                    obj = getattr(module, obj_name)
                except ImportError, AttributeError:
                    # Maybe the whole thing is a module?
                    try:
                        obj = importlib.import_module(obj)
                    except ImportError as e:
                        logger.debug(f"Failed to import {obj}: {e}")  # noqa: G004
                        return fallback
            else:
                # Just a module name
                try:
                    obj = importlib.import_module(obj)
                except ImportError as e:
                    logger.debug(f"Failed to import {obj}: {e}")  # noqa: G004
                    return fallback

    match obj:
        case _ if from_base_classes:
            doc = inspect.getdoc(obj)
        case _ if obj.__doc__:
            doc = inspect.cleandoc(obj.__doc__)
        case _:
            doc = None
    if not doc:
        return fallback
    if only_summary:
        doc = doc.split("\n")[0]
    if only_description:
        doc = "\n".join(doc.split("\n")[1:])
    return mdfilters.md_escape(doc) if doc and escape else doc

get_file

get_file(obj: module | type | method | function | traceback | frame | code | collections.abc.Callable[..., Any]) -> pathlib.Path | None

Cached wrapper for inspect.getfile.

Example

Jinja call:

{{ filters.get_file | get_file }}
Result: None

DocStrings

Parameters:

Name Type Description Default
obj HasCodeType

Object to get file for

required
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def get_file(obj: HasCodeType) -> pathlib.Path | None:
    """Cached wrapper for inspect.getfile.

    Args:
        obj: Object to get file for
    """
    with contextlib.suppress(TypeError):
        return pathlib.Path(inspect.getfile(obj))
    return None

get_signature

get_signature(obj: collections.abc.Callable[..., typing.Any]) -> inspect.Signature

Cached wrapper for inspect.signature.

Example

Jinja call:

{{ filters.get_signature | get_signature }}
Result: (obj: collections.abc.Callable[..., typing.Any]) -> inspect.Signature

DocStrings

Parameters:

Name Type Description Default
obj Callable[..., Any]

Callable to get a signature for.

required
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def get_signature(obj: Callable[..., Any]) -> inspect.Signature:
    """Cached wrapper for inspect.signature.

    Args:
        obj: Callable to get a signature for.
    """
    try:
        return inspect.signature(obj)
    except NameError:  # annotation names imported only under TYPE_CHECKING (PEP 649)
        return inspect.signature(obj, annotation_format=annotationlib.Format.STRING)

get_source

get_source(obj: module | type | method | function | traceback | frame | code | collections.abc.Callable[..., Any]) -> str

Cached wrapper for inspect.getsource.

Example

Jinja call:

{{ filters.get_source | get_source }}
Result: `@functools.cache def get_source(obj: HasCodeType) -> str: """Cached wrapper for inspect.getsource.

Args:
    obj: Object to return source for.
"""
return inspect.getsource(obj)

`

DocStrings

Parameters:

Name Type Description Default
obj HasCodeType

Object to return source for.

required
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def get_source(obj: HasCodeType) -> str:
    """Cached wrapper for inspect.getsource.

    Args:
        obj: Object to return source for.
    """
    return inspect.getsource(obj)

get_source_lines

get_source_lines(obj: module | type | method | function | traceback | frame | code | collections.abc.Callable[..., Any]) -> tuple[list[str], int]

Cached wrapper for inspect.getsourcelines.

Example

Jinja call:

{{ filters.get_source_lines | get_source_lines }}
Result: (['@functools.cache\n', 'def get_source_lines(obj: HasCodeType) -> tuple[list[str], int]:\n', ' """Cached wrapper for inspect.getsourcelines.\n', '\n', ' Args:\n', ' obj: Object to return source lines for.\n', ' """\n', ' return inspect.getsourcelines(obj)\n'], 297)

DocStrings

Parameters:

Name Type Description Default
obj HasCodeType

Object to return source lines for.

required
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def get_source_lines(obj: HasCodeType) -> tuple[list[str], int]:
    """Cached wrapper for inspect.getsourcelines.

    Args:
        obj: Object to return source lines for.
    """
    return inspect.getsourcelines(obj)

get_structure_map

get_structure_map(obj: os.PathLike[str] | str, *, show_types: bool = True, show_line_numbers: bool = False, show_decorators: bool = True, sort_alphabetically: bool = False, include_private: bool = True, include_dunder: bool = False, max_depth: int | None = None, use_unicode: bool = True) -> str

Generate a textual tree representation of Python code structure.

Example

Jinja call:

{{ "jinjarope.codetree" | import_module | get_structure_map }}
Result:
└── jinjarope.codetree (MODULE)
    ├── NodeType (CLASS)
    ├── Node (CLASS) [@dataclass]
    ├── TreeOptions (CLASS) [@dataclass]
    │   └── symbols (PROPERTY) [@property]
    ├── _get_decorator_names (FUNCTION)
    ├── _should_include_node (FUNCTION)
    ├── parse_object (FUNCTION)
    ├── generate_tree (FUNCTION)
    └── get_structure_map (FUNCTION)

DocStrings

Parameters:

Name Type Description Default
obj PathLike[str] | str

Path to the Python source file or a Python object

required
show_types bool

Include node type annotations

True
show_line_numbers bool

Display source line numbers

False
show_decorators bool

Include decorator information

True
sort_alphabetically bool

Sort nodes by name

False
include_private bool

Include private members

True
include_dunder bool

Include double underscore methods

False
max_depth int | None

Maximum tree depth to display

None
use_unicode bool

Use Unicode characters for tree branches

True
Source code in src/jinjarope/codetree.py
def get_structure_map(
    obj: os.PathLike[str] | str,
    *,
    show_types: bool = True,
    show_line_numbers: bool = False,
    show_decorators: bool = True,
    sort_alphabetically: bool = False,
    include_private: bool = True,
    include_dunder: bool = False,
    max_depth: int | None = None,
    use_unicode: bool = True,
) -> str:
    """Generate a textual tree representation of Python code structure.

    Creates a visual tree showing the hierarchical structure of classes,
    methods, and functions in a Python file, with customizable display options.

    !!! tip
        Use `use_unicode=True` for better-looking trees in terminals
        that support Unicode characters.

    Args:
        obj: Path to the Python source file or a Python object
        show_types: Include node type annotations
        show_line_numbers: Display source line numbers
        show_decorators: Include decorator information
        sort_alphabetically: Sort nodes by name
        include_private: Include private members
        include_dunder: Include double underscore methods
        max_depth: Maximum tree depth to display
        use_unicode: Use Unicode characters for tree branches

    Example:
        ```python
        tree = get_structure_map(
            "myfile.py",
            show_types=False,
            show_line_numbers=True,
            sort_alphabetically=True
        )
        print(tree)
        ```
    """
    options = TreeOptions(
        show_types=show_types,
        show_line_numbers=show_line_numbers,
        show_decorators=show_decorators,
        sort_alphabetically=sort_alphabetically,
        include_private=include_private,
        include_dunder=include_dunder,
        max_depth=max_depth,
        branch_style="unicode" if use_unicode else "ascii",
    )

    root = parse_object(obj)
    return generate_tree(root, options)

getattr

getattr(obj: Any, name: str, *default: Any) -> Any

Return an attribute of an object (Python's getattr, as a filter).

Example

Jinja call:

{{ "jinjarope" | getattr("__class__") }}
Result: <class 'str'>

DocStrings

Parameters:

Name Type Description Default
obj Any

The object

required
name str

The attribute name

required
default Any

Value to return if the attribute doesn't exist (else AttributeError)

()
Source code in src/jinjarope/inspectfilters.py
def get_attribute(obj: Any, name: str, *default: Any) -> Any:
    """Return an attribute of an object (Python's `getattr`, as a filter).

    Also reaches attributes starting with an underscore, which minijinja hides from
    `obj.attr` (`{{ cls | getattr("__name__") }}` works with both engines).

    Args:
        obj: The object
        name: The attribute name
        default: Value to return if the attribute doesn't exist (else AttributeError)
    """
    return getattr(obj, name, *default)

iter_union_types

iter_union_types(union_type: Any, *, filter_none: bool = True) -> collections.abc.Iterator[type]

Iterate through all types in a Union.

Example

Jinja call:

{%- for typ in "str | int | None" | evaluate | iter_union_types -%}
{{ typ }}
{% endfor -%}
Result: <class 'str'> <class 'int'>

DocStrings

Parameters:

Name Type Description Default
union_type Any

A Union type (e.g., Union[A, B, C] or A | B | C)

required
filter_none bool

Whether to filter out NoneType from the results

True

Yields:

Type Description
type

Each type found in the union

Source code in src/jinjarope/inspectfilters.py
def iter_union_types(
    union_type: Any,
    *,
    filter_none: bool = True,
) -> Iterator[type]:
    """Iterate through all types in a Union.

    Handles unwrapping of Annotated types automatically.

    Args:
        union_type: A Union type (e.g., Union[A, B, C] or A | B | C)
        filter_none: Whether to filter out NoneType from the results

    Yields:
        Each type found in the union

    Example:
        >>> from typing import Union
        >>> for typ in iter_union_types(Union[str, int, None]):
        ...     print(typ)
        <class 'str'>
        <class 'int'>
    """
    # Unwrap Annotated if needed
    origin = get_origin(union_type)
    if origin is Annotated:
        # Get the actual type from Annotated[Union[...], ...]
        union_type = get_args(union_type)[0]
        origin = get_origin(union_type)

    # Check if it's a Union type
    if origin not in (Union, types.UnionType):
        msg = f"Expected Union type, got: {union_type}"
        raise TypeError(msg)

    # Get all types in the union
    union_args = get_args(union_type)

    for arg in union_args:
        if filter_none and arg is type(None):
            continue
        yield arg

list_baseclasses

list_baseclasses(klass: type, *, recursive: bool = True, filter_abstract: bool = False, filter_generic: bool = True, filter_locals: bool = True) -> list[type]

Return list of all baseclasses of given klass.

Example

Jinja call:

{{ zip | list_baseclasses }}
Result: [<class 'object'>]

DocStrings

Parameters:

Name Type Description Default
klass type

class to get subclasses from

required
filter_abstract bool

whether abstract base classes should be included.

False
filter_generic bool

whether generic base classes should be included.

True
filter_locals bool

whether local base classes should be included.

True
recursive bool

whether to also get baseclasses of baseclasses.

True
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def list_baseclasses(
    klass: type,
    *,
    recursive: bool = True,
    filter_abstract: bool = False,
    filter_generic: bool = True,
    filter_locals: bool = True,
) -> list[type]:
    """Return list of all baseclasses of given klass.

    Args:
        klass: class to get subclasses from
        filter_abstract: whether abstract base classes should be included.
        filter_generic: whether generic base classes should be included.
        filter_locals: whether local base classes should be included.
        recursive: whether to also get baseclasses of baseclasses.
    """
    return list(
        iter_baseclasses(
            klass,
            recursive=recursive,
            filter_abstract=filter_abstract,
            filter_generic=filter_generic,
            filter_locals=filter_locals,
        ),
    )

list_subclasses

list_subclasses(klass: ClassType, *, recursive: bool = True, filter_abstract: bool = False, filter_generic: bool = True, filter_locals: bool = True) -> list[ClassType]

Return list of all subclasses of given klass.

Example

Jinja call:

{{ list | list_subclasses }}
Result: [<class '_frozen_importlib._List'>, <class 'traceback.StackSummary'>, <class 'email.header._Accumulator'>, <class 'fsspec.core.OpenFiles'>, <class 'markdown.blockparser.State'>, <class 'githarbor.core.datatypes.NiceReprList'>, <class 'git_changelog._internal.commit._Trailers'>, <class 'smmap.util.MapRegionList'>, <class 'gitdb.fun.TopdownDeltaChunkList'>, <class 'gitdb.fun.DeltaChunkList'>, <class 'gitdb.base.IStream'>, <class 'git.remote.PushInfoList'>, <class 'git.util.IterableList'>, <class 'git.diff.DiffIndex'>, <class 'git.refs.log.RefLog'>, <class 'mknodes.info.gitrepository.CommitList'>, <class 'unittest.mock._CallList'>, <class 'unittest.mock._AnyComparer'>, <class 'pydantic_ai._enqueue.PendingMessageQueue'>, <class 'pydantic_ai._enqueue.EnqueueGuard'>, <class 'pydantic_ai._run_context.EventStreamBuffer'>, <class 'pydantic_ai._run_context.RealtimeEventBuffer'>, <class 'pydantic_ai._history_mirroring.HistoryMirroringMessages'>, <class 'agentpool.messaging.messages.TeamResponse'>, <class 'agentpool.delegation.teamrun.ExtendedTeamTalk'>, <class 'agentpool.talk.talk.TeamTalk'>, <class 'socketserver._Threads'>, <class 'logging.config.ConvertingList'>, <class 'anthropic._models._EagerIterable'>]

DocStrings

Parameters:

Name Type Description Default
klass ClassType

class to get subclasses from

required
filter_abstract bool

whether abstract base classes should be included.

False
filter_generic bool

whether generic base classes should be included.

True
filter_locals bool

whether local base classes should be included.

True
recursive bool

whether to also get subclasses of subclasses.

True
Source code in src/jinjarope/inspectfilters.py
@functools.cache
def list_subclasses[ClassType: type](
    klass: ClassType,
    *,
    recursive: bool = True,
    filter_abstract: bool = False,
    filter_generic: bool = True,
    filter_locals: bool = True,
) -> list[ClassType]:
    """Return list of all subclasses of given klass.

    Note: This call is cached. Consider iter_subclasses for uncached iterating.

    Args:
        klass: class to get subclasses from
        filter_abstract: whether abstract base classes should be included.
        filter_generic: whether generic base classes should be included.
        filter_locals: whether local base classes should be included.
        recursive: whether to also get subclasses of subclasses.
    """
    return list(
        iter_subclasses(
            klass,
            recursive=recursive,
            filter_abstract=filter_abstract,
            filter_generic=filter_generic,
            filter_locals=filter_locals,
        ),
    )