Dan
Dan

Reputation: 1401

AWS Lambda Python - How to import modules from local files to app.py

This is a simple SAM-template based deploy with a Docker container. Filesystem structure:

src/app.py
    mymodule.py

In app.py:

from .mymodule import myfunction

Result (on invoke):

Unable to import module 'app': attempted relative import with no known parent package

Removing the dot results in:

Unable to import module 'app': No module named 'mymodule'

Adding the local directory to path does not help either:

import os, sys
currentdir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(currentdir)

Now I guess this appears to be due to the limitations described in the great answer from Relative imports for the billionth time

i.e. app.py is being run as a script, not a module, and scripts cannot import relatively

The workarounds in the above answer both require changing some way the Lambda function is built and/or invoked - how to do this is the question?

Upvotes: 4

Views: 2880

Answers (1)

kib gabriel
kib gabriel

Reputation: 138

Add __init__.py file to your src/ folder (same level as your app.py)

Or if you are using a container, make sure your Dockerfile copies everything and not just app.py

Upvotes: 2

Related Questions