Unable to Import Lambda Function Module: No module named 'lambda_function'

0

I'm encountering an issue with deploying a Python-based AWS Lambda function. Despite following various troubleshooting steps, I'm consistently getting the error message "Unable to import module 'lambda_function': No module named 'lambda_function'" when testing the Lambda function in the AWS Lambda console.

"lambda_function.py" is located in the same directory (lambda_package) in the ZIP file (lambda_package.zip), along with the required packages like below.

lambda_package/
├── lambda_function.py
├── pyotp
│   ├── ...
├── pyotp-2.9.0.dist-info
│   ├── ...
├── python_dotenv-1.0.1.dist-info
│   ├── ...
├── requests
│   ├── ...
├── requests-2.31.0.dist-info
│   ├── ...

In my AWS SAM template, the handler configuration for the Lambda function is specified as lambda_function.lambda_handler.

The lambda_function.py script looks like this:

import pyotp
import os

def lambda_handler(event, context):
    # Code here

Despite ensuring that the file name, ZIP structure, and handler configuration are correct, I'm still encountering this import error. I've tried redeploying the function multiple times but getting the same error like this: "[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_function': No module named 'lambda_function' Traceback (most recent call last):"

Any insights or suggestions would be greatly appreciated.

YLee
asked 3 months ago312 views
1 Answer
1
Accepted Answer

The structure you provided seems correct, but it's worth double-checking that lambda_function.py is indeed at the root of the ZIP archive and not inside another folder. The structure inside the ZIP should not have lambda_package as a top-level directory. If you open the ZIP file, you should immediately see lambda_function.py and the directories for your dependencies, like so:

lambda_function.py
pyotp/
pyotp-2.9.0.dist-info/
python_dotenv-1.0.1.dist-info/
requests/
requests-2.31.0.dist-info/

Use the following command from the directory containing lambda_function.py and the dependency directories:

zip -r9 ../lambda_package.zip .

If this has answered your question or was helpful, accepting the answer would be greatly appreciated. Thank you!

profile picture
EXPERT
answered 3 months ago
profile picture
EXPERT
reviewed a month ago
  • Thanks for the suggestion. I have a correct zip file with the structure you mentioned. Somehow my previous lambda session did not save the function I was testing, while I was on lunch break, so I had to re-create my lambda function again. This time, I did not get the same error (even with the same zip file). Since your suggestion is correct, I will take your suggestion as an answer.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions