Skip to content

importing

Class info

🛈 DocStrings

Utilities for importing callables and classes from dotted paths.

get_module_source

get_module_source(import_path: str, recursive: bool = False, include_tests: bool = False) -> str

Get source code from a module or package.

Source code in src/llmling/utils/importing.py
def get_module_source(
    import_path: str,
    recursive: bool = False,
    include_tests: bool = False,
) -> str:
    """Get source code from a module or package."""
    try:
        module = importlib.import_module(import_path)
        sources = _get_sources(module, recursive=recursive, include_tests=include_tests)
        return "\n\n# " + "-" * 40 + "\n\n".join(sources)

    except ImportError as exc:
        msg = f"Could not import module: {import_path}"
        raise ValueError(msg) from exc

get_pyobject_members

get_pyobject_members(
    obj: type | ModuleType | Any, *, include_imported: bool = False
) -> Iterator[tuple[str, Callable[..., Any]]]

Get callable members defined in a Python object.

Works with modules, classes, and instances. Only returns public callable members (functions, methods, etc.) that are defined in the object's module unless include_imported is True.

Parameters:

Name Type Description Default
obj type | ModuleType | Any

Any Python object to inspect (module, class, instance)

required
include_imported bool

Whether to include imported/inherited callables

False

Yields:

Type Description
tuple[str, Callable[..., Any]]

Tuples of (name, callable) for each public callable

Example

class MyClass: ... def method(self): pass ... def _private(self): pass for name, func in get_pyobject_members(MyClass()): ... print(name) method

import my_module for name, func in get_pyobject_members(my_module): ... print(name) public_function

Source code in src/llmling/utils/importing.py
def get_pyobject_members(
    obj: type | ModuleType | Any,
    *,
    include_imported: bool = False,
) -> Iterator[tuple[str, Callable[..., Any]]]:
    """Get callable members defined in a Python object.

    Works with modules, classes, and instances. Only returns public callable
    members (functions, methods, etc.) that are defined in the object's module
    unless include_imported is True.

    Args:
        obj: Any Python object to inspect (module, class, instance)
        include_imported: Whether to include imported/inherited callables

    Yields:
        Tuples of (name, callable) for each public callable

    Example:
        >>> class MyClass:
        ...     def method(self): pass
        ...     def _private(self): pass
        >>> for name, func in get_pyobject_members(MyClass()):
        ...     print(name)
        method

        >>> import my_module
        >>> for name, func in get_pyobject_members(my_module):
        ...     print(name)
        public_function
    """
    # Get the module where the object is defined
    defining_module = obj.__name__ if isinstance(obj, ModuleType) else obj.__module__

    for name, member in inspect.getmembers(obj, inspect.isroutine):
        if name.startswith("_"):
            continue

        # Check if callable is defined in the object's module
        if include_imported or getattr(member, "__module__", None) == defining_module:
            yield name, member

import_callable

import_callable(path: str) -> Callable[..., Any]

Import a callable from a dotted path.

Supports both dot and colon notation: - Dot notation: module.submodule.Class.method - Colon notation: module.submodule:Class.method

Examples:

>>> import_callable("os.path.join")
>>> import_callable("llmling.testing:processors.failing_processor")
>>> import_callable("builtins.str.upper")
>>> import_callable("sqlalchemy.orm:Session.query")

Parameters:

Name Type Description Default
path str

Import path using dots and/or colon

required

Returns:

Type Description
Callable[..., Any]

Imported callable

Raises:

Type Description
ValueError

If path cannot be imported or result isn't callable

Source code in src/llmling/utils/importing.py
def import_callable(path: str) -> Callable[..., Any]:
    """Import a callable from a dotted path.

    Supports both dot and colon notation:
    - Dot notation: module.submodule.Class.method
    - Colon notation: module.submodule:Class.method

    Examples:
        >>> import_callable("os.path.join")
        >>> import_callable("llmling.testing:processors.failing_processor")
        >>> import_callable("builtins.str.upper")
        >>> import_callable("sqlalchemy.orm:Session.query")

    Args:
        path: Import path using dots and/or colon

    Returns:
        Imported callable

    Raises:
        ValueError: If path cannot be imported or result isn't callable
    """
    if not path:
        msg = "Import path cannot be empty"
        raise ValueError(msg)

    # Normalize path - replace colon with dot if present
    normalized_path = path.replace(":", ".")
    parts = normalized_path.split(".")

    # Try importing progressively smaller module paths
    for i in range(len(parts), 0, -1):
        try:
            # Try current module path
            module_path = ".".join(parts[:i])
            module = importlib.import_module(module_path)

            # Walk remaining parts as attributes
            obj = module
            for part in parts[i:]:
                obj = getattr(obj, part)

            # Check if we got a callable
            if callable(obj):
                return obj

            msg = f"Found object at {path} but it isn't callable"
            raise ValueError(msg)

        except ImportError:
            # Try next shorter path
            continue
        except AttributeError:
            # Attribute not found - try next shorter path
            continue

    # If we get here, no import combination worked
    msg = f"Could not import callable from path: {path}"
    raise ValueError(msg)

import_class

import_class(path: str) -> type

Import a class from a dotted path.

Parameters:

Name Type Description Default
path str

Dot-separated path to the class

required

Returns:

Type Description
type

The imported class

Raises:

Type Description
ValueError

If path is invalid or doesn't point to a class

Source code in src/llmling/utils/importing.py
def import_class(path: str) -> type:
    """Import a class from a dotted path.

    Args:
        path: Dot-separated path to the class

    Returns:
        The imported class

    Raises:
        ValueError: If path is invalid or doesn't point to a class
    """
    try:
        obj = import_callable(path)
        if not isinstance(obj, type):
            msg = f"{path} is not a class"
            raise TypeError(msg)  # noqa: TRY301
    except Exception as exc:
        msg = f"Failed to import class from {path}"
        raise ValueError(msg) from exc
    else:
        return obj