DEV Community

Cover image for ImportError in AWS Lambda function
Tobias Haindl
Tobias Haindl

Posted on

2 1

ImportError in AWS Lambda function

I recently stumbled across an import error when deploying an AWS lambda function via SAM.

I used the following folder structure:

src/lambda.py
template.yml
Enter fullscreen mode Exit fullscreen mode

Lambda.py:

def lambda_handler(event, context):
    print('hello world')
Enter fullscreen mode Exit fullscreen mode

Template.yml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  Lambda:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src.lambda.lambda_handler
      Runtime: python3.8
      Events:
        SchedulingEvent:
          Type: Schedule
          Properties:
            Schedule: rate(5 minutes)
Enter fullscreen mode Exit fullscreen mode

Once deployed, the following error was raised:

Runtime.ImportModuleError: Unable to import module 'src.lambda': No module named 'src'
Enter fullscreen mode Exit fullscreen mode

Since I copied the template and the lambda code from another project I was really baffled why I didn't work out of the box. Then I realized the little __init__.py was missing in the source folder...

Don't forget to add an empty __init__.py file to the src folder if you use the same project structure!
If you set Handler to src.lambda in your template.yml the lambda environment is looking for a python module called src therefore a __init__.py is required.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay