Skip to content

util

call_method

call_method(obj: RuntimeValue, name: str, args: tuple[RuntimeValue, ...] = (), kwargs: dict[str, RuntimeValue] | None = None) -> RuntimeValue

Call a method with the given name on the given object.

Parameters:

Name Type Description Default
obj object

The object to call the method on.

required
name str

The name of the method to call.

required
args tuple

The positional arguments to pass to the method.

()
kwargs dict

The keyword arguments to pass to the method.

None

Returns:

Name Type Description
object RuntimeValue

The result of calling the method.

Example
>>> import math
>>> call_method(math, "pow", args=(2, 2))
4.0
Source code in objinspect/util.py
def call_method(
    obj: RuntimeValue,
    name: str,
    args: tuple[RuntimeValue, ...] = (),
    kwargs: dict[str, RuntimeValue] | None = None,
) -> RuntimeValue:
    """
    Call a method with the given name on the given object.

    Args:
        obj (object): The object to call the method on.
        name (str): The name of the method to call.
        args (tuple, optional): The positional arguments to pass to the method.
        kwargs (dict, optional): The keyword arguments to pass to the method.

    Returns:
        object: The result of calling the method.

    Example:
        ```python
        >>> import math
        >>> call_method(math, "pow", args=(2, 2))
        4.0
        ```
    """
    kwargs = kwargs or {}
    return getattr(obj, name)(*args, **kwargs)

call_method_async async

call_method_async(obj: RuntimeValue, name: str, args: tuple[RuntimeValue, ...] = (), kwargs: dict[str, RuntimeValue] | None = None) -> RuntimeValue

Call a method with the given name on the given object and await when needed.

Parameters:

Name Type Description Default
obj object

The object to call the method on.

required
name str

The name of the method to call.

required
args tuple

The positional arguments to pass to the method.

()
kwargs dict

The keyword arguments to pass to the method.

None

Returns:

Name Type Description
object RuntimeValue

The result of calling the method.

Source code in objinspect/util.py
async def call_method_async(
    obj: RuntimeValue,
    name: str,
    args: tuple[RuntimeValue, ...] = (),
    kwargs: dict[str, RuntimeValue] | None = None,
) -> RuntimeValue:
    """
    Call a method with the given name on the given object and await when needed.

    Args:
        obj (object): The object to call the method on.
        name (str): The name of the method to call.
        args (tuple, optional): The positional arguments to pass to the method.
        kwargs (dict, optional): The keyword arguments to pass to the method.

    Returns:
        object: The result of calling the method.
    """
    kwargs = kwargs or {}
    result = getattr(obj, name)(*args, **kwargs)
    if inspect.isawaitable(result):
        return await result

    return result

get_uninherited_methods

get_uninherited_methods(cls: type) -> list[str]

Get the methods of a class that are not inherited from its parent classes.

Source code in objinspect/util.py
def get_uninherited_methods(cls: type) -> list[str]:
    """Get the methods of a class that are not inherited from its parent classes."""
    return [
        name
        for name, method in cls.__dict__.items()
        if isinstance(method, (FunctionType, classmethod, staticmethod))
    ]

create_function

create_function(name: str, args: dict[str, ArgumentDef], body: str | list[str], globs: dict[str, RuntimeValue], return_type: TypeAnnotation = EMPTY, docstring: str | None = None) -> Callable[..., RuntimeValue]

Create a function with the given name, arguments, body, and globals.

Parameters:

Name Type Description Default
name str

The name of the function.

required
args dict

A dictionary mapping argument names to tuples of the argument type and default value.

required
body str | list

The body of the function. If a string, it will be split by newlines.

required
globs dict

The globals to use when executing the function.

required
return_type Any

The return type of the function.

EMPTY
docstring str

The docstring of the function.

None
Example
>>> add = create_function(
...     name="add",
...     args={
...         "a": (int, None),
...         "b": (int, 2),
...     },
...     body=[
...         "result = a + b",
...         "return result",
...          ],
...     docstring="Adds two numbers together. If b is not provided, defaults to 2.",
...     globs=globals(),
...   )
>>> add(2, 2)
4
Source code in objinspect/util.py
def create_function(
    name: str,
    args: dict[str, ArgumentDef],
    body: str | list[str],
    globs: dict[str, RuntimeValue],
    return_type: TypeAnnotation = EMPTY,
    docstring: str | None = None,
) -> Callable[..., RuntimeValue]:
    """
    Create a function with the given name, arguments, body, and globals.

    Args:
        name (str): The name of the function.
        args (dict): A dictionary mapping argument names to tuples of the argument type and default value.
        body (str | list): The body of the function. If a string, it will be split by newlines.
        globs (dict): The globals to use when executing the function.
        return_type (Any, optional): The return type of the function.
        docstring (str, optional): The docstring of the function.

    Example:
        ```python
        >>> add = create_function(
        ...     name="add",
        ...     args={
        ...         "a": (int, None),
        ...         "b": (int, 2),
        ...     },
        ...     body=[
        ...         "result = a + b",
        ...         "return result",
        ...          ],
        ...     docstring="Adds two numbers together. If b is not provided, defaults to 2.",
        ...     globs=globals(),
        ...   )
        >>> add(2, 2)
        4
        ```
    """
    func_str = _build_function_source(
        name=name,
        args=args,
        body=body,
        return_type=return_type,
        docstring=docstring,
    )
    code_obj = compile(func_str, "<string>", "exec")
    exec(code_obj, globs)  # noqa: S102  # required for runtime function definition
    func = globs[name]
    if not isinstance(func, FunctionType):
        raise TypeError(f"Expected generated function {name!r}, got {type(func)!r}")

    func.__annotations__ = {arg: annotation[0] for arg, annotation in args.items()}
    if return_type is not EMPTY:
        func.__annotations__["return"] = return_type

    return func

colored_type

colored_type(t: TypeAnnotation, style: TextStyle, simplify: bool = True) -> str

Return a colored string representation of a type.

Parameters:

Name Type Description Default
t type

The type to format.

required
style TextStyle

The text style (color) to apply.

required
simplify bool

Whether to simplify the type name. Defaults to True.

True
Source code in objinspect/util.py
def colored_type(
    t: TypeAnnotation,
    style: TextStyle,
    simplify: bool = True,
) -> str:
    """
    Return a colored string representation of a type.

    Args:
        t (type): The type to format.
        style (TextStyle): The text style (color) to apply.
        simplify (bool, optional): Whether to simplify the type name. Defaults to True.
    """
    text = type_name(t)
    if simplify:
        text = simplified_type_name(text)

    NO_COLOR_CHARS = "[](){}|,?"
    colored_segments: list[str] = []
    current_segment: list[str] = []
    for char in text:
        if char in NO_COLOR_CHARS:
            colored_segments.append(with_style("".join(current_segment), style))
            current_segment.clear()
            colored_segments.append(char)
        else:
            current_segment.append(char)

    colored_segments.append(with_style("".join(current_segment), style))

    return "".join(colored_segments)