Coverage for core / src / sensorkit / common / importutil.py: 100%

51 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Utilities for dynamic module loading and object resolution from string specifiers.""" 

3 

4import importlib 

5import importlib.util 

6import inspect 

7import pathlib 

8import sys 

9from importlib.machinery import ModuleSpec 

10from types import ModuleType 

11 

12 

13def get_caller_module(*, depth: int): 

14 """Retrieves the module of the calling function at the specified stack depth.""" 

15 # Account for the direct caller frame. 

16 depth += 1 

17 

18 # Find the requested module by inspecting the call stack. 

19 stack = inspect.stack() 

20 

21 if len(stack) <= depth: 

22 return None 

23 

24 frame = stack[depth][0] 

25 module = inspect.getmodule(frame) 

26 

27 return module 

28 

29 

30def module_from_file(path: pathlib.Path, name: str): 

31 """Load a Python file with its directory temporarily on the import path.""" 

32 # Dynamic load boilerplate. 

33 spec = importlib.util.spec_from_file_location(name, path) 

34 module = importlib.util.module_from_spec(spec) 

35 

36 # Temporarily allow imports of sibling modules from the file's directory. 

37 sys.path.append(str(path.parent)) 

38 

39 try: 

40 # Evaluate the module code. 

41 spec.loader.exec_module(module) 

42 except Exception as e: 

43 # Wrap the exception so a downstream ModuleNotFoundError won't confuse things. 

44 raise ImportError from e 

45 finally: 

46 # Restore sys.path even if import fails. 

47 sys.path.pop() 

48 

49 return module 

50 

51 

52def import_module_or_file(name: str): 

53 """Import a module by name or load a file with access to sibling modules. 

54 

55 Importing the same path again returns the already loaded module. 

56 """ 

57 path = pathlib.Path(name) 

58 

59 if path.exists(): 

60 match sys.modules.get(path.stem): 

61 case ModuleType(__spec__=ModuleSpec(origin=str(origin))) as module if ( 

62 pathlib.Path(origin).resolve() == path.resolve() 

63 ): 

64 return module 

65 

66 module = module_from_file(path, path.stem) 

67 sys.modules[path.stem] = module 

68 return module 

69 

70 return importlib.import_module(name) 

71 

72 

73def obj_from_spec[T]( 

74 *, 

75 spec: str, 

76 base: type[T], 

77 subclass: bool = False, 

78 load_file: bool = False, 

79) -> T: 

80 """Find and return an object of a given type based on a string specifier.""" 

81 module_name, sep, obj_name = spec.rpartition(":") 

82 

83 if not sep: 

84 module_name = spec 

85 obj_name = None 

86 

87 module = ( 

88 import_module_or_file(module_name) 

89 if load_file 

90 else importlib.import_module(module_name) 

91 ) 

92 haystack = [obj_name] if obj_name else dir(module) 

93 

94 for symbol in haystack: 

95 obj = getattr(module, symbol) 

96 

97 if subclass: 

98 if isinstance(obj, type) and obj is not base and issubclass(obj, base): 

99 return obj 

100 elif isinstance(obj, base): 

101 return obj 

102 

103 kind = "subclass" if subclass else "instance" 

104 raise ValueError(f"no {base.__name__} {kind} matching spec found in {module_name}")