1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
|
"""Compatibility utilities for module loading.
This module provides utilities for loading Python modules safely,
including mock handling for imports that may fail during documentation
builds.
Unlike sphinx-argparse, this module does NOT depend on autodoc's mock
functionality, which moved in Sphinx 9.x.
"""
from __future__ import annotations
import contextlib
import importlib
import sys
import typing as t
if t.TYPE_CHECKING:
import argparse
from collections.abc import Iterator
class MockModule:
"""Simple mock for unavailable imports.
This class provides a minimal mock that can be used as a placeholder
for modules that aren't available during documentation builds.
Parameters
----------
name : str
The module name being mocked.
Examples
--------
>>> mock = MockModule("mypackage.submodule")
>>> mock.__name__
'mypackage.submodule'
>>> child = mock.child_attr
>>> child.__name__
'mypackage.submodule.child_attr'
>>> callable(mock.some_function)
True
>>> mock.some_function()
<MockModule: mypackage.submodule.some_function>
"""
def __init__(self, name: str) -> None:
"""Initialize the mock module."""
self.__name__ = name
self._name = name
def __repr__(self) -> str:
"""Return string representation."""
return f"<MockModule: {self._name}>"
def __getattr__(self, name: str) -> MockModule:
"""Return a child mock for any attribute access.
Parameters
----------
name : str
The attribute name.
Returns
-------
MockModule
A new mock for the child attribute.
"""
return MockModule(f"{self._name}.{name}")
def __call__(self, *args: t.Any, **kwargs: t.Any) -> MockModule:
"""Return self when called as a function.
Parameters
----------
*args : t.Any
Positional arguments (ignored).
**kwargs : t.Any
Keyword arguments (ignored).
Returns
-------
MockModule
Self.
"""
return self
@contextlib.contextmanager
def mock_imports(modules: list[str]) -> Iterator[None]:
"""Context manager to mock missing imports.
This provides a simple way to temporarily add mock modules to
sys.modules, allowing imports to succeed during documentation builds
even when the actual modules aren't available.
Parameters
----------
modules : list[str]
List of module names to mock.
Yields
------
None
Context manager yields nothing.
Examples
--------
>>> import sys
>>> "fake_module" in sys.modules
False
>>> with mock_imports(["fake_module", "fake_module.sub"]):
... import fake_module
... fake_module.__name__
'fake_module'
>>> "fake_module" in sys.modules
False
"""
mocked: dict[str, MockModule] = {}
for name in modules:
if name not in sys.modules:
mocked[name] = MockModule(name)
sys.modules[name] = mocked[name] # type: ignore[assignment]
try:
yield
finally:
for name in mocked:
del sys.modules[name]
def import_module(module_name: str) -> t.Any:
"""Import a module by name.
Parameters
----------
module_name : str
The fully qualified module name.
Returns
-------
t.Any
The imported module.
Raises
------
ImportError
If the module cannot be imported.
Examples
--------
>>> mod = import_module("argparse")
>>> hasattr(mod, "ArgumentParser")
True
"""
return importlib.import_module(module_name)
def get_parser_from_module(
module_name: str,
func_name: str,
mock_modules: list[str] | None = None,
) -> argparse.ArgumentParser:
"""Import a module and call a function to get an ArgumentParser.
Parameters
----------
module_name : str
The module containing the parser factory function.
func_name : str
The name of the function that returns an ArgumentParser.
Can be a dotted path like "Class.method".
mock_modules : list[str] | None
Optional list of module names to mock during import.
Returns
-------
argparse.ArgumentParser
The argument parser returned by the function.
Raises
------
ImportError
If the module cannot be imported.
AttributeError
If the function is not found.
TypeError
If the function doesn't return an ArgumentParser.
Examples
--------
Load tmuxp's parser factory:
>>> parser = get_parser_from_module("tmuxp.cli", "create_parser")
>>> parser.prog
'tmuxp'
>>> hasattr(parser, 'parse_args')
True
"""
ctx = mock_imports(mock_modules) if mock_modules else contextlib.nullcontext()
with ctx:
module = import_module(module_name)
# Handle dotted paths like "Class.method"
obj = module
for part in func_name.split("."):
obj = getattr(obj, part)
# Call the function if it's callable
parser = obj() if callable(obj) else obj
# Validate the return type at runtime
import argparse as argparse_module
if not isinstance(parser, argparse_module.ArgumentParser):
msg = (
f"{module_name}:{func_name} returned {type(parser).__name__}, "
f"expected ArgumentParser"
)
raise TypeError(msg)
return parser
def get_parser_from_entry_point(
entry_point: str,
mock_modules: list[str] | None = None,
) -> argparse.ArgumentParser:
"""Get an ArgumentParser from a setuptools-style entry point string.
Parameters
----------
entry_point : str
Entry point in the format "module:function" or "module:Class.method".
mock_modules : list[str] | None
Optional list of module names to mock during import.
Returns
-------
argparse.ArgumentParser
The argument parser.
Raises
------
ValueError
If the entry point format is invalid.
Examples
--------
Load tmuxp's parser using entry point syntax:
>>> parser = get_parser_from_entry_point("tmuxp.cli:create_parser")
>>> parser.prog
'tmuxp'
Invalid format raises ValueError:
>>> get_parser_from_entry_point("no_colon")
Traceback (most recent call last):
...
ValueError: Invalid entry point format: 'no_colon'. Expected 'module:function'
"""
if ":" not in entry_point:
msg = f"Invalid entry point format: {entry_point!r}. Expected 'module:function'"
raise ValueError(msg)
module_name, func_name = entry_point.split(":", 1)
return get_parser_from_module(module_name, func_name, mock_modules)
|