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_agent/utils/importing.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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_agent/utils/importing.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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_agent/utils/importing.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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_agent/utils/importing.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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