Imports in a file imported by location generate ModuleNotFoundError

34 Views Asked by At

(old title: Resolve ModuleNotFoundError on import from module imported by file name)

I have the following project structure

. Root
|--lambdas/
|   |-- lambda-1/
|       |-- lambda_function.py
|       |-- lambda_context.py
|-- tests
    | -- unit
        |-- test_my_lambda.py

lambda_function.py imports from lambda_conext.py, as such

from lambda_context import SomeClass
from lambda_context import function_xyz

I import lambda_function into test_my_lambda.py:

spec = importlib.util.spec_from_file_location("lambda_function", ansolute_path_to_lambda_function/lambda_function.py)
module_name = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module_name)

I run pytest with:

c:\path_to_project_root\tests> python -m pytest unit\test_my_lambda.py

pytest fails with:

..\lambdas\lambda-1\lambda_function.py:14: in <module>
    from lambda_context import SomeClass
E   ModuleNotFoundError: No module named 'lambda_context'

How do I resolve this error?

1

There are 1 best solutions below

0
JayCravens On

Import the path, I believe.

import sys

sys.path.insert(0, '../../../lambda/lambda-1')