3

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?

Dan
  • 1,249
  • 2
  • 16
  • 31
  • 1
    Please try `from mymodule import ...` **without dot** before mymodule. Ref: https://stackoverflow.com/Questions/16981921/relative-imports-in-python-3 – shimo Oct 06 '21 at 22:49
  • It then fails with "Unable to import module 'app': No module named 'mymodule'". Have also tried all the sys.path.append() ideas in that answer without any luck. – Dan Oct 07 '21 at 05:35

1 Answers1

1

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

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

kib gabriel
  • 108
  • 7