Chad Van De Hey
Chad Van De Hey

Reputation: 2911

AWS Lambda: Unable to import module 'package/file': No module named 'util'

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!

Upvotes: 2

Views: 5575

Answers (2)

serp-ya
serp-ya

Reputation: 11

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

# package.py
from .util.helper1 import foo

Upvotes: 1

Chad Van De Hey
Chad Van De Hey

Reputation: 2911

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.

Upvotes: 4

Related Questions