Import an object from a module.
PARAMETER | DESCRIPTION |
module | The path to the module file. TYPE: Path |
app | The name of the object to import. TYPE: str |
Source code in faststream/cli/utils/imports.py
| def import_object(module: Path, app: str) -> object:
"""Import an object from a module.
Args:
module: The path to the module file.
app: The name of the object to import.
Returns:
The imported object.
Raises:
FileNotFoundError: If the module file is not found.
ValueError: If the module has no loader.
AttributeError: If the object is not found in the module.
"""
spec = spec_from_file_location(
"mode",
f"{module}.py",
submodule_search_locations=[str(module.parent.absolute())],
)
if spec is None: # pragma: no cover
raise FileNotFoundError(module)
mod = module_from_spec(spec)
loader = spec.loader
if loader is None: # pragma: no cover
raise ValueError(f"{spec} has no loader")
loader.exec_module(mod)
try:
obj = getattr(mod, app)
except AttributeError as e:
raise FileNotFoundError(module) from e
return obj
|