2

I am struggling to get module importing to work in AWS lambda using Python 3.

My file structure looks like this:

package:
  stage1.py
  __init__.py
  util:
    helper1.py
    __init__.py

helper1.py is a simple util class:

def foo():
  print("yes")

Within stage1.py I have the following lines that cause Lambda to throw an error when it is starting:

from util.helper1 import foo
foo()
Unable to import module 'package/stage1': No module named 'util'

Both __init__.py files are empty.

Sadly, I see that this works if I invoke the script locally. Frustrating is an understatement!

martineau
  • 119,623
  • 25
  • 170
  • 301
Chad Van De Hey
  • 2,716
  • 3
  • 29
  • 46
  • `stage1.py` is being called by a handler in AWS Lambda – Chad Van De Hey Nov 15 '18 at 01:41
  • Invoking scripts a **within** a package like it was a standalone often doesn't work. [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) might be helpful (it has a lot of information on how packages work). – martineau Nov 15 '18 at 03:05
  • As you mentioned the directory structure, I created the same on the Lambda and it is working file. Can you please update the question with the screenshot of the directory structure in lambda? – Srce Cde Nov 15 '18 at 14:19

2 Answers2

4

Thanks to some of the links sent above and my own (and necessary) research into how imports are handled in python, I figured out the issue regarding unavailable modules.

How I debugged my app in Lambda: I attached this line of code to the top of the file

print("Name is ({})".format(__name__))

This gave me an output that could help me understand an make an educated decision on how to import the files in the util module. I saw an output for the stage1.py file was packager/stage1. This made the import code modifications easy to make. I changed the imports in the stage1.py file to (using absolute path imports -- pep recommendation):

from packager.util.helper1 import foo

For whatever subjective reason, this link helped me understand the process the most.

Chad Van De Hey
  • 2,716
  • 3
  • 29
  • 46
1

I avoided this issue using a leading dot in the path like this

# package.py
from .util.helper1 import foo
Dharman
  • 30,962
  • 25
  • 85
  • 135
serp-ya
  • 11
  • 1