Python Forum

Full Version: Correct way to import from a standalone module in a different location
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone.

I have the following setup:
  • 3 separate AWS Lambda functions, written in Python
  • A small Flask app to test and run the lambda functions locally

The 3 Lambda functions are standalone modules with their requirements pip installed in their folders.
The Flask app is a single app.py file.

Here is the directory structure.
Output:
└── MyProject ├── lambda1 ..folders of libraries like lxml, requests etc... ├── handler.py └── __init__.py ├── lambda2 ..folders of libraries like lxml, requests etc... ├── handler.py └── __init__.py ├── lambda3 ..folders of libraries like lxml, requests etc... ├── handler.py └── __init__.py ├── app.py └── __init__.py
I am trying to import a function from each lambda file, to be used in the Flask app. I do it like so:
from lambda1.handler import some_function
In each lambda file I have an import statement like:
from some_file import something #  This is inside the lambda folder
Whenever I try to run the Flask app I get the following error:
Error:
File "../lambda1/handler.py", line 7, in <module> from some_file import something ModuleNotFoundError: No module named 'some_file'
The question is: How can I import a function from a standalone, separate module I am working on?

Thanks Exclamation

I think I just solved this myself...
I had to change the import to:
from .some_file import something #  This is inside the lambda folder
I spent so much time trying different things! So simple at the end.
import sys
sys.path.append("/the_path_to_your_module/")
As I mentioned above in the Edit I changed the import to have a "." in the beginning. This fixed the Flask app.
The problem now is that if I want to run the lambda separately I get the following error:
Error:
ModuleNotFoundError: No module named '__main__.some_file'; '__main__' is not a package
I have an __init__.py in each Lambda folder.

@wavic, your suggestion worked. I did this for all 3 lambda folders.
you need a top level __init__.py module, which has to be populated with the data structure of dependencies.
It will look a lot like your ' Here is the directory structure. '
ex (partial):
MyProject/
    lambda1/
        handler.py
        ...
    lambda2/
    ...