Skip to content

Class

Class

Class(cls: type | object, init: bool = True, public: bool = True, inherited: bool = True, static_methods: bool = True, protected: bool = False, private: bool = False, classmethod: bool = True, skip_self: bool = True)

Wraps a class or class instance and provides information about its methods.

Parameters:

Name Type Description Default
cls type or object

The class or class instance to wrap.

required
init bool

Include the class's init method.

True
public bool

Include public methods.

True
inherited bool

Include inherited methods.

True
static_methods bool

Include static methods.

True
classmethod bool

Include class methods.

True
protected bool

Include protected methods.

False
private bool

Include private methods.

False

Attributes:

Name Type Description
cls type or object

The class or class instance that was passed as an argument.

is_initialized bool

Whether the class has been initialized as an instance.

name str

The name of the class.

instance object | None

The instance of the class if it has been initialized, otherwise None.

docstring Docstring | None

The parsed docstring object.

docstring_text str | None

The raw docstring text.

has_docstring bool

Whether the class has a docstring.

extractor_kwargs dict

The keyword arguments used to initialize the MethodExtractor object.

has_init bool

Whether the class has an init method.

description str

The description of the class from its docstring.

Source code in objinspect/_class.py
def __init__(
    self,
    cls: type | object,
    init: bool = True,
    public: bool = True,
    inherited: bool = True,
    static_methods: bool = True,
    protected: bool = False,
    private: bool = False,
    classmethod: bool = True,
    skip_self: bool = True,
) -> None:
    self.cls = cls
    self.skip_self = skip_self
    self.receieved_instance = not inspect.isclass(cls)

    if self.receieved_instance:
        self.is_initialized = True
        self.instance = cls
        self.name = f"{cls.__class__.__name__} instance"
    else:
        self.is_initialized = False
        self.instance = None
        self.name = getattr(cls, "__name__", str(cls))

    self.docstring_text: str | None = inspect.getdoc(self.cls)
    self.has_docstring = has_docstr(self.docstring_text)
    self.extractor_kwargs = {
        "init": init,
        "public": public,
        "inherited": inherited,
        "static_methods": static_methods,
        "protected": protected,
        "private": private,
        "classmethod": classmethod,
    }
    self._methods = self._find_methods()
    self.has_init = "__init__" in self._methods
    if self.has_docstring and self.docstring_text is not None:
        self.docstring: Docstring | None = docstring_parser.parse(self.docstring_text)
    else:
        self.docstring = None

    self.description = get_docstr_description(self.docstring)

init_method property

init_method: Method | None

The init method of the class, or None if not present.

init_args property

init_args: list[Parameter] | None

The parameters of the init method, or None if not present.

methods property

methods: list[Method]

Returns the list of methods of the class or instance as a list of :class:Function objects.

dict property

dict: dict[str, object]

Return a dictionary representation of the class.

init

init(*args: RuntimeValue, **kwargs: RuntimeValue) -> None

Initializes the class as an instance using the provided arguments.

Raises:

Type Description
ValueError

If the class is already initialized.

Source code in objinspect/_class.py
def init(self, *args: RuntimeValue, **kwargs: RuntimeValue) -> None:
    """
    Initializes the class as an instance using the provided arguments.

    Raises:
        ValueError: If the class is already initialized.

    """
    if self.is_initialized:
        raise ValueError(f"Class {self.cls} is already initialized")

    if callable(self.cls):
        self.instance = self.cls(*args, **kwargs)
    else:
        raise TypeError(f"Cannot initialize object of type {type(self.cls)}")

    self.is_initialized = True

call_method

call_method(method: str | int, *args: RuntimeValue, **kwargs: RuntimeValue) -> RuntimeValue

Calls the specified method on the class or instance.

Parameters:

Name Type Description Default
method str | int

The name or index of the method to call.

required
*args RuntimeValue

Positional arguments to pass to the method.

()
**kwargs RuntimeValue

Keyword arguments to pass to the method.

{}

Returns:

Name Type Description
Any RuntimeValue

The result of calling the specified method.

Raises:

Type Description
ValueError

If the class has not been initialized.

Source code in objinspect/_class.py
def call_method(
    self,
    method: str | int,
    *args: RuntimeValue,
    **kwargs: RuntimeValue,
) -> RuntimeValue:
    """
    Calls the specified method on the class or instance.

    Args:
        method (str | int): The name or index of the method to call.
        *args: Positional arguments to pass to the method.
        **kwargs: Keyword arguments to pass to the method.

    Returns:
        Any: The result of calling the specified method.

    Raises:
        ValueError: If the class has not been initialized.
    """
    method_obj = self.get_method(method)
    if not self.is_initialized and not (method_obj.is_static or method_obj.is_classmethod):
        raise ValueError(f"Class {self.cls} is not initialized")
    if self.receieved_instance:
        return method_obj.call(*args, **kwargs)
    if method_obj.is_static or method_obj.is_classmethod:
        return method_obj.call(*args, **kwargs)

    return method_obj.call(self.instance, *args, **kwargs)

call_method_async async

call_method_async(method: str | int, *args: RuntimeValue, **kwargs: RuntimeValue) -> RuntimeValue

Call the specified method and await its result when needed.

Parameters:

Name Type Description Default
method str | int

The name or index of the method to call.

required
*args RuntimeValue

Positional arguments to pass to the method.

()
**kwargs RuntimeValue

Keyword arguments to pass to the method.

{}

Returns:

Name Type Description
Any RuntimeValue

The result of calling the specified method.

Raises:

Type Description
ValueError

If the class has not been initialized.

Source code in objinspect/_class.py
async def call_method_async(
    self,
    method: str | int,
    *args: RuntimeValue,
    **kwargs: RuntimeValue,
) -> RuntimeValue:
    """
    Call the specified method and await its result when needed.

    Args:
        method (str | int): The name or index of the method to call.
        *args: Positional arguments to pass to the method.
        **kwargs: Keyword arguments to pass to the method.

    Returns:
        Any: The result of calling the specified method.

    Raises:
        ValueError: If the class has not been initialized.
    """
    method_obj = self.get_method(method)
    if not self.is_initialized and not (method_obj.is_static or method_obj.is_classmethod):
        raise ValueError(f"Class {self.cls} is not initialized")
    if self.receieved_instance:
        return await method_obj.call_async(*args, **kwargs)
    if method_obj.is_static or method_obj.is_classmethod:
        return await method_obj.call_async(*args, **kwargs)

    return await method_obj.call_async(self.instance, *args, **kwargs)

get_method

get_method(method: str | int) -> Method

Retrieves a method from the list of methods of the class or instance.

Parameters:

Name Type Description Default
method str | int

The method name or index to retrieve.

required

Returns:

Name Type Description
Method Method

The Method object representing the requested method.

Source code in objinspect/_class.py
def get_method(self, method: str | int) -> Method:
    """
    Retrieves a method from the list of methods of the class or instance.

    Args:
        method (str | int): The method name or index to retrieve.

    Returns:
        Method: The `Method` object representing the requested method.
    """
    match method:
        case str():
            return self._methods[method]
        case int():
            return self.methods[method]
        case _:
            raise TypeError(type(method))

as_str

as_str(*, color: bool = True, indent: int = 2, theme: ClassStrTheme | None = None) -> str

Return a string representation of the class.

Parameters:

Name Type Description Default
color bool

Whether to colorize the output. Defaults to True.

True
indent int

Indentation width for methods. Defaults to 2.

2
theme ClassStrTheme | None

Color theme to use. Default will be used if None.

None
Source code in objinspect/_class.py
def as_str(
    self,
    *,
    color: bool = True,
    indent: int = 2,
    theme: ClassStrTheme | None = None,
) -> str:
    """
    Return a string representation of the class.

    Args:
        color (bool, optional): Whether to colorize the output. Defaults to True.
        indent (int, optional): Indentation width for methods. Defaults to 2.
        theme (ClassStrTheme | None): Color theme to use. Default will be used if
            None.
    """
    if theme is None:
        theme = ClassStrTheme()

    string: str
    if color:
        string = colored("class", theme.class_kw) + " " + colored(self.name, theme.name) + ":"
    else:
        string = f"class {self.name}:"

    if self.description:
        if color:
            string += "\n" + colored(self.description, theme.description)
        else:
            string += "\n" + str(self.description)

    if not len(self.methods):
        return string

    string += "\n"
    string += "\n".join([" " * indent + method.as_str(color=color) for method in self.methods])

    return string

split_init_args

split_init_args(args: dict[str, RuntimeValue], cls: Class, method: Method) -> tuple[dict[str, RuntimeValue], dict[str, RuntimeValue]]

Split the arguments into those that should be passed to the init method and those that should be passed to the method call.

Source code in objinspect/_class.py
def split_init_args(
    args: dict[str, RuntimeValue],
    cls: Class,
    method: Method,
) -> tuple[dict[str, RuntimeValue], dict[str, RuntimeValue]]:
    """
    Split the arguments into those that should be passed to the __init__ method
    and those that should be passed to the method call.
    """
    if not method.is_static and cls.has_init:
        init_method = cls.get_method("__init__")
        init_arg_names = [i.name for i in init_method.params]
        args_init = {k: v for k, v in args.items() if k in init_arg_names}
        args_method = {k: v for k, v in args.items() if k not in init_arg_names}

        return args_init, args_method

    return {}, args