Skip to content

Class

Class

Class(cls, init=True, public=True, inherited=True, static_methods=True, protected=False, private=False, classmethod=True, skip_self=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
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 str | None

The docstring of the class if it exists, otherwise None.

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,
    init=True,
    public=True,
    inherited=True,
    static_methods=True,
    protected=False,
    private=False,
    classmethod=True,
    skip_self=True,
) -> None:
    self.cls = cls
    self.is_initialized = False
    self.skip_self = skip_self
    self.receieved_instance = False

    try:
        self.name: str = self.cls.__name__
    except AttributeError:
        self.receieved_instance = True
        self.name = f"{self.cls.__class__.__name__} instance"
        self.is_initialized = True

    self.instance = None if not self.is_initialized else self.cls
    self.docstring = inspect.getdoc(self.cls)
    self.has_docstring = _has_docstr(self.docstring)
    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
    self._parsed_docstring = (
        docstring_parser.parse(self.docstring) if self.has_docstring else None  # type: ignore
    )
    self.description = _get_docstr_desc(self._parsed_docstring)

methods property

methods: list[Method]

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

init

init(*args, **kwargs) -> 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, **kwargs) -> 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")
    self.instance = self.cls(*args, **kwargs)
    self.is_initialized = True

call_method

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

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

Positional arguments to pass to the method.

()
**kwargs

Keyword arguments to pass to the method.

{}

Returns:

Name Type Description
Any Any

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, **kwargs) -> Any:
    """
    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:
        raise ValueError(f"Class {self.cls} is not initialized")
    if self.receieved_instance:
        return method_obj.call(*args, **kwargs)
    return method_obj.call(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))

split_init_args

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

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, cls: Class, method: Method) -> tuple[dict, dict]:
    """
    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